es6.js 4.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180
  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. * Resets the cache of effects.
  1161. */
  1162. Effect.ResetCache = function () {
  1163. Effect._baseCache = {};
  1164. };
  1165. Effect._uniqueIdSeed = 0;
  1166. Effect._baseCache = {};
  1167. // Statics
  1168. /**
  1169. * Store of each shader (The can be looked up using effect.key)
  1170. */
  1171. Effect.ShadersStore = {};
  1172. /**
  1173. * Store of each included file for a shader (The can be looked up using effect.key)
  1174. */
  1175. Effect.IncludesShadersStore = {};
  1176. return Effect;
  1177. }());
  1178. BABYLON.Effect = Effect;
  1179. })(BABYLON || (BABYLON = {}));
  1180. //# sourceMappingURL=babylon.effect.js.map
  1181. //# sourceMappingURL=babylon.types.js.map
  1182. var BABYLON;
  1183. (function (BABYLON) {
  1184. var KeyboardEventTypes = /** @class */ (function () {
  1185. function KeyboardEventTypes() {
  1186. }
  1187. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1188. get: function () {
  1189. return KeyboardEventTypes._KEYDOWN;
  1190. },
  1191. enumerable: true,
  1192. configurable: true
  1193. });
  1194. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1195. get: function () {
  1196. return KeyboardEventTypes._KEYUP;
  1197. },
  1198. enumerable: true,
  1199. configurable: true
  1200. });
  1201. KeyboardEventTypes._KEYDOWN = 0x01;
  1202. KeyboardEventTypes._KEYUP = 0x02;
  1203. return KeyboardEventTypes;
  1204. }());
  1205. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1206. var KeyboardInfo = /** @class */ (function () {
  1207. function KeyboardInfo(type, event) {
  1208. this.type = type;
  1209. this.event = event;
  1210. }
  1211. return KeyboardInfo;
  1212. }());
  1213. BABYLON.KeyboardInfo = KeyboardInfo;
  1214. /**
  1215. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1216. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1217. */
  1218. var KeyboardInfoPre = /** @class */ (function (_super) {
  1219. __extends(KeyboardInfoPre, _super);
  1220. function KeyboardInfoPre(type, event) {
  1221. var _this = _super.call(this, type, event) || this;
  1222. _this.skipOnPointerObservable = false;
  1223. return _this;
  1224. }
  1225. return KeyboardInfoPre;
  1226. }(KeyboardInfo));
  1227. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1228. })(BABYLON || (BABYLON = {}));
  1229. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1230. var BABYLON;
  1231. (function (BABYLON) {
  1232. var PointerEventTypes = /** @class */ (function () {
  1233. function PointerEventTypes() {
  1234. }
  1235. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1236. get: function () {
  1237. return PointerEventTypes._POINTERDOWN;
  1238. },
  1239. enumerable: true,
  1240. configurable: true
  1241. });
  1242. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1243. get: function () {
  1244. return PointerEventTypes._POINTERUP;
  1245. },
  1246. enumerable: true,
  1247. configurable: true
  1248. });
  1249. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1250. get: function () {
  1251. return PointerEventTypes._POINTERMOVE;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1257. get: function () {
  1258. return PointerEventTypes._POINTERWHEEL;
  1259. },
  1260. enumerable: true,
  1261. configurable: true
  1262. });
  1263. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1264. get: function () {
  1265. return PointerEventTypes._POINTERPICK;
  1266. },
  1267. enumerable: true,
  1268. configurable: true
  1269. });
  1270. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1271. get: function () {
  1272. return PointerEventTypes._POINTERTAP;
  1273. },
  1274. enumerable: true,
  1275. configurable: true
  1276. });
  1277. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1278. get: function () {
  1279. return PointerEventTypes._POINTERDOUBLETAP;
  1280. },
  1281. enumerable: true,
  1282. configurable: true
  1283. });
  1284. PointerEventTypes._POINTERDOWN = 0x01;
  1285. PointerEventTypes._POINTERUP = 0x02;
  1286. PointerEventTypes._POINTERMOVE = 0x04;
  1287. PointerEventTypes._POINTERWHEEL = 0x08;
  1288. PointerEventTypes._POINTERPICK = 0x10;
  1289. PointerEventTypes._POINTERTAP = 0x20;
  1290. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1291. return PointerEventTypes;
  1292. }());
  1293. BABYLON.PointerEventTypes = PointerEventTypes;
  1294. var PointerInfoBase = /** @class */ (function () {
  1295. function PointerInfoBase(type, event) {
  1296. this.type = type;
  1297. this.event = event;
  1298. }
  1299. return PointerInfoBase;
  1300. }());
  1301. BABYLON.PointerInfoBase = PointerInfoBase;
  1302. /**
  1303. * This class is used to store pointer related info for the onPrePointerObservable event.
  1304. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1305. */
  1306. var PointerInfoPre = /** @class */ (function (_super) {
  1307. __extends(PointerInfoPre, _super);
  1308. function PointerInfoPre(type, event, localX, localY) {
  1309. var _this = _super.call(this, type, event) || this;
  1310. _this.skipOnPointerObservable = false;
  1311. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1312. return _this;
  1313. }
  1314. return PointerInfoPre;
  1315. }(PointerInfoBase));
  1316. BABYLON.PointerInfoPre = PointerInfoPre;
  1317. /**
  1318. * This type contains all the data related to a pointer event in Babylon.js.
  1319. * 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.
  1320. */
  1321. var PointerInfo = /** @class */ (function (_super) {
  1322. __extends(PointerInfo, _super);
  1323. function PointerInfo(type, event, pickInfo) {
  1324. var _this = _super.call(this, type, event) || this;
  1325. _this.pickInfo = pickInfo;
  1326. return _this;
  1327. }
  1328. return PointerInfo;
  1329. }(PointerInfoBase));
  1330. BABYLON.PointerInfo = PointerInfo;
  1331. })(BABYLON || (BABYLON = {}));
  1332. //# sourceMappingURL=babylon.pointerEvents.js.map
  1333. var BABYLON;
  1334. (function (BABYLON) {
  1335. BABYLON.ToGammaSpace = 1 / 2.2;
  1336. BABYLON.ToLinearSpace = 2.2;
  1337. BABYLON.Epsilon = 0.001;
  1338. /**
  1339. * Class used to hold a RBG color
  1340. */
  1341. var Color3 = /** @class */ (function () {
  1342. /**
  1343. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1344. * @param r defines the red component (between 0 and 1, default is 0)
  1345. * @param g defines the green component (between 0 and 1, default is 0)
  1346. * @param b defines the blue component (between 0 and 1, default is 0)
  1347. */
  1348. function Color3(
  1349. /**
  1350. * Defines the red component (between 0 and 1, default is 0)
  1351. */
  1352. r,
  1353. /**
  1354. * Defines the green component (between 0 and 1, default is 0)
  1355. */
  1356. g,
  1357. /**
  1358. * Defines the blue component (between 0 and 1, default is 0)
  1359. */
  1360. b) {
  1361. if (r === void 0) { r = 0; }
  1362. if (g === void 0) { g = 0; }
  1363. if (b === void 0) { b = 0; }
  1364. this.r = r;
  1365. this.g = g;
  1366. this.b = b;
  1367. }
  1368. /**
  1369. * Creates a string with the Color3 current values
  1370. * @returns the string representation of the Color3 object
  1371. */
  1372. Color3.prototype.toString = function () {
  1373. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1374. };
  1375. /**
  1376. * Returns the string "Color3"
  1377. * @returns "Color3"
  1378. */
  1379. Color3.prototype.getClassName = function () {
  1380. return "Color3";
  1381. };
  1382. /**
  1383. * Compute the Color3 hash code
  1384. * @returns an unique number that can be used to hash Color3 objects
  1385. */
  1386. Color3.prototype.getHashCode = function () {
  1387. var hash = this.r || 0;
  1388. hash = (hash * 397) ^ (this.g || 0);
  1389. hash = (hash * 397) ^ (this.b || 0);
  1390. return hash;
  1391. };
  1392. // Operators
  1393. /**
  1394. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1395. * @param array defines the array where to store the r,g,b components
  1396. * @param index defines an optional index in the target array to define where to start storing values
  1397. * @returns the current Color3 object
  1398. */
  1399. Color3.prototype.toArray = function (array, index) {
  1400. if (index === undefined) {
  1401. index = 0;
  1402. }
  1403. array[index] = this.r;
  1404. array[index + 1] = this.g;
  1405. array[index + 2] = this.b;
  1406. return this;
  1407. };
  1408. /**
  1409. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1410. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1411. * @returns a new {BABYLON.Color4} object
  1412. */
  1413. Color3.prototype.toColor4 = function (alpha) {
  1414. if (alpha === void 0) { alpha = 1; }
  1415. return new Color4(this.r, this.g, this.b, alpha);
  1416. };
  1417. /**
  1418. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1419. * @returns the new array
  1420. */
  1421. Color3.prototype.asArray = function () {
  1422. var result = new Array();
  1423. this.toArray(result, 0);
  1424. return result;
  1425. };
  1426. /**
  1427. * Returns the luminance value
  1428. * @returns a float value
  1429. */
  1430. Color3.prototype.toLuminance = function () {
  1431. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1432. };
  1433. /**
  1434. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1435. * @param otherColor defines the second operand
  1436. * @returns the new Color3 object
  1437. */
  1438. Color3.prototype.multiply = function (otherColor) {
  1439. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1440. };
  1441. /**
  1442. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1443. * @param otherColor defines the second operand
  1444. * @param result defines the Color3 object where to store the result
  1445. * @returns the current Color3
  1446. */
  1447. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1448. result.r = this.r * otherColor.r;
  1449. result.g = this.g * otherColor.g;
  1450. result.b = this.b * otherColor.b;
  1451. return this;
  1452. };
  1453. /**
  1454. * Determines equality between Color3 objects
  1455. * @param otherColor defines the second operand
  1456. * @returns true if the rgb values are equal to the passed ones
  1457. */
  1458. Color3.prototype.equals = function (otherColor) {
  1459. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1460. };
  1461. /**
  1462. * Determines equality between the current Color3 object and a set of r,b,g values
  1463. * @param r defines the red component to check
  1464. * @param g defines the green component to check
  1465. * @param b defines the blue component to check
  1466. * @returns true if the rgb values are equal to the passed ones
  1467. */
  1468. Color3.prototype.equalsFloats = function (r, g, b) {
  1469. return this.r === r && this.g === g && this.b === b;
  1470. };
  1471. /**
  1472. * Multiplies in place each rgb value by scale
  1473. * @param scale defines the scaling factor
  1474. * @returns the updated Color3.
  1475. */
  1476. Color3.prototype.scale = function (scale) {
  1477. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1478. };
  1479. /**
  1480. * Multiplies the rgb values by scale and stores the result into "result"
  1481. * @param scale defines the scaling factor
  1482. * @param result defines the Color3 object where to store the result
  1483. * @returns the unmodified current Color3.
  1484. */
  1485. Color3.prototype.scaleToRef = function (scale, result) {
  1486. result.r = this.r * scale;
  1487. result.g = this.g * scale;
  1488. result.b = this.b * scale;
  1489. return this;
  1490. };
  1491. /**
  1492. * Clamps the rgb values by the min and max values and stores the result into "result"
  1493. * @param min defines minimum clamping value (default is 0)
  1494. * @param max defines maximum clamping value (default is 1)
  1495. * @param result defines color to store the result into
  1496. * @returns the original Color3
  1497. */
  1498. Color3.prototype.clampToRef = function (min, max, result) {
  1499. if (min === void 0) { min = 0; }
  1500. if (max === void 0) { max = 1; }
  1501. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1502. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1503. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1504. return this;
  1505. };
  1506. /**
  1507. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1508. * @param otherColor defines the second operand
  1509. * @returns the new Color3
  1510. */
  1511. Color3.prototype.add = function (otherColor) {
  1512. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1513. };
  1514. /**
  1515. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1516. * @param otherColor defines the second operand
  1517. * @param result defines Color3 object to store the result into
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.addToRef = function (otherColor, result) {
  1521. result.r = this.r + otherColor.r;
  1522. result.g = this.g + otherColor.g;
  1523. result.b = this.b + otherColor.b;
  1524. return this;
  1525. };
  1526. /**
  1527. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1528. * @param otherColor defines the second operand
  1529. * @returns the new Color3
  1530. */
  1531. Color3.prototype.subtract = function (otherColor) {
  1532. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1533. };
  1534. /**
  1535. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1536. * @param otherColor defines the second operand
  1537. * @param result defines Color3 object to store the result into
  1538. * @returns the unmodified current Color3
  1539. */
  1540. Color3.prototype.subtractToRef = function (otherColor, result) {
  1541. result.r = this.r - otherColor.r;
  1542. result.g = this.g - otherColor.g;
  1543. result.b = this.b - otherColor.b;
  1544. return this;
  1545. };
  1546. /**
  1547. * Copy the current object
  1548. * @returns a new Color3 copied the current one
  1549. */
  1550. Color3.prototype.clone = function () {
  1551. return new Color3(this.r, this.g, this.b);
  1552. };
  1553. /**
  1554. * Copies the rgb values from the source in the current Color3
  1555. * @param source defines the source Color3 object
  1556. * @returns the updated Color3 object
  1557. */
  1558. Color3.prototype.copyFrom = function (source) {
  1559. this.r = source.r;
  1560. this.g = source.g;
  1561. this.b = source.b;
  1562. return this;
  1563. };
  1564. /**
  1565. * Updates the Color3 rgb values from the passed floats
  1566. * @param r defines the red component to read from
  1567. * @param g defines the green component to read from
  1568. * @param b defines the blue component to read from
  1569. * @returns the current Color3 object
  1570. */
  1571. Color3.prototype.copyFromFloats = function (r, g, b) {
  1572. this.r = r;
  1573. this.g = g;
  1574. this.b = b;
  1575. return this;
  1576. };
  1577. /**
  1578. * Updates the Color3 rgb values from the passed floats
  1579. * @param r defines the red component to read from
  1580. * @param g defines the green component to read from
  1581. * @param b defines the blue component to read from
  1582. * @returns the current Color3 object
  1583. */
  1584. Color3.prototype.set = function (r, g, b) {
  1585. return this.copyFromFloats(r, g, b);
  1586. };
  1587. /**
  1588. * Compute the Color3 hexadecimal code as a string
  1589. * @returns a string containing the hexadecimal representation of the Color3 object
  1590. */
  1591. Color3.prototype.toHexString = function () {
  1592. var intR = (this.r * 255) | 0;
  1593. var intG = (this.g * 255) | 0;
  1594. var intB = (this.b * 255) | 0;
  1595. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1596. };
  1597. /**
  1598. * Computes a new Color3 converted from the current one to linear space
  1599. * @returns a new Color3 object
  1600. */
  1601. Color3.prototype.toLinearSpace = function () {
  1602. var convertedColor = new Color3();
  1603. this.toLinearSpaceToRef(convertedColor);
  1604. return convertedColor;
  1605. };
  1606. /**
  1607. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1608. * @param convertedColor defines the Color3 object where to store the linear space version
  1609. * @returns the unmodified Color3
  1610. */
  1611. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1612. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1613. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1614. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1615. return this;
  1616. };
  1617. /**
  1618. * Computes a new Color3 converted from the current one to gamma space
  1619. * @returns a new Color3 object
  1620. */
  1621. Color3.prototype.toGammaSpace = function () {
  1622. var convertedColor = new Color3();
  1623. this.toGammaSpaceToRef(convertedColor);
  1624. return convertedColor;
  1625. };
  1626. /**
  1627. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1628. * @param convertedColor defines the Color3 object where to store the gamma space version
  1629. * @returns the unmodified Color3
  1630. */
  1631. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1632. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1633. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1634. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1635. return this;
  1636. };
  1637. // Statics
  1638. /**
  1639. * Creates a new Color3 from the string containing valid hexadecimal values
  1640. * @param hex defines a string containing valid hexadecimal values
  1641. * @returns a new Color3 object
  1642. */
  1643. Color3.FromHexString = function (hex) {
  1644. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1645. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1646. return new Color3(0, 0, 0);
  1647. }
  1648. var r = parseInt(hex.substring(1, 3), 16);
  1649. var g = parseInt(hex.substring(3, 5), 16);
  1650. var b = parseInt(hex.substring(5, 7), 16);
  1651. return Color3.FromInts(r, g, b);
  1652. };
  1653. /**
  1654. * Creates a new Vector3 from the starting index of the passed array
  1655. * @param array defines the source array
  1656. * @param offset defines an offset in the source array
  1657. * @returns a new Color3 object
  1658. */
  1659. Color3.FromArray = function (array, offset) {
  1660. if (offset === void 0) { offset = 0; }
  1661. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1662. };
  1663. /**
  1664. * Creates a new Color3 from integer values (< 256)
  1665. * @param r defines the red component to read from (value between 0 and 255)
  1666. * @param g defines the green component to read from (value between 0 and 255)
  1667. * @param b defines the blue component to read from (value between 0 and 255)
  1668. * @returns a new Color3 object
  1669. */
  1670. Color3.FromInts = function (r, g, b) {
  1671. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1672. };
  1673. /**
  1674. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1675. * @param start defines the start Color3 value
  1676. * @param end defines the end Color3 value
  1677. * @param amount defines the gradient value between start and end
  1678. * @returns a new Color3 object
  1679. */
  1680. Color3.Lerp = function (start, end, amount) {
  1681. var r = start.r + ((end.r - start.r) * amount);
  1682. var g = start.g + ((end.g - start.g) * amount);
  1683. var b = start.b + ((end.b - start.b) * amount);
  1684. return new Color3(r, g, b);
  1685. };
  1686. /**
  1687. * Returns a Color3 value containing a red color
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.Red = function () { return new Color3(1, 0, 0); };
  1691. /**
  1692. * Returns a Color3 value containing a green color
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.Green = function () { return new Color3(0, 1, 0); };
  1696. /**
  1697. * Returns a Color3 value containing a blue color
  1698. * @returns a new Color3 object
  1699. */
  1700. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1701. /**
  1702. * Returns a Color3 value containing a black color
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.Black = function () { return new Color3(0, 0, 0); };
  1706. /**
  1707. * Returns a Color3 value containing a white color
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.White = function () { return new Color3(1, 1, 1); };
  1711. /**
  1712. * Returns a Color3 value containing a purple color
  1713. * @returns a new Color3 object
  1714. */
  1715. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1716. /**
  1717. * Returns a Color3 value containing a magenta color
  1718. * @returns a new Color3 object
  1719. */
  1720. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1721. /**
  1722. * Returns a Color3 value containing a yellow color
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1726. /**
  1727. * Returns a Color3 value containing a gray color
  1728. * @returns a new Color3 object
  1729. */
  1730. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1731. /**
  1732. * Returns a Color3 value containing a teal color
  1733. * @returns a new Color3 object
  1734. */
  1735. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1736. /**
  1737. * Returns a Color3 value containing a random color
  1738. * @returns a new Color3 object
  1739. */
  1740. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1741. return Color3;
  1742. }());
  1743. BABYLON.Color3 = Color3;
  1744. /**
  1745. * Class used to hold a RBGA color
  1746. */
  1747. var Color4 = /** @class */ (function () {
  1748. /**
  1749. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1750. * @param r defines the red component (between 0 and 1, default is 0)
  1751. * @param g defines the green component (between 0 and 1, default is 0)
  1752. * @param b defines the blue component (between 0 and 1, default is 0)
  1753. * @param a defines the alpha component (between 0 and 1, default is 1)
  1754. */
  1755. function Color4(
  1756. /**
  1757. * Defines the red component (between 0 and 1, default is 0)
  1758. */
  1759. r,
  1760. /**
  1761. * Defines the green component (between 0 and 1, default is 0)
  1762. */
  1763. g,
  1764. /**
  1765. * Defines the blue component (between 0 and 1, default is 0)
  1766. */
  1767. b,
  1768. /**
  1769. * Defines the alpha component (between 0 and 1, default is 1)
  1770. */
  1771. a) {
  1772. if (r === void 0) { r = 0; }
  1773. if (g === void 0) { g = 0; }
  1774. if (b === void 0) { b = 0; }
  1775. if (a === void 0) { a = 1; }
  1776. this.r = r;
  1777. this.g = g;
  1778. this.b = b;
  1779. this.a = a;
  1780. }
  1781. // Operators
  1782. /**
  1783. * Adds in place the passed Color4 values to the current Color4 object
  1784. * @param right defines the second operand
  1785. * @returns the current updated Color4 object
  1786. */
  1787. Color4.prototype.addInPlace = function (right) {
  1788. this.r += right.r;
  1789. this.g += right.g;
  1790. this.b += right.b;
  1791. this.a += right.a;
  1792. return this;
  1793. };
  1794. /**
  1795. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1796. * @returns the new array
  1797. */
  1798. Color4.prototype.asArray = function () {
  1799. var result = new Array();
  1800. this.toArray(result, 0);
  1801. return result;
  1802. };
  1803. /**
  1804. * Stores from the starting index in the passed array the Color4 successive values
  1805. * @param array defines the array where to store the r,g,b components
  1806. * @param index defines an optional index in the target array to define where to start storing values
  1807. * @returns the current Color4 object
  1808. */
  1809. Color4.prototype.toArray = function (array, index) {
  1810. if (index === undefined) {
  1811. index = 0;
  1812. }
  1813. array[index] = this.r;
  1814. array[index + 1] = this.g;
  1815. array[index + 2] = this.b;
  1816. array[index + 3] = this.a;
  1817. return this;
  1818. };
  1819. /**
  1820. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1821. * @param right defines the second operand
  1822. * @returns a new Color4 object
  1823. */
  1824. Color4.prototype.add = function (right) {
  1825. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1826. };
  1827. /**
  1828. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1829. * @param right defines the second operand
  1830. * @returns a new Color4 object
  1831. */
  1832. Color4.prototype.subtract = function (right) {
  1833. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1834. };
  1835. /**
  1836. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1837. * @param right defines the second operand
  1838. * @param result defines the Color4 object where to store the result
  1839. * @returns the current Color4 object
  1840. */
  1841. Color4.prototype.subtractToRef = function (right, result) {
  1842. result.r = this.r - right.r;
  1843. result.g = this.g - right.g;
  1844. result.b = this.b - right.b;
  1845. result.a = this.a - right.a;
  1846. return this;
  1847. };
  1848. /**
  1849. * Creates a new Color4 with the current Color4 values multiplied by scale
  1850. * @param scale defines the scaling factor to apply
  1851. * @returns a new Color4 object
  1852. */
  1853. Color4.prototype.scale = function (scale) {
  1854. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1855. };
  1856. /**
  1857. * Multiplies the current Color4 values by scale and stores the result in "result"
  1858. * @param scale defines the scaling factor to apply
  1859. * @param result defines the Color4 object where to store the result
  1860. * @returns the current Color4.
  1861. */
  1862. Color4.prototype.scaleToRef = function (scale, result) {
  1863. result.r = this.r * scale;
  1864. result.g = this.g * scale;
  1865. result.b = this.b * scale;
  1866. result.a = this.a * scale;
  1867. return this;
  1868. };
  1869. /**
  1870. * Clamps the rgb values by the min and max values and stores the result into "result"
  1871. * @param min defines minimum clamping value (default is 0)
  1872. * @param max defines maximum clamping value (default is 1)
  1873. * @param result defines color to store the result into.
  1874. * @returns the cuurent Color4
  1875. */
  1876. Color4.prototype.clampToRef = function (min, max, result) {
  1877. if (min === void 0) { min = 0; }
  1878. if (max === void 0) { max = 1; }
  1879. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1880. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1881. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1882. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1883. return this;
  1884. };
  1885. /**
  1886. * Multipy an Color4 value by another and return a new Color4 object
  1887. * @param color defines the Color4 value to multiply by
  1888. * @returns a new Color4 object
  1889. */
  1890. Color4.prototype.multiply = function (color) {
  1891. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1892. };
  1893. /**
  1894. * Multipy a Color4 value by another and push the result in a reference value
  1895. * @param color defines the Color4 value to multiply by
  1896. * @param result defines the Color4 to fill the result in
  1897. * @returns the result Color4
  1898. */
  1899. Color4.prototype.multiplyToRef = function (color, result) {
  1900. result.r = this.r * color.r;
  1901. result.g = this.g * color.g;
  1902. result.b = this.b * color.b;
  1903. result.a = this.a * color.a;
  1904. return result;
  1905. };
  1906. /**
  1907. * Creates a string with the Color4 current values
  1908. * @returns the string representation of the Color4 object
  1909. */
  1910. Color4.prototype.toString = function () {
  1911. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1912. };
  1913. /**
  1914. * Returns the string "Color4"
  1915. * @returns "Color4"
  1916. */
  1917. Color4.prototype.getClassName = function () {
  1918. return "Color4";
  1919. };
  1920. /**
  1921. * Compute the Color4 hash code
  1922. * @returns an unique number that can be used to hash Color4 objects
  1923. */
  1924. Color4.prototype.getHashCode = function () {
  1925. var hash = this.r || 0;
  1926. hash = (hash * 397) ^ (this.g || 0);
  1927. hash = (hash * 397) ^ (this.b || 0);
  1928. hash = (hash * 397) ^ (this.a || 0);
  1929. return hash;
  1930. };
  1931. /**
  1932. * Creates a new Color4 copied from the current one
  1933. * @returns a new Color4 object
  1934. */
  1935. Color4.prototype.clone = function () {
  1936. return new Color4(this.r, this.g, this.b, this.a);
  1937. };
  1938. /**
  1939. * Copies the passed Color4 values into the current one
  1940. * @param source defines the source Color4 object
  1941. * @returns the current updated Color4 object
  1942. */
  1943. Color4.prototype.copyFrom = function (source) {
  1944. this.r = source.r;
  1945. this.g = source.g;
  1946. this.b = source.b;
  1947. this.a = source.a;
  1948. return this;
  1949. };
  1950. /**
  1951. * Copies the passed float values into the current one
  1952. * @param r defines the red component to read from
  1953. * @param g defines the green component to read from
  1954. * @param b defines the blue component to read from
  1955. * @param a defines the alpha component to read from
  1956. * @returns the current updated Color4 object
  1957. */
  1958. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1959. this.r = r;
  1960. this.g = g;
  1961. this.b = b;
  1962. this.a = a;
  1963. return this;
  1964. };
  1965. /**
  1966. * Copies the passed float values into the current one
  1967. * @param r defines the red component to read from
  1968. * @param g defines the green component to read from
  1969. * @param b defines the blue component to read from
  1970. * @param a defines the alpha component to read from
  1971. * @returns the current updated Color4 object
  1972. */
  1973. Color4.prototype.set = function (r, g, b, a) {
  1974. return this.copyFromFloats(r, g, b, a);
  1975. };
  1976. /**
  1977. * Compute the Color4 hexadecimal code as a string
  1978. * @returns a string containing the hexadecimal representation of the Color4 object
  1979. */
  1980. Color4.prototype.toHexString = function () {
  1981. var intR = (this.r * 255) | 0;
  1982. var intG = (this.g * 255) | 0;
  1983. var intB = (this.b * 255) | 0;
  1984. var intA = (this.a * 255) | 0;
  1985. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1986. };
  1987. /**
  1988. * Computes a new Color4 converted from the current one to linear space
  1989. * @returns a new Color4 object
  1990. */
  1991. Color4.prototype.toLinearSpace = function () {
  1992. var convertedColor = new Color4();
  1993. this.toLinearSpaceToRef(convertedColor);
  1994. return convertedColor;
  1995. };
  1996. /**
  1997. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1998. * @param convertedColor defines the Color4 object where to store the linear space version
  1999. * @returns the unmodified Color4
  2000. */
  2001. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2002. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2003. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2004. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2005. convertedColor.a = this.a;
  2006. return this;
  2007. };
  2008. /**
  2009. * Computes a new Color4 converted from the current one to gamma space
  2010. * @returns a new Color4 object
  2011. */
  2012. Color4.prototype.toGammaSpace = function () {
  2013. var convertedColor = new Color4();
  2014. this.toGammaSpaceToRef(convertedColor);
  2015. return convertedColor;
  2016. };
  2017. /**
  2018. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2019. * @param convertedColor defines the Color4 object where to store the gamma space version
  2020. * @returns the unmodified Color4
  2021. */
  2022. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2023. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2024. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2025. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2026. convertedColor.a = this.a;
  2027. return this;
  2028. };
  2029. // Statics
  2030. /**
  2031. * Creates a new Color4 from the string containing valid hexadecimal values
  2032. * @param hex defines a string containing valid hexadecimal values
  2033. * @returns a new Color4 object
  2034. */
  2035. Color4.FromHexString = function (hex) {
  2036. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2037. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2038. return new Color4(0.0, 0.0, 0.0, 0.0);
  2039. }
  2040. var r = parseInt(hex.substring(1, 3), 16);
  2041. var g = parseInt(hex.substring(3, 5), 16);
  2042. var b = parseInt(hex.substring(5, 7), 16);
  2043. var a = parseInt(hex.substring(7, 9), 16);
  2044. return Color4.FromInts(r, g, b, a);
  2045. };
  2046. /**
  2047. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2048. * @param left defines the start value
  2049. * @param right defines the end value
  2050. * @param amount defines the gradient factor
  2051. * @returns a new Color4 object
  2052. */
  2053. Color4.Lerp = function (left, right, amount) {
  2054. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2055. Color4.LerpToRef(left, right, amount, result);
  2056. return result;
  2057. };
  2058. /**
  2059. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2060. * @param left defines the start value
  2061. * @param right defines the end value
  2062. * @param amount defines the gradient factor
  2063. * @param result defines the Color4 object where to store data
  2064. */
  2065. Color4.LerpToRef = function (left, right, amount, result) {
  2066. result.r = left.r + (right.r - left.r) * amount;
  2067. result.g = left.g + (right.g - left.g) * amount;
  2068. result.b = left.b + (right.b - left.b) * amount;
  2069. result.a = left.a + (right.a - left.a) * amount;
  2070. };
  2071. /**
  2072. * Creates a new Color4 from the starting index element of the passed array
  2073. * @param array defines the source array to read from
  2074. * @param offset defines the offset in the source array
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.FromArray = function (array, offset) {
  2078. if (offset === void 0) { offset = 0; }
  2079. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2080. };
  2081. /**
  2082. * Creates a new Color3 from integer values (< 256)
  2083. * @param r defines the red component to read from (value between 0 and 255)
  2084. * @param g defines the green component to read from (value between 0 and 255)
  2085. * @param b defines the blue component to read from (value between 0 and 255)
  2086. * @param a defines the alpha component to read from (value between 0 and 255)
  2087. * @returns a new Color3 object
  2088. */
  2089. Color4.FromInts = function (r, g, b, a) {
  2090. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2091. };
  2092. /**
  2093. * Check the content of a given array and convert it to an array containing RGBA data
  2094. * If the original array was already containing count * 4 values then it is returned directly
  2095. * @param colors defines the array to check
  2096. * @param count defines the number of RGBA data to expect
  2097. * @returns an array containing count * 4 values (RGBA)
  2098. */
  2099. Color4.CheckColors4 = function (colors, count) {
  2100. // Check if color3 was used
  2101. if (colors.length === count * 3) {
  2102. var colors4 = [];
  2103. for (var index = 0; index < colors.length; index += 3) {
  2104. var newIndex = (index / 3) * 4;
  2105. colors4[newIndex] = colors[index];
  2106. colors4[newIndex + 1] = colors[index + 1];
  2107. colors4[newIndex + 2] = colors[index + 2];
  2108. colors4[newIndex + 3] = 1.0;
  2109. }
  2110. return colors4;
  2111. }
  2112. return colors;
  2113. };
  2114. return Color4;
  2115. }());
  2116. BABYLON.Color4 = Color4;
  2117. var Vector2 = /** @class */ (function () {
  2118. /**
  2119. * Creates a new Vector2 from the passed x and y coordinates.
  2120. */
  2121. function Vector2(x, y) {
  2122. this.x = x;
  2123. this.y = y;
  2124. }
  2125. /**
  2126. * Returns a string with the Vector2 coordinates.
  2127. */
  2128. Vector2.prototype.toString = function () {
  2129. return "{X: " + this.x + " Y:" + this.y + "}";
  2130. };
  2131. /**
  2132. * Returns the string "Vector2"
  2133. */
  2134. Vector2.prototype.getClassName = function () {
  2135. return "Vector2";
  2136. };
  2137. /**
  2138. * Returns the Vector2 hash code as a number.
  2139. */
  2140. Vector2.prototype.getHashCode = function () {
  2141. var hash = this.x || 0;
  2142. hash = (hash * 397) ^ (this.y || 0);
  2143. return hash;
  2144. };
  2145. // Operators
  2146. /**
  2147. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2148. * Returns the Vector2.
  2149. */
  2150. Vector2.prototype.toArray = function (array, index) {
  2151. if (index === void 0) { index = 0; }
  2152. array[index] = this.x;
  2153. array[index + 1] = this.y;
  2154. return this;
  2155. };
  2156. /**
  2157. * Returns a new array with 2 elements : the Vector2 coordinates.
  2158. */
  2159. Vector2.prototype.asArray = function () {
  2160. var result = new Array();
  2161. this.toArray(result, 0);
  2162. return result;
  2163. };
  2164. /**
  2165. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2166. * Returns the updated Vector2.
  2167. */
  2168. Vector2.prototype.copyFrom = function (source) {
  2169. this.x = source.x;
  2170. this.y = source.y;
  2171. return this;
  2172. };
  2173. /**
  2174. * Sets the Vector2 coordinates with the passed floats.
  2175. * Returns the updated Vector2.
  2176. */
  2177. Vector2.prototype.copyFromFloats = function (x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. return this;
  2181. };
  2182. /**
  2183. * Sets the Vector2 coordinates with the passed floats.
  2184. * Returns the updated Vector2.
  2185. */
  2186. Vector2.prototype.set = function (x, y) {
  2187. return this.copyFromFloats(x, y);
  2188. };
  2189. /**
  2190. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2191. */
  2192. Vector2.prototype.add = function (otherVector) {
  2193. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2194. };
  2195. /**
  2196. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2197. * Returns the Vector2.
  2198. */
  2199. Vector2.prototype.addToRef = function (otherVector, result) {
  2200. result.x = this.x + otherVector.x;
  2201. result.y = this.y + otherVector.y;
  2202. return this;
  2203. };
  2204. /**
  2205. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2206. * Returns the updated Vector2.
  2207. */
  2208. Vector2.prototype.addInPlace = function (otherVector) {
  2209. this.x += otherVector.x;
  2210. this.y += otherVector.y;
  2211. return this;
  2212. };
  2213. /**
  2214. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2215. */
  2216. Vector2.prototype.addVector3 = function (otherVector) {
  2217. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2218. };
  2219. /**
  2220. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2221. */
  2222. Vector2.prototype.subtract = function (otherVector) {
  2223. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2224. };
  2225. /**
  2226. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2227. * Returns the Vector2.
  2228. */
  2229. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2230. result.x = this.x - otherVector.x;
  2231. result.y = this.y - otherVector.y;
  2232. return this;
  2233. };
  2234. /**
  2235. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2236. * Returns the updated Vector2.
  2237. */
  2238. Vector2.prototype.subtractInPlace = function (otherVector) {
  2239. this.x -= otherVector.x;
  2240. this.y -= otherVector.y;
  2241. return this;
  2242. };
  2243. /**
  2244. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2245. * Returns the updated Vector2.
  2246. */
  2247. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2248. this.x *= otherVector.x;
  2249. this.y *= otherVector.y;
  2250. return this;
  2251. };
  2252. /**
  2253. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2254. */
  2255. Vector2.prototype.multiply = function (otherVector) {
  2256. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2257. };
  2258. /**
  2259. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2260. * Returns the Vector2.
  2261. */
  2262. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2263. result.x = this.x * otherVector.x;
  2264. result.y = this.y * otherVector.y;
  2265. return this;
  2266. };
  2267. /**
  2268. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2269. */
  2270. Vector2.prototype.multiplyByFloats = function (x, y) {
  2271. return new Vector2(this.x * x, this.y * y);
  2272. };
  2273. /**
  2274. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2275. */
  2276. Vector2.prototype.divide = function (otherVector) {
  2277. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2278. };
  2279. /**
  2280. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2281. * Returns the Vector2.
  2282. */
  2283. Vector2.prototype.divideToRef = function (otherVector, result) {
  2284. result.x = this.x / otherVector.x;
  2285. result.y = this.y / otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Divides the current Vector3 coordinates by the passed ones.
  2290. * Returns the updated Vector3.
  2291. */
  2292. Vector2.prototype.divideInPlace = function (otherVector) {
  2293. return this.divideToRef(otherVector, this);
  2294. };
  2295. /**
  2296. * Returns a new Vector2 with current Vector2 negated coordinates.
  2297. */
  2298. Vector2.prototype.negate = function () {
  2299. return new Vector2(-this.x, -this.y);
  2300. };
  2301. /**
  2302. * Multiply the Vector2 coordinates by scale.
  2303. * Returns the updated Vector2.
  2304. */
  2305. Vector2.prototype.scaleInPlace = function (scale) {
  2306. this.x *= scale;
  2307. this.y *= scale;
  2308. return this;
  2309. };
  2310. /**
  2311. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2312. */
  2313. Vector2.prototype.scale = function (scale) {
  2314. return new Vector2(this.x * scale, this.y * scale);
  2315. };
  2316. /**
  2317. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2318. */
  2319. Vector2.prototype.equals = function (otherVector) {
  2320. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2321. };
  2322. /**
  2323. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2324. */
  2325. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2326. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2327. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2328. };
  2329. // Properties
  2330. /**
  2331. * Returns the vector length (float).
  2332. */
  2333. Vector2.prototype.length = function () {
  2334. return Math.sqrt(this.x * this.x + this.y * this.y);
  2335. };
  2336. /**
  2337. * Returns the vector squared length (float);
  2338. */
  2339. Vector2.prototype.lengthSquared = function () {
  2340. return (this.x * this.x + this.y * this.y);
  2341. };
  2342. // Methods
  2343. /**
  2344. * Normalize the vector.
  2345. * Returns the updated Vector2.
  2346. */
  2347. Vector2.prototype.normalize = function () {
  2348. var len = this.length();
  2349. if (len === 0)
  2350. return this;
  2351. var num = 1.0 / len;
  2352. this.x *= num;
  2353. this.y *= num;
  2354. return this;
  2355. };
  2356. /**
  2357. * Returns a new Vector2 copied from the Vector2.
  2358. */
  2359. Vector2.prototype.clone = function () {
  2360. return new Vector2(this.x, this.y);
  2361. };
  2362. // Statics
  2363. /**
  2364. * Returns a new Vector2(0, 0)
  2365. */
  2366. Vector2.Zero = function () {
  2367. return new Vector2(0, 0);
  2368. };
  2369. /**
  2370. * Returns a new Vector2(1, 1)
  2371. */
  2372. Vector2.One = function () {
  2373. return new Vector2(1, 1);
  2374. };
  2375. /**
  2376. * Returns a new Vector2 set from the passed index element of the passed array.
  2377. */
  2378. Vector2.FromArray = function (array, offset) {
  2379. if (offset === void 0) { offset = 0; }
  2380. return new Vector2(array[offset], array[offset + 1]);
  2381. };
  2382. /**
  2383. * Sets "result" from the passed index element of the passed array.
  2384. */
  2385. Vector2.FromArrayToRef = function (array, offset, result) {
  2386. result.x = array[offset];
  2387. result.y = array[offset + 1];
  2388. };
  2389. /**
  2390. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2391. */
  2392. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2393. var squared = amount * amount;
  2394. var cubed = amount * squared;
  2395. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2396. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2397. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2398. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2399. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2400. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2401. return new Vector2(x, y);
  2402. };
  2403. /**
  2404. * 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".
  2405. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2406. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2407. */
  2408. Vector2.Clamp = function (value, min, max) {
  2409. var x = value.x;
  2410. x = (x > max.x) ? max.x : x;
  2411. x = (x < min.x) ? min.x : x;
  2412. var y = value.y;
  2413. y = (y > max.y) ? max.y : y;
  2414. y = (y < min.y) ? min.y : y;
  2415. return new Vector2(x, y);
  2416. };
  2417. /**
  2418. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2419. */
  2420. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2421. var squared = amount * amount;
  2422. var cubed = amount * squared;
  2423. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2424. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2425. var part3 = (cubed - (2.0 * squared)) + amount;
  2426. var part4 = cubed - squared;
  2427. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2428. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2429. return new Vector2(x, y);
  2430. };
  2431. /**
  2432. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2433. */
  2434. Vector2.Lerp = function (start, end, amount) {
  2435. var x = start.x + ((end.x - start.x) * amount);
  2436. var y = start.y + ((end.y - start.y) * amount);
  2437. return new Vector2(x, y);
  2438. };
  2439. /**
  2440. * Returns the dot product (float) of the vector "left" and the vector "right".
  2441. */
  2442. Vector2.Dot = function (left, right) {
  2443. return left.x * right.x + left.y * right.y;
  2444. };
  2445. /**
  2446. * Returns a new Vector2 equal to the normalized passed vector.
  2447. */
  2448. Vector2.Normalize = function (vector) {
  2449. var newVector = vector.clone();
  2450. newVector.normalize();
  2451. return newVector;
  2452. };
  2453. /**
  2454. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2455. */
  2456. Vector2.Minimize = function (left, right) {
  2457. var x = (left.x < right.x) ? left.x : right.x;
  2458. var y = (left.y < right.y) ? left.y : right.y;
  2459. return new Vector2(x, y);
  2460. };
  2461. /**
  2462. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2463. */
  2464. Vector2.Maximize = function (left, right) {
  2465. var x = (left.x > right.x) ? left.x : right.x;
  2466. var y = (left.y > right.y) ? left.y : right.y;
  2467. return new Vector2(x, y);
  2468. };
  2469. /**
  2470. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2471. */
  2472. Vector2.Transform = function (vector, transformation) {
  2473. var r = Vector2.Zero();
  2474. Vector2.TransformToRef(vector, transformation, r);
  2475. return r;
  2476. };
  2477. /**
  2478. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2479. */
  2480. Vector2.TransformToRef = function (vector, transformation, result) {
  2481. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2482. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2483. result.x = x;
  2484. result.y = y;
  2485. };
  2486. /**
  2487. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2488. */
  2489. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2490. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2491. var sign = a < 0 ? -1 : 1;
  2492. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2493. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2494. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2495. };
  2496. /**
  2497. * Returns the distance (float) between the vectors "value1" and "value2".
  2498. */
  2499. Vector2.Distance = function (value1, value2) {
  2500. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2501. };
  2502. /**
  2503. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2504. */
  2505. Vector2.DistanceSquared = function (value1, value2) {
  2506. var x = value1.x - value2.x;
  2507. var y = value1.y - value2.y;
  2508. return (x * x) + (y * y);
  2509. };
  2510. /**
  2511. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2512. */
  2513. Vector2.Center = function (value1, value2) {
  2514. var center = value1.add(value2);
  2515. center.scaleInPlace(0.5);
  2516. return center;
  2517. };
  2518. /**
  2519. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2520. */
  2521. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2522. var l2 = Vector2.DistanceSquared(segA, segB);
  2523. if (l2 === 0.0) {
  2524. return Vector2.Distance(p, segA);
  2525. }
  2526. var v = segB.subtract(segA);
  2527. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2528. var proj = segA.add(v.multiplyByFloats(t, t));
  2529. return Vector2.Distance(p, proj);
  2530. };
  2531. return Vector2;
  2532. }());
  2533. BABYLON.Vector2 = Vector2;
  2534. /**
  2535. * Classed used to store (x,y,z) vector representation
  2536. * A Vector3 is the main object used in 3D geometry
  2537. * It can represent etiher the coordinates of a point the space, either a direction
  2538. * Reminder: Babylon.js uses a left handed forward facing system
  2539. */
  2540. var Vector3 = /** @class */ (function () {
  2541. /**
  2542. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2543. * @param x defines the first coordinates (on X axis)
  2544. * @param y defines the second coordinates (on Y axis)
  2545. * @param z defines the third coordinates (on Z axis)
  2546. */
  2547. function Vector3(
  2548. /**
  2549. * Defines the first coordinates (on X axis)
  2550. */
  2551. x,
  2552. /**
  2553. * Defines the second coordinates (on Y axis)
  2554. */
  2555. y,
  2556. /**
  2557. * Defines the third coordinates (on Z axis)
  2558. */
  2559. z) {
  2560. this.x = x;
  2561. this.y = y;
  2562. this.z = z;
  2563. }
  2564. /**
  2565. * Creates a string representation of the Vector3
  2566. * @returns a string with the Vector3 coordinates.
  2567. */
  2568. Vector3.prototype.toString = function () {
  2569. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2570. };
  2571. /**
  2572. * Gets the class name
  2573. * @returns the string "Vector3"
  2574. */
  2575. Vector3.prototype.getClassName = function () {
  2576. return "Vector3";
  2577. };
  2578. /**
  2579. * Creates the Vector3 hash code
  2580. * @returns a number which tends to be unique between Vector3 instances
  2581. */
  2582. Vector3.prototype.getHashCode = function () {
  2583. var hash = this.x || 0;
  2584. hash = (hash * 397) ^ (this.y || 0);
  2585. hash = (hash * 397) ^ (this.z || 0);
  2586. return hash;
  2587. };
  2588. // Operators
  2589. /**
  2590. * Creates an array containing three elements : the coordinates of the Vector3
  2591. * @returns a new array of numbers
  2592. */
  2593. Vector3.prototype.asArray = function () {
  2594. var result = [];
  2595. this.toArray(result, 0);
  2596. return result;
  2597. };
  2598. /**
  2599. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2600. * @param array defines the destination array
  2601. * @param index defines the offset in the destination array
  2602. * @returns the current Vector3
  2603. */
  2604. Vector3.prototype.toArray = function (array, index) {
  2605. if (index === void 0) { index = 0; }
  2606. array[index] = this.x;
  2607. array[index + 1] = this.y;
  2608. array[index + 2] = this.z;
  2609. return this;
  2610. };
  2611. /**
  2612. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2613. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2614. */
  2615. Vector3.prototype.toQuaternion = function () {
  2616. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2617. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2618. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2619. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2620. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2621. var cosy = Math.cos(this.y * 0.5);
  2622. var siny = Math.sin(this.y * 0.5);
  2623. result.x = coszMinusx * siny;
  2624. result.y = -sinzMinusx * siny;
  2625. result.z = sinxPlusz * cosy;
  2626. result.w = cosxPlusz * cosy;
  2627. return result;
  2628. };
  2629. /**
  2630. * Adds the passed vector to the current Vector3
  2631. * @param otherVector defines the second operand
  2632. * @returns the current updated Vector3
  2633. */
  2634. Vector3.prototype.addInPlace = function (otherVector) {
  2635. this.x += otherVector.x;
  2636. this.y += otherVector.y;
  2637. this.z += otherVector.z;
  2638. return this;
  2639. };
  2640. /**
  2641. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2642. * @param otherVector defines the second operand
  2643. * @returns the resulting Vector3
  2644. */
  2645. Vector3.prototype.add = function (otherVector) {
  2646. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2647. };
  2648. /**
  2649. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2650. * @param otherVector defines the second operand
  2651. * @param result defines the Vector3 object where to store the result
  2652. * @returns the current Vector3
  2653. */
  2654. Vector3.prototype.addToRef = function (otherVector, result) {
  2655. result.x = this.x + otherVector.x;
  2656. result.y = this.y + otherVector.y;
  2657. result.z = this.z + otherVector.z;
  2658. return this;
  2659. };
  2660. /**
  2661. * Subtract the passed vector from the current Vector3
  2662. * @param otherVector defines the second operand
  2663. * @returns the current updated Vector3
  2664. */
  2665. Vector3.prototype.subtractInPlace = function (otherVector) {
  2666. this.x -= otherVector.x;
  2667. this.y -= otherVector.y;
  2668. this.z -= otherVector.z;
  2669. return this;
  2670. };
  2671. /**
  2672. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2673. * @param otherVector defines the second operand
  2674. * @returns the resulting Vector3
  2675. */
  2676. Vector3.prototype.subtract = function (otherVector) {
  2677. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2678. };
  2679. /**
  2680. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2681. * @param otherVector defines the second operand
  2682. * @param result defines the Vector3 object where to store the result
  2683. * @returns the current Vector3
  2684. */
  2685. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2686. result.x = this.x - otherVector.x;
  2687. result.y = this.y - otherVector.y;
  2688. result.z = this.z - otherVector.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2693. * @param x defines the x coordinate of the operand
  2694. * @param y defines the y coordinate of the operand
  2695. * @param z defines the z coordinate of the operand
  2696. * @returns the resulting Vector3
  2697. */
  2698. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2699. return new Vector3(this.x - x, this.y - y, this.z - z);
  2700. };
  2701. /**
  2702. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  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. * @param result defines the Vector3 object where to store the result
  2707. * @returns the current Vector3
  2708. */
  2709. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2710. result.x = this.x - x;
  2711. result.y = this.y - y;
  2712. result.z = this.z - z;
  2713. return this;
  2714. };
  2715. /**
  2716. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2717. * @returns a new Vector3
  2718. */
  2719. Vector3.prototype.negate = function () {
  2720. return new Vector3(-this.x, -this.y, -this.z);
  2721. };
  2722. /**
  2723. * Multiplies the Vector3 coordinates by the float "scale"
  2724. * @param scale defines the multiplier factor
  2725. * @returns the current updated Vector3
  2726. */
  2727. Vector3.prototype.scaleInPlace = function (scale) {
  2728. this.x *= scale;
  2729. this.y *= scale;
  2730. this.z *= scale;
  2731. return this;
  2732. };
  2733. /**
  2734. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2735. * @param scale defines the multiplier factor
  2736. * @returns a new Vector3
  2737. */
  2738. Vector3.prototype.scale = function (scale) {
  2739. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2740. };
  2741. /**
  2742. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2743. * @param scale defines the multiplier factor
  2744. * @param result defines the Vector3 object where to store the result
  2745. * @returns the current Vector3
  2746. */
  2747. Vector3.prototype.scaleToRef = function (scale, result) {
  2748. result.x = this.x * scale;
  2749. result.y = this.y * scale;
  2750. result.z = this.z * scale;
  2751. return this;
  2752. };
  2753. /**
  2754. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2755. * @param otherVector defines the second operand
  2756. * @returns true if both vectors are equals
  2757. */
  2758. Vector3.prototype.equals = function (otherVector) {
  2759. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2760. };
  2761. /**
  2762. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2763. * @param otherVector defines the second operand
  2764. * @param epsilon defines the minimal distance to define values as equals
  2765. * @returns true if both vectors are distant less than epsilon
  2766. */
  2767. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2768. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2769. 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);
  2770. };
  2771. /**
  2772. * Returns true if the current Vector3 coordinates equals the passed floats
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns true if both vectors are equals
  2777. */
  2778. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2779. return this.x === x && this.y === y && this.z === z;
  2780. };
  2781. /**
  2782. * Multiplies the current Vector3 coordinates by the passed ones
  2783. * @param otherVector defines the second operand
  2784. * @returns the current updated Vector3
  2785. */
  2786. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2787. this.x *= otherVector.x;
  2788. this.y *= otherVector.y;
  2789. this.z *= otherVector.z;
  2790. return this;
  2791. };
  2792. /**
  2793. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2794. * @param otherVector defines the second operand
  2795. * @returns the new Vector3
  2796. */
  2797. Vector3.prototype.multiply = function (otherVector) {
  2798. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2799. };
  2800. /**
  2801. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2802. * @param otherVector defines the second operand
  2803. * @param result defines the Vector3 object where to store the result
  2804. * @returns the current Vector3
  2805. */
  2806. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2807. result.x = this.x * otherVector.x;
  2808. result.y = this.y * otherVector.y;
  2809. result.z = this.z * otherVector.z;
  2810. return this;
  2811. };
  2812. /**
  2813. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2814. * @param x defines the x coordinate of the operand
  2815. * @param y defines the y coordinate of the operand
  2816. * @param z defines the z coordinate of the operand
  2817. * @returns the new Vector3
  2818. */
  2819. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2820. return new Vector3(this.x * x, this.y * y, this.z * z);
  2821. };
  2822. /**
  2823. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2824. * @param otherVector defines the second operand
  2825. * @returns the new Vector3
  2826. */
  2827. Vector3.prototype.divide = function (otherVector) {
  2828. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2829. };
  2830. /**
  2831. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2832. * @param otherVector defines the second operand
  2833. * @param result defines the Vector3 object where to store the result
  2834. * @returns the current Vector3
  2835. */
  2836. Vector3.prototype.divideToRef = function (otherVector, result) {
  2837. result.x = this.x / otherVector.x;
  2838. result.y = this.y / otherVector.y;
  2839. result.z = this.z / otherVector.z;
  2840. return this;
  2841. };
  2842. /**
  2843. * Divides the current Vector3 coordinates by the passed ones.
  2844. * @param otherVector defines the second operand
  2845. * @returns the current updated Vector3
  2846. */
  2847. Vector3.prototype.divideInPlace = function (otherVector) {
  2848. return this.divideToRef(otherVector, this);
  2849. };
  2850. /**
  2851. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2852. * @param other defines the second operand
  2853. * @returns the current updated Vector3
  2854. */
  2855. Vector3.prototype.minimizeInPlace = function (other) {
  2856. if (other.x < this.x)
  2857. this.x = other.x;
  2858. if (other.y < this.y)
  2859. this.y = other.y;
  2860. if (other.z < this.z)
  2861. this.z = other.z;
  2862. return this;
  2863. };
  2864. /**
  2865. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2866. * @param other defines the second operand
  2867. * @returns the current updated Vector3
  2868. */
  2869. Vector3.prototype.maximizeInPlace = function (other) {
  2870. if (other.x > this.x)
  2871. this.x = other.x;
  2872. if (other.y > this.y)
  2873. this.y = other.y;
  2874. if (other.z > this.z)
  2875. this.z = other.z;
  2876. return this;
  2877. };
  2878. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2879. /**
  2880. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2881. */
  2882. get: function () {
  2883. var absX = Math.abs(this.x);
  2884. var absY = Math.abs(this.y);
  2885. if (absX !== absY) {
  2886. return true;
  2887. }
  2888. var absZ = Math.abs(this.z);
  2889. if (absX !== absZ) {
  2890. return true;
  2891. }
  2892. if (absY !== absZ) {
  2893. return true;
  2894. }
  2895. return false;
  2896. },
  2897. enumerable: true,
  2898. configurable: true
  2899. });
  2900. // Properties
  2901. /**
  2902. * Gets the length of the Vector3
  2903. * @returns the length of the Vecto3
  2904. */
  2905. Vector3.prototype.length = function () {
  2906. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2907. };
  2908. /**
  2909. * Gets the squared length of the Vector3
  2910. * @returns squared length of the Vector3
  2911. */
  2912. Vector3.prototype.lengthSquared = function () {
  2913. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2914. };
  2915. /**
  2916. * Normalize the current Vector3.
  2917. * Please note that this is an in place operation.
  2918. * @returns the current updated Vector3
  2919. */
  2920. Vector3.prototype.normalize = function () {
  2921. var len = this.length();
  2922. if (len === 0 || len === 1.0)
  2923. return this;
  2924. var num = 1.0 / len;
  2925. this.x *= num;
  2926. this.y *= num;
  2927. this.z *= num;
  2928. return this;
  2929. };
  2930. /**
  2931. * Normalize the current Vector3 to a new vector
  2932. * @returns the new Vector3
  2933. */
  2934. Vector3.prototype.normalizeToNew = function () {
  2935. var normalized = new Vector3(0, 0, 0);
  2936. this.normalizeToRef(normalized);
  2937. return normalized;
  2938. };
  2939. /**
  2940. * Normalize the current Vector3 to the reference
  2941. * @param reference define the Vector3 to update
  2942. * @returns the updated Vector3
  2943. */
  2944. Vector3.prototype.normalizeToRef = function (reference) {
  2945. var len = this.length();
  2946. if (len === 0 || len === 1.0) {
  2947. reference.set(this.x, this.y, this.z);
  2948. return reference;
  2949. }
  2950. var scale = 1.0 / len;
  2951. this.scaleToRef(scale, reference);
  2952. return reference;
  2953. };
  2954. /**
  2955. * Creates a new Vector3 copied from the current Vector3
  2956. * @returns the new Vector3
  2957. */
  2958. Vector3.prototype.clone = function () {
  2959. return new Vector3(this.x, this.y, this.z);
  2960. };
  2961. /**
  2962. * Copies the passed vector coordinates to the current Vector3 ones
  2963. * @param source defines the source Vector3
  2964. * @returns the current updated Vector3
  2965. */
  2966. Vector3.prototype.copyFrom = function (source) {
  2967. this.x = source.x;
  2968. this.y = source.y;
  2969. this.z = source.z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Copies the passed floats to the current Vector3 coordinates
  2974. * @param x defines the x coordinate of the operand
  2975. * @param y defines the y coordinate of the operand
  2976. * @param z defines the z coordinate of the operand
  2977. * @returns the current updated Vector3
  2978. */
  2979. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2980. this.x = x;
  2981. this.y = y;
  2982. this.z = z;
  2983. return this;
  2984. };
  2985. /**
  2986. * Copies the passed floats to the current Vector3 coordinates
  2987. * @param x defines the x coordinate of the operand
  2988. * @param y defines the y coordinate of the operand
  2989. * @param z defines the z coordinate of the operand
  2990. * @returns the current updated Vector3
  2991. */
  2992. Vector3.prototype.set = function (x, y, z) {
  2993. return this.copyFromFloats(x, y, z);
  2994. };
  2995. // Statics
  2996. /**
  2997. * Get the clip factor between two vectors
  2998. * @param vector0 defines the first operand
  2999. * @param vector1 defines the second operand
  3000. * @param axis defines the axis to use
  3001. * @param size defines the size along the axis
  3002. * @returns the clip factor
  3003. */
  3004. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3005. var d0 = Vector3.Dot(vector0, axis) - size;
  3006. var d1 = Vector3.Dot(vector1, axis) - size;
  3007. var s = d0 / (d0 - d1);
  3008. return s;
  3009. };
  3010. /**
  3011. * Get angle between two vectors
  3012. * @param vector0 angle between vector0 and vector1
  3013. * @param vector1 angle between vector0 and vector1
  3014. * @param normal direction of the normal
  3015. * @return the angle between vector0 and vector1
  3016. */
  3017. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3018. var v0 = vector0.clone().normalize();
  3019. var v1 = vector1.clone().normalize();
  3020. var dot = Vector3.Dot(v0, v1);
  3021. var n = Vector3.Cross(v0, v1);
  3022. if (Vector3.Dot(n, normal) > 0) {
  3023. return Math.acos(dot);
  3024. }
  3025. return -Math.acos(dot);
  3026. };
  3027. /**
  3028. * Returns a new Vector3 set from the index "offset" of the passed array
  3029. * @param array defines the source array
  3030. * @param offset defines the offset in the source array
  3031. * @returns the new Vector3
  3032. */
  3033. Vector3.FromArray = function (array, offset) {
  3034. if (!offset) {
  3035. offset = 0;
  3036. }
  3037. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3038. };
  3039. /**
  3040. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3041. * This function is deprecated. Use FromArray instead
  3042. * @param array defines the source array
  3043. * @param offset defines the offset in the source array
  3044. * @returns the new Vector3
  3045. */
  3046. Vector3.FromFloatArray = function (array, offset) {
  3047. return Vector3.FromArray(array, offset);
  3048. };
  3049. /**
  3050. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3051. * @param array defines the source array
  3052. * @param offset defines the offset in the source array
  3053. * @param result defines the Vector3 where to store the result
  3054. */
  3055. Vector3.FromArrayToRef = function (array, offset, result) {
  3056. result.x = array[offset];
  3057. result.y = array[offset + 1];
  3058. result.z = array[offset + 2];
  3059. };
  3060. /**
  3061. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3062. * This function is deprecated. Use FromArrayToRef instead.
  3063. * @param array defines the source array
  3064. * @param offset defines the offset in the source array
  3065. * @param result defines the Vector3 where to store the result
  3066. */
  3067. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3068. return Vector3.FromArrayToRef(array, offset, result);
  3069. };
  3070. /**
  3071. * Sets the passed vector "result" with the passed floats.
  3072. * @param x defines the x coordinate of the source
  3073. * @param y defines the y coordinate of the source
  3074. * @param z defines the z coordinate of the source
  3075. * @param result defines the Vector3 where to store the result
  3076. */
  3077. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3078. result.x = x;
  3079. result.y = y;
  3080. result.z = z;
  3081. };
  3082. /**
  3083. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3084. * @returns a new empty Vector3
  3085. */
  3086. Vector3.Zero = function () {
  3087. return new Vector3(0.0, 0.0, 0.0);
  3088. };
  3089. /**
  3090. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3091. * @returns a new unit Vector3
  3092. */
  3093. Vector3.One = function () {
  3094. return new Vector3(1.0, 1.0, 1.0);
  3095. };
  3096. /**
  3097. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3098. * @returns a new up Vector3
  3099. */
  3100. Vector3.Up = function () {
  3101. return new Vector3(0.0, 1.0, 0.0);
  3102. };
  3103. /**
  3104. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3105. * @returns a new forward Vector3
  3106. */
  3107. Vector3.Forward = function () {
  3108. return new Vector3(0.0, 0.0, 1.0);
  3109. };
  3110. /**
  3111. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3112. * @returns a new right Vector3
  3113. */
  3114. Vector3.Right = function () {
  3115. return new Vector3(1.0, 0.0, 0.0);
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3119. * @returns a new left Vector3
  3120. */
  3121. Vector3.Left = function () {
  3122. return new Vector3(-1.0, 0.0, 0.0);
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3126. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3127. * @param vector defines the Vector3 to transform
  3128. * @param transformation defines the transformation matrix
  3129. * @returns the transformed Vector3
  3130. */
  3131. Vector3.TransformCoordinates = function (vector, transformation) {
  3132. var result = Vector3.Zero();
  3133. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3134. return result;
  3135. };
  3136. /**
  3137. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3138. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3139. * @param vector defines the Vector3 to transform
  3140. * @param transformation defines the transformation matrix
  3141. * @param result defines the Vector3 where to store the result
  3142. */
  3143. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3144. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3145. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3146. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3147. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3148. result.x = x / w;
  3149. result.y = y / w;
  3150. result.z = z / w;
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3154. * This method computes tranformed coordinates only, not transformed direction vectors
  3155. * @param x define the x coordinate of the source vector
  3156. * @param y define the y coordinate of the source vector
  3157. * @param z define the z coordinate of the source vector
  3158. * @param transformation defines the transformation matrix
  3159. * @param result defines the Vector3 where to store the result
  3160. */
  3161. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3162. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3163. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3164. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3165. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3166. result.x = rx / rw;
  3167. result.y = ry / rw;
  3168. result.z = rz / rw;
  3169. };
  3170. /**
  3171. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3172. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3173. * @param vector defines the Vector3 to transform
  3174. * @param transformation defines the transformation matrix
  3175. * @returns the new Vector3
  3176. */
  3177. Vector3.TransformNormal = function (vector, transformation) {
  3178. var result = Vector3.Zero();
  3179. Vector3.TransformNormalToRef(vector, transformation, result);
  3180. return result;
  3181. };
  3182. /**
  3183. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3184. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3185. * @param vector defines the Vector3 to transform
  3186. * @param transformation defines the transformation matrix
  3187. * @param result defines the Vector3 where to store the result
  3188. */
  3189. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3190. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3191. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3192. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3193. result.x = x;
  3194. result.y = y;
  3195. result.z = z;
  3196. };
  3197. /**
  3198. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3199. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3200. * @param x define the x coordinate of the source vector
  3201. * @param y define the y coordinate of the source vector
  3202. * @param z define the z coordinate of the source vector
  3203. * @param transformation defines the transformation matrix
  3204. * @param result defines the Vector3 where to store the result
  3205. */
  3206. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3207. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3208. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3209. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3210. };
  3211. /**
  3212. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3213. * @param value1 defines the first control point
  3214. * @param value2 defines the second control point
  3215. * @param value3 defines the third control point
  3216. * @param value4 defines the fourth control point
  3217. * @param amount defines the amount on the spline to use
  3218. * @returns the new Vector3
  3219. */
  3220. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3221. var squared = amount * amount;
  3222. var cubed = amount * squared;
  3223. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3224. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3225. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3226. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3227. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3228. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3229. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3230. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3231. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3232. return new Vector3(x, y, z);
  3233. };
  3234. /**
  3235. * 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"
  3236. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3237. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3238. * @param value defines the current value
  3239. * @param min defines the lower range value
  3240. * @param max defines the upper range value
  3241. * @returns the new Vector3
  3242. */
  3243. Vector3.Clamp = function (value, min, max) {
  3244. var x = value.x;
  3245. x = (x > max.x) ? max.x : x;
  3246. x = (x < min.x) ? min.x : x;
  3247. var y = value.y;
  3248. y = (y > max.y) ? max.y : y;
  3249. y = (y < min.y) ? min.y : y;
  3250. var z = value.z;
  3251. z = (z > max.z) ? max.z : z;
  3252. z = (z < min.z) ? min.z : z;
  3253. return new Vector3(x, y, z);
  3254. };
  3255. /**
  3256. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3257. * @param value1 defines the first control point
  3258. * @param tangent1 defines the first tangent vector
  3259. * @param value2 defines the second control point
  3260. * @param tangent2 defines the second tangent vector
  3261. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3262. * @returns the new Vector3
  3263. */
  3264. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3265. var squared = amount * amount;
  3266. var cubed = amount * squared;
  3267. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3268. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3269. var part3 = (cubed - (2.0 * squared)) + amount;
  3270. var part4 = cubed - squared;
  3271. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3272. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3273. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3274. return new Vector3(x, y, z);
  3275. };
  3276. /**
  3277. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3278. * @param start defines the start value
  3279. * @param end defines the end value
  3280. * @param amount max defines amount between both (between 0 and 1)
  3281. * @returns the new Vector3
  3282. */
  3283. Vector3.Lerp = function (start, end, amount) {
  3284. var result = new Vector3(0, 0, 0);
  3285. Vector3.LerpToRef(start, end, amount, result);
  3286. return result;
  3287. };
  3288. /**
  3289. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3290. * @param start defines the start value
  3291. * @param end defines the end value
  3292. * @param amount max defines amount between both (between 0 and 1)
  3293. * @param result defines the Vector3 where to store the result
  3294. */
  3295. Vector3.LerpToRef = function (start, end, amount, result) {
  3296. result.x = start.x + ((end.x - start.x) * amount);
  3297. result.y = start.y + ((end.y - start.y) * amount);
  3298. result.z = start.z + ((end.z - start.z) * amount);
  3299. };
  3300. /**
  3301. * Returns the dot product (float) between the vectors "left" and "right"
  3302. * @param left defines the left operand
  3303. * @param right defines the right operand
  3304. * @returns the dot product
  3305. */
  3306. Vector3.Dot = function (left, right) {
  3307. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3308. };
  3309. /**
  3310. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3311. * The cross product is then orthogonal to both "left" and "right"
  3312. * @param left defines the left operand
  3313. * @param right defines the right operand
  3314. * @returns the cross product
  3315. */
  3316. Vector3.Cross = function (left, right) {
  3317. var result = Vector3.Zero();
  3318. Vector3.CrossToRef(left, right, result);
  3319. return result;
  3320. };
  3321. /**
  3322. * Sets the passed vector "result" with the cross product of "left" and "right"
  3323. * The cross product is then orthogonal to both "left" and "right"
  3324. * @param left defines the left operand
  3325. * @param right defines the right operand
  3326. * @param result defines the Vector3 where to store the result
  3327. */
  3328. Vector3.CrossToRef = function (left, right, result) {
  3329. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3330. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3331. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3332. result.copyFrom(MathTmp.Vector3[0]);
  3333. };
  3334. /**
  3335. * Returns a new Vector3 as the normalization of the passed vector
  3336. * @param vector defines the Vector3 to normalize
  3337. * @returns the new Vector3
  3338. */
  3339. Vector3.Normalize = function (vector) {
  3340. var result = Vector3.Zero();
  3341. Vector3.NormalizeToRef(vector, result);
  3342. return result;
  3343. };
  3344. /**
  3345. * Sets the passed vector "result" with the normalization of the passed first vector
  3346. * @param vector defines the Vector3 to normalize
  3347. * @param result defines the Vector3 where to store the result
  3348. */
  3349. Vector3.NormalizeToRef = function (vector, result) {
  3350. result.copyFrom(vector);
  3351. result.normalize();
  3352. };
  3353. /**
  3354. * Project a Vector3 onto screen space
  3355. * @param vector defines the Vector3 to project
  3356. * @param world defines the world matrix to use
  3357. * @param transform defines the transform (view x projection) matrix to use
  3358. * @param viewport defines the screen viewport to use
  3359. * @returns the new Vector3
  3360. */
  3361. Vector3.Project = function (vector, world, transform, viewport) {
  3362. var cw = viewport.width;
  3363. var ch = viewport.height;
  3364. var cx = viewport.x;
  3365. var cy = viewport.y;
  3366. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3367. 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);
  3368. var matrix = MathTmp.Matrix[0];
  3369. world.multiplyToRef(transform, matrix);
  3370. matrix.multiplyToRef(viewportMatrix, matrix);
  3371. return Vector3.TransformCoordinates(vector, matrix);
  3372. };
  3373. /**
  3374. * Unproject from screen space to object space
  3375. * @param source defines the screen space Vector3 to use
  3376. * @param viewportWidth defines the current width of the viewport
  3377. * @param viewportHeight defines the current height of the viewport
  3378. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3379. * @param transform defines the transform (view x projection) matrix to use
  3380. * @returns the new Vector3
  3381. */
  3382. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3383. var matrix = MathTmp.Matrix[0];
  3384. world.multiplyToRef(transform, matrix);
  3385. matrix.invert();
  3386. source.x = source.x / viewportWidth * 2 - 1;
  3387. source.y = -(source.y / viewportHeight * 2 - 1);
  3388. var vector = Vector3.TransformCoordinates(source, matrix);
  3389. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3390. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3391. vector = vector.scale(1.0 / num);
  3392. }
  3393. return vector;
  3394. };
  3395. /**
  3396. * Unproject from screen space to object space
  3397. * @param source defines the screen space Vector3 to use
  3398. * @param viewportWidth defines the current width of the viewport
  3399. * @param viewportHeight defines the current height of the viewport
  3400. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3401. * @param view defines the view matrix to use
  3402. * @param projection defines the projection matrix to use
  3403. * @returns the new Vector3
  3404. */
  3405. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3406. var result = Vector3.Zero();
  3407. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3408. return result;
  3409. };
  3410. /**
  3411. * Unproject from screen space to object space
  3412. * @param source defines the screen space Vector3 to use
  3413. * @param viewportWidth defines the current width of the viewport
  3414. * @param viewportHeight defines the current height of the viewport
  3415. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3416. * @param view defines the view matrix to use
  3417. * @param projection defines the projection matrix to use
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3421. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3422. };
  3423. /**
  3424. * Unproject from screen space to object space
  3425. * @param sourceX defines the screen space x coordinate to use
  3426. * @param sourceY defines the screen space y coordinate to use
  3427. * @param sourceZ defines the screen space z coordinate to use
  3428. * @param viewportWidth defines the current width of the viewport
  3429. * @param viewportHeight defines the current height of the viewport
  3430. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3431. * @param view defines the view matrix to use
  3432. * @param projection defines the projection matrix to use
  3433. * @param result defines the Vector3 where to store the result
  3434. */
  3435. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3436. var matrix = MathTmp.Matrix[0];
  3437. world.multiplyToRef(view, matrix);
  3438. matrix.multiplyToRef(projection, matrix);
  3439. matrix.invert();
  3440. var screenSource = MathTmp.Vector3[0];
  3441. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3442. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3443. screenSource.z = 2 * sourceZ - 1.0;
  3444. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3445. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3446. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3447. result.scaleInPlace(1.0 / num);
  3448. }
  3449. };
  3450. /**
  3451. * Gets the minimal coordinate values between two Vector3
  3452. * @param left defines the first operand
  3453. * @param right defines the second operand
  3454. * @returns the new Vector3
  3455. */
  3456. Vector3.Minimize = function (left, right) {
  3457. var min = left.clone();
  3458. min.minimizeInPlace(right);
  3459. return min;
  3460. };
  3461. /**
  3462. * Gets the maximal coordinate values between two Vector3
  3463. * @param left defines the first operand
  3464. * @param right defines the second operand
  3465. * @returns the new Vector3
  3466. */
  3467. Vector3.Maximize = function (left, right) {
  3468. var max = left.clone();
  3469. max.maximizeInPlace(right);
  3470. return max;
  3471. };
  3472. /**
  3473. * Returns the distance between the vectors "value1" and "value2"
  3474. * @param value1 defines the first operand
  3475. * @param value2 defines the second operand
  3476. * @returns the distance
  3477. */
  3478. Vector3.Distance = function (value1, value2) {
  3479. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3480. };
  3481. /**
  3482. * Returns the squared distance between the vectors "value1" and "value2"
  3483. * @param value1 defines the first operand
  3484. * @param value2 defines the second operand
  3485. * @returns the squared distance
  3486. */
  3487. Vector3.DistanceSquared = function (value1, value2) {
  3488. var x = value1.x - value2.x;
  3489. var y = value1.y - value2.y;
  3490. var z = value1.z - value2.z;
  3491. return (x * x) + (y * y) + (z * z);
  3492. };
  3493. /**
  3494. * Returns a new Vector3 located at the center between "value1" and "value2"
  3495. * @param value1 defines the first operand
  3496. * @param value2 defines the second operand
  3497. * @returns the new Vector3
  3498. */
  3499. Vector3.Center = function (value1, value2) {
  3500. var center = value1.add(value2);
  3501. center.scaleInPlace(0.5);
  3502. return center;
  3503. };
  3504. /**
  3505. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3506. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3507. * to something in order to rotate it from its local system to the given target system
  3508. * Note: axis1, axis2 and axis3 are normalized during this operation
  3509. * @param axis1 defines the first axis
  3510. * @param axis2 defines the second axis
  3511. * @param axis3 defines the third axis
  3512. * @returns a new Vector3
  3513. */
  3514. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3515. var rotation = Vector3.Zero();
  3516. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3517. return rotation;
  3518. };
  3519. /**
  3520. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3521. * @param axis1 defines the first axis
  3522. * @param axis2 defines the second axis
  3523. * @param axis3 defines the third axis
  3524. * @param ref defines the Vector3 where to store the result
  3525. */
  3526. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3527. var quat = MathTmp.Quaternion[0];
  3528. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3529. quat.toEulerAnglesToRef(ref);
  3530. };
  3531. return Vector3;
  3532. }());
  3533. BABYLON.Vector3 = Vector3;
  3534. //Vector4 class created for EulerAngle class conversion to Quaternion
  3535. var Vector4 = /** @class */ (function () {
  3536. /**
  3537. * Creates a Vector4 object from the passed floats.
  3538. */
  3539. function Vector4(x, y, z, w) {
  3540. this.x = x;
  3541. this.y = y;
  3542. this.z = z;
  3543. this.w = w;
  3544. }
  3545. /**
  3546. * Returns the string with the Vector4 coordinates.
  3547. */
  3548. Vector4.prototype.toString = function () {
  3549. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3550. };
  3551. /**
  3552. * Returns the string "Vector4".
  3553. */
  3554. Vector4.prototype.getClassName = function () {
  3555. return "Vector4";
  3556. };
  3557. /**
  3558. * Returns the Vector4 hash code.
  3559. */
  3560. Vector4.prototype.getHashCode = function () {
  3561. var hash = this.x || 0;
  3562. hash = (hash * 397) ^ (this.y || 0);
  3563. hash = (hash * 397) ^ (this.z || 0);
  3564. hash = (hash * 397) ^ (this.w || 0);
  3565. return hash;
  3566. };
  3567. // Operators
  3568. /**
  3569. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3570. */
  3571. Vector4.prototype.asArray = function () {
  3572. var result = new Array();
  3573. this.toArray(result, 0);
  3574. return result;
  3575. };
  3576. /**
  3577. * Populates the passed array from the passed index with the Vector4 coordinates.
  3578. * Returns the Vector4.
  3579. */
  3580. Vector4.prototype.toArray = function (array, index) {
  3581. if (index === undefined) {
  3582. index = 0;
  3583. }
  3584. array[index] = this.x;
  3585. array[index + 1] = this.y;
  3586. array[index + 2] = this.z;
  3587. array[index + 3] = this.w;
  3588. return this;
  3589. };
  3590. /**
  3591. * Adds the passed vector to the current Vector4.
  3592. * Returns the updated Vector4.
  3593. */
  3594. Vector4.prototype.addInPlace = function (otherVector) {
  3595. this.x += otherVector.x;
  3596. this.y += otherVector.y;
  3597. this.z += otherVector.z;
  3598. this.w += otherVector.w;
  3599. return this;
  3600. };
  3601. /**
  3602. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3603. */
  3604. Vector4.prototype.add = function (otherVector) {
  3605. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3606. };
  3607. /**
  3608. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3609. * Returns the current Vector4.
  3610. */
  3611. Vector4.prototype.addToRef = function (otherVector, result) {
  3612. result.x = this.x + otherVector.x;
  3613. result.y = this.y + otherVector.y;
  3614. result.z = this.z + otherVector.z;
  3615. result.w = this.w + otherVector.w;
  3616. return this;
  3617. };
  3618. /**
  3619. * Subtract in place the passed vector from the current Vector4.
  3620. * Returns the updated Vector4.
  3621. */
  3622. Vector4.prototype.subtractInPlace = function (otherVector) {
  3623. this.x -= otherVector.x;
  3624. this.y -= otherVector.y;
  3625. this.z -= otherVector.z;
  3626. this.w -= otherVector.w;
  3627. return this;
  3628. };
  3629. /**
  3630. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3631. */
  3632. Vector4.prototype.subtract = function (otherVector) {
  3633. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3634. };
  3635. /**
  3636. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3637. * Returns the current Vector4.
  3638. */
  3639. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3640. result.x = this.x - otherVector.x;
  3641. result.y = this.y - otherVector.y;
  3642. result.z = this.z - otherVector.z;
  3643. result.w = this.w - otherVector.w;
  3644. return this;
  3645. };
  3646. /**
  3647. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3648. */
  3649. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3650. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3651. };
  3652. /**
  3653. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3654. * Returns the current Vector4.
  3655. */
  3656. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3657. result.x = this.x - x;
  3658. result.y = this.y - y;
  3659. result.z = this.z - z;
  3660. result.w = this.w - w;
  3661. return this;
  3662. };
  3663. /**
  3664. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3665. */
  3666. Vector4.prototype.negate = function () {
  3667. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3668. };
  3669. /**
  3670. * Multiplies the current Vector4 coordinates by scale (float).
  3671. * Returns the updated Vector4.
  3672. */
  3673. Vector4.prototype.scaleInPlace = function (scale) {
  3674. this.x *= scale;
  3675. this.y *= scale;
  3676. this.z *= scale;
  3677. this.w *= scale;
  3678. return this;
  3679. };
  3680. /**
  3681. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3682. */
  3683. Vector4.prototype.scale = function (scale) {
  3684. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3685. };
  3686. /**
  3687. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3688. * Returns the current Vector4.
  3689. */
  3690. Vector4.prototype.scaleToRef = function (scale, result) {
  3691. result.x = this.x * scale;
  3692. result.y = this.y * scale;
  3693. result.z = this.z * scale;
  3694. result.w = this.w * scale;
  3695. return this;
  3696. };
  3697. /**
  3698. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3699. */
  3700. Vector4.prototype.equals = function (otherVector) {
  3701. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3702. };
  3703. /**
  3704. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3705. */
  3706. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3707. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3708. return otherVector
  3709. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3710. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3711. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3712. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3713. };
  3714. /**
  3715. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3716. */
  3717. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3718. return this.x === x && this.y === y && this.z === z && this.w === w;
  3719. };
  3720. /**
  3721. * Multiplies in place the current Vector4 by the passed one.
  3722. * Returns the updated Vector4.
  3723. */
  3724. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3725. this.x *= otherVector.x;
  3726. this.y *= otherVector.y;
  3727. this.z *= otherVector.z;
  3728. this.w *= otherVector.w;
  3729. return this;
  3730. };
  3731. /**
  3732. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3733. */
  3734. Vector4.prototype.multiply = function (otherVector) {
  3735. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3736. };
  3737. /**
  3738. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3739. * Returns the current Vector4.
  3740. */
  3741. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3742. result.x = this.x * otherVector.x;
  3743. result.y = this.y * otherVector.y;
  3744. result.z = this.z * otherVector.z;
  3745. result.w = this.w * otherVector.w;
  3746. return this;
  3747. };
  3748. /**
  3749. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3750. */
  3751. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3752. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3753. };
  3754. /**
  3755. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3756. */
  3757. Vector4.prototype.divide = function (otherVector) {
  3758. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3759. };
  3760. /**
  3761. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3762. * Returns the current Vector4.
  3763. */
  3764. Vector4.prototype.divideToRef = function (otherVector, result) {
  3765. result.x = this.x / otherVector.x;
  3766. result.y = this.y / otherVector.y;
  3767. result.z = this.z / otherVector.z;
  3768. result.w = this.w / otherVector.w;
  3769. return this;
  3770. };
  3771. /**
  3772. * Divides the current Vector3 coordinates by the passed ones.
  3773. * @returns the updated Vector3.
  3774. */
  3775. Vector4.prototype.divideInPlace = function (otherVector) {
  3776. return this.divideToRef(otherVector, this);
  3777. };
  3778. /**
  3779. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3780. * @param other defines the second operand
  3781. * @returns the current updated Vector4
  3782. */
  3783. Vector4.prototype.minimizeInPlace = function (other) {
  3784. if (other.x < this.x)
  3785. this.x = other.x;
  3786. if (other.y < this.y)
  3787. this.y = other.y;
  3788. if (other.z < this.z)
  3789. this.z = other.z;
  3790. if (other.w < this.w)
  3791. this.w = other.w;
  3792. return this;
  3793. };
  3794. /**
  3795. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3796. * @param other defines the second operand
  3797. * @returns the current updated Vector4
  3798. */
  3799. Vector4.prototype.maximizeInPlace = function (other) {
  3800. if (other.x > this.x)
  3801. this.x = other.x;
  3802. if (other.y > this.y)
  3803. this.y = other.y;
  3804. if (other.z > this.z)
  3805. this.z = other.z;
  3806. if (other.w > this.w)
  3807. this.w = other.w;
  3808. return this;
  3809. };
  3810. // Properties
  3811. /**
  3812. * Returns the Vector4 length (float).
  3813. */
  3814. Vector4.prototype.length = function () {
  3815. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3816. };
  3817. /**
  3818. * Returns the Vector4 squared length (float).
  3819. */
  3820. Vector4.prototype.lengthSquared = function () {
  3821. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3822. };
  3823. // Methods
  3824. /**
  3825. * Normalizes in place the Vector4.
  3826. * Returns the updated Vector4.
  3827. */
  3828. Vector4.prototype.normalize = function () {
  3829. var len = this.length();
  3830. if (len === 0)
  3831. return this;
  3832. var num = 1.0 / len;
  3833. this.x *= num;
  3834. this.y *= num;
  3835. this.z *= num;
  3836. this.w *= num;
  3837. return this;
  3838. };
  3839. /**
  3840. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3841. */
  3842. Vector4.prototype.toVector3 = function () {
  3843. return new Vector3(this.x, this.y, this.z);
  3844. };
  3845. /**
  3846. * Returns a new Vector4 copied from the current one.
  3847. */
  3848. Vector4.prototype.clone = function () {
  3849. return new Vector4(this.x, this.y, this.z, this.w);
  3850. };
  3851. /**
  3852. * Updates the current Vector4 with the passed one coordinates.
  3853. * Returns the updated Vector4.
  3854. */
  3855. Vector4.prototype.copyFrom = function (source) {
  3856. this.x = source.x;
  3857. this.y = source.y;
  3858. this.z = source.z;
  3859. this.w = source.w;
  3860. return this;
  3861. };
  3862. /**
  3863. * Updates the current Vector4 coordinates with the passed floats.
  3864. * Returns the updated Vector4.
  3865. */
  3866. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3867. this.x = x;
  3868. this.y = y;
  3869. this.z = z;
  3870. this.w = w;
  3871. return this;
  3872. };
  3873. /**
  3874. * Updates the current Vector4 coordinates with the passed floats.
  3875. * Returns the updated Vector4.
  3876. */
  3877. Vector4.prototype.set = function (x, y, z, w) {
  3878. return this.copyFromFloats(x, y, z, w);
  3879. };
  3880. // Statics
  3881. /**
  3882. * Returns a new Vector4 set from the starting index of the passed array.
  3883. */
  3884. Vector4.FromArray = function (array, offset) {
  3885. if (!offset) {
  3886. offset = 0;
  3887. }
  3888. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3889. };
  3890. /**
  3891. * Updates the passed vector "result" from the starting index of the passed array.
  3892. */
  3893. Vector4.FromArrayToRef = function (array, offset, result) {
  3894. result.x = array[offset];
  3895. result.y = array[offset + 1];
  3896. result.z = array[offset + 2];
  3897. result.w = array[offset + 3];
  3898. };
  3899. /**
  3900. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3901. */
  3902. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3903. Vector4.FromArrayToRef(array, offset, result);
  3904. };
  3905. /**
  3906. * Updates the passed vector "result" coordinates from the passed floats.
  3907. */
  3908. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3909. result.x = x;
  3910. result.y = y;
  3911. result.z = z;
  3912. result.w = w;
  3913. };
  3914. /**
  3915. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3916. */
  3917. Vector4.Zero = function () {
  3918. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3919. };
  3920. /**
  3921. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3922. */
  3923. Vector4.One = function () {
  3924. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3925. };
  3926. /**
  3927. * Returns a new normalized Vector4 from the passed one.
  3928. */
  3929. Vector4.Normalize = function (vector) {
  3930. var result = Vector4.Zero();
  3931. Vector4.NormalizeToRef(vector, result);
  3932. return result;
  3933. };
  3934. /**
  3935. * Updates the passed vector "result" from the normalization of the passed one.
  3936. */
  3937. Vector4.NormalizeToRef = function (vector, result) {
  3938. result.copyFrom(vector);
  3939. result.normalize();
  3940. };
  3941. Vector4.Minimize = function (left, right) {
  3942. var min = left.clone();
  3943. min.minimizeInPlace(right);
  3944. return min;
  3945. };
  3946. Vector4.Maximize = function (left, right) {
  3947. var max = left.clone();
  3948. max.maximizeInPlace(right);
  3949. return max;
  3950. };
  3951. /**
  3952. * Returns the distance (float) between the vectors "value1" and "value2".
  3953. */
  3954. Vector4.Distance = function (value1, value2) {
  3955. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3956. };
  3957. /**
  3958. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3959. */
  3960. Vector4.DistanceSquared = function (value1, value2) {
  3961. var x = value1.x - value2.x;
  3962. var y = value1.y - value2.y;
  3963. var z = value1.z - value2.z;
  3964. var w = value1.w - value2.w;
  3965. return (x * x) + (y * y) + (z * z) + (w * w);
  3966. };
  3967. /**
  3968. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3969. */
  3970. Vector4.Center = function (value1, value2) {
  3971. var center = value1.add(value2);
  3972. center.scaleInPlace(0.5);
  3973. return center;
  3974. };
  3975. /**
  3976. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3977. * This methods computes transformed normalized direction vectors only.
  3978. */
  3979. Vector4.TransformNormal = function (vector, transformation) {
  3980. var result = Vector4.Zero();
  3981. Vector4.TransformNormalToRef(vector, transformation, result);
  3982. return result;
  3983. };
  3984. /**
  3985. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3986. * This methods computes transformed normalized direction vectors only.
  3987. */
  3988. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3989. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3990. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3991. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3992. result.x = x;
  3993. result.y = y;
  3994. result.z = z;
  3995. result.w = vector.w;
  3996. };
  3997. /**
  3998. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3999. * This methods computes transformed normalized direction vectors only.
  4000. */
  4001. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4002. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4003. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4004. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4005. result.w = w;
  4006. };
  4007. return Vector4;
  4008. }());
  4009. BABYLON.Vector4 = Vector4;
  4010. var Size = /** @class */ (function () {
  4011. /**
  4012. * Creates a Size object from the passed width and height (floats).
  4013. */
  4014. function Size(width, height) {
  4015. this.width = width;
  4016. this.height = height;
  4017. }
  4018. // Returns a string with the Size width and height.
  4019. Size.prototype.toString = function () {
  4020. return "{W: " + this.width + ", H: " + this.height + "}";
  4021. };
  4022. /**
  4023. * Returns the string "Size"
  4024. */
  4025. Size.prototype.getClassName = function () {
  4026. return "Size";
  4027. };
  4028. /**
  4029. * Returns the Size hash code.
  4030. */
  4031. Size.prototype.getHashCode = function () {
  4032. var hash = this.width || 0;
  4033. hash = (hash * 397) ^ (this.height || 0);
  4034. return hash;
  4035. };
  4036. /**
  4037. * Updates the current size from the passed one.
  4038. * Returns the updated Size.
  4039. */
  4040. Size.prototype.copyFrom = function (src) {
  4041. this.width = src.width;
  4042. this.height = src.height;
  4043. };
  4044. /**
  4045. * Updates in place the current Size from the passed floats.
  4046. * Returns the updated Size.
  4047. */
  4048. Size.prototype.copyFromFloats = function (width, height) {
  4049. this.width = width;
  4050. this.height = height;
  4051. return this;
  4052. };
  4053. /**
  4054. * Updates in place the current Size from the passed floats.
  4055. * Returns the updated Size.
  4056. */
  4057. Size.prototype.set = function (width, height) {
  4058. return this.copyFromFloats(width, height);
  4059. };
  4060. /**
  4061. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4062. */
  4063. Size.prototype.multiplyByFloats = function (w, h) {
  4064. return new Size(this.width * w, this.height * h);
  4065. };
  4066. /**
  4067. * Returns a new Size copied from the passed one.
  4068. */
  4069. Size.prototype.clone = function () {
  4070. return new Size(this.width, this.height);
  4071. };
  4072. /**
  4073. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4074. */
  4075. Size.prototype.equals = function (other) {
  4076. if (!other) {
  4077. return false;
  4078. }
  4079. return (this.width === other.width) && (this.height === other.height);
  4080. };
  4081. Object.defineProperty(Size.prototype, "surface", {
  4082. /**
  4083. * Returns the surface of the Size : width * height (float).
  4084. */
  4085. get: function () {
  4086. return this.width * this.height;
  4087. },
  4088. enumerable: true,
  4089. configurable: true
  4090. });
  4091. /**
  4092. * Returns a new Size set to (0.0, 0.0)
  4093. */
  4094. Size.Zero = function () {
  4095. return new Size(0.0, 0.0);
  4096. };
  4097. /**
  4098. * Returns a new Size set as the addition result of the current Size and the passed one.
  4099. */
  4100. Size.prototype.add = function (otherSize) {
  4101. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4102. return r;
  4103. };
  4104. /**
  4105. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4106. */
  4107. Size.prototype.subtract = function (otherSize) {
  4108. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4109. return r;
  4110. };
  4111. /**
  4112. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4113. */
  4114. Size.Lerp = function (start, end, amount) {
  4115. var w = start.width + ((end.width - start.width) * amount);
  4116. var h = start.height + ((end.height - start.height) * amount);
  4117. return new Size(w, h);
  4118. };
  4119. return Size;
  4120. }());
  4121. BABYLON.Size = Size;
  4122. var Quaternion = /** @class */ (function () {
  4123. /**
  4124. * Creates a new Quaternion from the passed floats.
  4125. */
  4126. function Quaternion(x, y, z, w) {
  4127. if (x === void 0) { x = 0.0; }
  4128. if (y === void 0) { y = 0.0; }
  4129. if (z === void 0) { z = 0.0; }
  4130. if (w === void 0) { w = 1.0; }
  4131. this.x = x;
  4132. this.y = y;
  4133. this.z = z;
  4134. this.w = w;
  4135. }
  4136. /**
  4137. * Returns a string with the Quaternion coordinates.
  4138. */
  4139. Quaternion.prototype.toString = function () {
  4140. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4141. };
  4142. /**
  4143. * Returns the string "Quaternion".
  4144. */
  4145. Quaternion.prototype.getClassName = function () {
  4146. return "Quaternion";
  4147. };
  4148. /**
  4149. * Returns the Quaternion hash code.
  4150. */
  4151. Quaternion.prototype.getHashCode = function () {
  4152. var hash = this.x || 0;
  4153. hash = (hash * 397) ^ (this.y || 0);
  4154. hash = (hash * 397) ^ (this.z || 0);
  4155. hash = (hash * 397) ^ (this.w || 0);
  4156. return hash;
  4157. };
  4158. /**
  4159. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4160. */
  4161. Quaternion.prototype.asArray = function () {
  4162. return [this.x, this.y, this.z, this.w];
  4163. };
  4164. /**
  4165. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4166. */
  4167. Quaternion.prototype.equals = function (otherQuaternion) {
  4168. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4169. };
  4170. /**
  4171. * Returns a new Quaternion copied from the current one.
  4172. */
  4173. Quaternion.prototype.clone = function () {
  4174. return new Quaternion(this.x, this.y, this.z, this.w);
  4175. };
  4176. /**
  4177. * Updates the current Quaternion from the passed one coordinates.
  4178. * Returns the updated Quaterion.
  4179. */
  4180. Quaternion.prototype.copyFrom = function (other) {
  4181. this.x = other.x;
  4182. this.y = other.y;
  4183. this.z = other.z;
  4184. this.w = other.w;
  4185. return this;
  4186. };
  4187. /**
  4188. * Updates the current Quaternion from the passed float coordinates.
  4189. * Returns the updated Quaterion.
  4190. */
  4191. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4192. this.x = x;
  4193. this.y = y;
  4194. this.z = z;
  4195. this.w = w;
  4196. return this;
  4197. };
  4198. /**
  4199. * Updates the current Quaternion from the passed float coordinates.
  4200. * Returns the updated Quaterion.
  4201. */
  4202. Quaternion.prototype.set = function (x, y, z, w) {
  4203. return this.copyFromFloats(x, y, z, w);
  4204. };
  4205. /**
  4206. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4207. */
  4208. Quaternion.prototype.add = function (other) {
  4209. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4210. };
  4211. /**
  4212. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4213. */
  4214. Quaternion.prototype.subtract = function (other) {
  4215. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4216. };
  4217. /**
  4218. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4219. */
  4220. Quaternion.prototype.scale = function (value) {
  4221. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4222. };
  4223. /**
  4224. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4225. */
  4226. Quaternion.prototype.multiply = function (q1) {
  4227. var result = new Quaternion(0, 0, 0, 1.0);
  4228. this.multiplyToRef(q1, result);
  4229. return result;
  4230. };
  4231. /**
  4232. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4233. * Returns the current Quaternion.
  4234. */
  4235. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4236. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4237. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4238. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4239. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4240. result.copyFromFloats(x, y, z, w);
  4241. return this;
  4242. };
  4243. /**
  4244. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4245. * Returns the updated Quaternion.
  4246. */
  4247. Quaternion.prototype.multiplyInPlace = function (q1) {
  4248. this.multiplyToRef(q1, this);
  4249. return this;
  4250. };
  4251. /**
  4252. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4253. * Returns the current Quaternion.
  4254. */
  4255. Quaternion.prototype.conjugateToRef = function (ref) {
  4256. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4257. return this;
  4258. };
  4259. /**
  4260. * Conjugates in place the current Quaternion.
  4261. * Returns the updated Quaternion.
  4262. */
  4263. Quaternion.prototype.conjugateInPlace = function () {
  4264. this.x *= -1;
  4265. this.y *= -1;
  4266. this.z *= -1;
  4267. return this;
  4268. };
  4269. /**
  4270. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4271. */
  4272. Quaternion.prototype.conjugate = function () {
  4273. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4274. return result;
  4275. };
  4276. /**
  4277. * Returns the Quaternion length (float).
  4278. */
  4279. Quaternion.prototype.length = function () {
  4280. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4281. };
  4282. /**
  4283. * Normalize in place the current Quaternion.
  4284. * Returns the updated Quaternion.
  4285. */
  4286. Quaternion.prototype.normalize = function () {
  4287. var length = 1.0 / this.length();
  4288. this.x *= length;
  4289. this.y *= length;
  4290. this.z *= length;
  4291. this.w *= length;
  4292. return this;
  4293. };
  4294. /**
  4295. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4296. */
  4297. Quaternion.prototype.toEulerAngles = function (order) {
  4298. if (order === void 0) { order = "YZX"; }
  4299. var result = Vector3.Zero();
  4300. this.toEulerAnglesToRef(result, order);
  4301. return result;
  4302. };
  4303. /**
  4304. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4305. * Returns the current Quaternion.
  4306. */
  4307. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4308. if (order === void 0) { order = "YZX"; }
  4309. var qz = this.z;
  4310. var qx = this.x;
  4311. var qy = this.y;
  4312. var qw = this.w;
  4313. var sqw = qw * qw;
  4314. var sqz = qz * qz;
  4315. var sqx = qx * qx;
  4316. var sqy = qy * qy;
  4317. var zAxisY = qy * qz - qx * qw;
  4318. var limit = .4999999;
  4319. if (zAxisY < -limit) {
  4320. result.y = 2 * Math.atan2(qy, qw);
  4321. result.x = Math.PI / 2;
  4322. result.z = 0;
  4323. }
  4324. else if (zAxisY > limit) {
  4325. result.y = 2 * Math.atan2(qy, qw);
  4326. result.x = -Math.PI / 2;
  4327. result.z = 0;
  4328. }
  4329. else {
  4330. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4331. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4332. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4333. }
  4334. return this;
  4335. };
  4336. /**
  4337. * Updates the passed rotation matrix with the current Quaternion values.
  4338. * Returns the current Quaternion.
  4339. */
  4340. Quaternion.prototype.toRotationMatrix = function (result) {
  4341. var xx = this.x * this.x;
  4342. var yy = this.y * this.y;
  4343. var zz = this.z * this.z;
  4344. var xy = this.x * this.y;
  4345. var zw = this.z * this.w;
  4346. var zx = this.z * this.x;
  4347. var yw = this.y * this.w;
  4348. var yz = this.y * this.z;
  4349. var xw = this.x * this.w;
  4350. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4351. result.m[1] = 2.0 * (xy + zw);
  4352. result.m[2] = 2.0 * (zx - yw);
  4353. result.m[3] = 0;
  4354. result.m[4] = 2.0 * (xy - zw);
  4355. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4356. result.m[6] = 2.0 * (yz + xw);
  4357. result.m[7] = 0;
  4358. result.m[8] = 2.0 * (zx + yw);
  4359. result.m[9] = 2.0 * (yz - xw);
  4360. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4361. result.m[11] = 0;
  4362. result.m[12] = 0;
  4363. result.m[13] = 0;
  4364. result.m[14] = 0;
  4365. result.m[15] = 1.0;
  4366. result._markAsUpdated();
  4367. return this;
  4368. };
  4369. /**
  4370. * Updates the current Quaternion from the passed rotation matrix values.
  4371. * Returns the updated Quaternion.
  4372. */
  4373. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4374. Quaternion.FromRotationMatrixToRef(matrix, this);
  4375. return this;
  4376. };
  4377. // Statics
  4378. /**
  4379. * Returns a new Quaternion set from the passed rotation matrix values.
  4380. */
  4381. Quaternion.FromRotationMatrix = function (matrix) {
  4382. var result = new Quaternion();
  4383. Quaternion.FromRotationMatrixToRef(matrix, result);
  4384. return result;
  4385. };
  4386. /**
  4387. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4388. */
  4389. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4390. var data = matrix.m;
  4391. var m11 = data[0], m12 = data[4], m13 = data[8];
  4392. var m21 = data[1], m22 = data[5], m23 = data[9];
  4393. var m31 = data[2], m32 = data[6], m33 = data[10];
  4394. var trace = m11 + m22 + m33;
  4395. var s;
  4396. if (trace > 0) {
  4397. s = 0.5 / Math.sqrt(trace + 1.0);
  4398. result.w = 0.25 / s;
  4399. result.x = (m32 - m23) * s;
  4400. result.y = (m13 - m31) * s;
  4401. result.z = (m21 - m12) * s;
  4402. }
  4403. else if (m11 > m22 && m11 > m33) {
  4404. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4405. result.w = (m32 - m23) / s;
  4406. result.x = 0.25 * s;
  4407. result.y = (m12 + m21) / s;
  4408. result.z = (m13 + m31) / s;
  4409. }
  4410. else if (m22 > m33) {
  4411. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4412. result.w = (m13 - m31) / s;
  4413. result.x = (m12 + m21) / s;
  4414. result.y = 0.25 * s;
  4415. result.z = (m23 + m32) / s;
  4416. }
  4417. else {
  4418. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4419. result.w = (m21 - m12) / s;
  4420. result.x = (m13 + m31) / s;
  4421. result.y = (m23 + m32) / s;
  4422. result.z = 0.25 * s;
  4423. }
  4424. };
  4425. /**
  4426. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4427. */
  4428. Quaternion.Zero = function () {
  4429. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4430. };
  4431. /**
  4432. * Returns a new Quaternion as the inverted current Quaternion.
  4433. */
  4434. Quaternion.Inverse = function (q) {
  4435. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4436. };
  4437. /**
  4438. * Returns the identity Quaternion.
  4439. */
  4440. Quaternion.Identity = function () {
  4441. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4442. };
  4443. Quaternion.IsIdentity = function (quaternion) {
  4444. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4445. };
  4446. /**
  4447. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4448. */
  4449. Quaternion.RotationAxis = function (axis, angle) {
  4450. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4451. };
  4452. /**
  4453. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4454. */
  4455. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4456. var sin = Math.sin(angle / 2);
  4457. axis.normalize();
  4458. result.w = Math.cos(angle / 2);
  4459. result.x = axis.x * sin;
  4460. result.y = axis.y * sin;
  4461. result.z = axis.z * sin;
  4462. return result;
  4463. };
  4464. /**
  4465. * Retuns a new Quaternion set from the starting index of the passed array.
  4466. */
  4467. Quaternion.FromArray = function (array, offset) {
  4468. if (!offset) {
  4469. offset = 0;
  4470. }
  4471. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4472. };
  4473. /**
  4474. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4475. */
  4476. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4477. var q = new Quaternion();
  4478. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4479. return q;
  4480. };
  4481. /**
  4482. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4483. */
  4484. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4485. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4486. var halfRoll = roll * 0.5;
  4487. var halfPitch = pitch * 0.5;
  4488. var halfYaw = yaw * 0.5;
  4489. var sinRoll = Math.sin(halfRoll);
  4490. var cosRoll = Math.cos(halfRoll);
  4491. var sinPitch = Math.sin(halfPitch);
  4492. var cosPitch = Math.cos(halfPitch);
  4493. var sinYaw = Math.sin(halfYaw);
  4494. var cosYaw = Math.cos(halfYaw);
  4495. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4496. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4497. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4498. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4499. };
  4500. /**
  4501. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4502. */
  4503. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4504. var result = new Quaternion();
  4505. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4506. return result;
  4507. };
  4508. /**
  4509. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4510. */
  4511. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4512. // Produces a quaternion from Euler angles in the z-x-z orientation
  4513. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4514. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4515. var halfBeta = beta * 0.5;
  4516. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4517. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4518. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4519. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4520. };
  4521. /**
  4522. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4523. * cf to Vector3.RotationFromAxis() documentation.
  4524. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4525. */
  4526. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4527. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4528. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4529. return quat;
  4530. };
  4531. /**
  4532. * Sets the passed quaternion "ref" with 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.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4537. var rotMat = MathTmp.Matrix[0];
  4538. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4539. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4540. };
  4541. Quaternion.Slerp = function (left, right, amount) {
  4542. var result = Quaternion.Identity();
  4543. Quaternion.SlerpToRef(left, right, amount, result);
  4544. return result;
  4545. };
  4546. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4547. var num2;
  4548. var num3;
  4549. var num = amount;
  4550. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4551. var flag = false;
  4552. if (num4 < 0) {
  4553. flag = true;
  4554. num4 = -num4;
  4555. }
  4556. if (num4 > 0.999999) {
  4557. num3 = 1 - num;
  4558. num2 = flag ? -num : num;
  4559. }
  4560. else {
  4561. var num5 = Math.acos(num4);
  4562. var num6 = (1.0 / Math.sin(num5));
  4563. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4564. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4565. }
  4566. result.x = (num3 * left.x) + (num2 * right.x);
  4567. result.y = (num3 * left.y) + (num2 * right.y);
  4568. result.z = (num3 * left.z) + (num2 * right.z);
  4569. result.w = (num3 * left.w) + (num2 * right.w);
  4570. };
  4571. /**
  4572. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4573. */
  4574. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4575. var squared = amount * amount;
  4576. var cubed = amount * squared;
  4577. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4578. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4579. var part3 = (cubed - (2.0 * squared)) + amount;
  4580. var part4 = cubed - squared;
  4581. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4582. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4583. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4584. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4585. return new Quaternion(x, y, z, w);
  4586. };
  4587. return Quaternion;
  4588. }());
  4589. BABYLON.Quaternion = Quaternion;
  4590. var Matrix = /** @class */ (function () {
  4591. function Matrix() {
  4592. this._isIdentity = false;
  4593. this._isIdentityDirty = true;
  4594. this.m = new Float32Array(16);
  4595. this._markAsUpdated();
  4596. }
  4597. Matrix.prototype._markAsUpdated = function () {
  4598. this.updateFlag = Matrix._updateFlagSeed++;
  4599. this._isIdentityDirty = true;
  4600. };
  4601. // Properties
  4602. /**
  4603. * Boolean : True is the matrix is the identity matrix
  4604. */
  4605. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4606. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4607. if (this._isIdentityDirty) {
  4608. this._isIdentityDirty = false;
  4609. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4610. this._isIdentity = false;
  4611. }
  4612. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4613. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4614. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4615. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4616. this._isIdentity = false;
  4617. }
  4618. else {
  4619. this._isIdentity = true;
  4620. }
  4621. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4622. this._isIdentity = false;
  4623. }
  4624. }
  4625. return this._isIdentity;
  4626. };
  4627. /**
  4628. * Returns the matrix determinant (float).
  4629. */
  4630. Matrix.prototype.determinant = function () {
  4631. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4632. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4633. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4634. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4635. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4636. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4637. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4638. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4639. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4640. };
  4641. // Methods
  4642. /**
  4643. * Returns the matrix underlying array.
  4644. */
  4645. Matrix.prototype.toArray = function () {
  4646. return this.m;
  4647. };
  4648. /**
  4649. * Returns the matrix underlying array.
  4650. */
  4651. Matrix.prototype.asArray = function () {
  4652. return this.toArray();
  4653. };
  4654. /**
  4655. * Inverts in place the Matrix.
  4656. * Returns the Matrix inverted.
  4657. */
  4658. Matrix.prototype.invert = function () {
  4659. this.invertToRef(this);
  4660. return this;
  4661. };
  4662. /**
  4663. * Sets all the matrix elements to zero.
  4664. * Returns the Matrix.
  4665. */
  4666. Matrix.prototype.reset = function () {
  4667. for (var index = 0; index < 16; index++) {
  4668. this.m[index] = 0.0;
  4669. }
  4670. this._markAsUpdated();
  4671. return this;
  4672. };
  4673. /**
  4674. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4675. */
  4676. Matrix.prototype.add = function (other) {
  4677. var result = new Matrix();
  4678. this.addToRef(other, result);
  4679. return result;
  4680. };
  4681. /**
  4682. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4683. * Returns the Matrix.
  4684. */
  4685. Matrix.prototype.addToRef = function (other, result) {
  4686. for (var index = 0; index < 16; index++) {
  4687. result.m[index] = this.m[index] + other.m[index];
  4688. }
  4689. result._markAsUpdated();
  4690. return this;
  4691. };
  4692. /**
  4693. * Adds in place the passed matrix to the current Matrix.
  4694. * Returns the updated Matrix.
  4695. */
  4696. Matrix.prototype.addToSelf = function (other) {
  4697. for (var index = 0; index < 16; index++) {
  4698. this.m[index] += other.m[index];
  4699. }
  4700. this._markAsUpdated();
  4701. return this;
  4702. };
  4703. /**
  4704. * Sets the passed matrix with the current inverted Matrix.
  4705. * Returns the unmodified current Matrix.
  4706. */
  4707. Matrix.prototype.invertToRef = function (other) {
  4708. var l1 = this.m[0];
  4709. var l2 = this.m[1];
  4710. var l3 = this.m[2];
  4711. var l4 = this.m[3];
  4712. var l5 = this.m[4];
  4713. var l6 = this.m[5];
  4714. var l7 = this.m[6];
  4715. var l8 = this.m[7];
  4716. var l9 = this.m[8];
  4717. var l10 = this.m[9];
  4718. var l11 = this.m[10];
  4719. var l12 = this.m[11];
  4720. var l13 = this.m[12];
  4721. var l14 = this.m[13];
  4722. var l15 = this.m[14];
  4723. var l16 = this.m[15];
  4724. var l17 = (l11 * l16) - (l12 * l15);
  4725. var l18 = (l10 * l16) - (l12 * l14);
  4726. var l19 = (l10 * l15) - (l11 * l14);
  4727. var l20 = (l9 * l16) - (l12 * l13);
  4728. var l21 = (l9 * l15) - (l11 * l13);
  4729. var l22 = (l9 * l14) - (l10 * l13);
  4730. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4731. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4732. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4733. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4734. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4735. var l28 = (l7 * l16) - (l8 * l15);
  4736. var l29 = (l6 * l16) - (l8 * l14);
  4737. var l30 = (l6 * l15) - (l7 * l14);
  4738. var l31 = (l5 * l16) - (l8 * l13);
  4739. var l32 = (l5 * l15) - (l7 * l13);
  4740. var l33 = (l5 * l14) - (l6 * l13);
  4741. var l34 = (l7 * l12) - (l8 * l11);
  4742. var l35 = (l6 * l12) - (l8 * l10);
  4743. var l36 = (l6 * l11) - (l7 * l10);
  4744. var l37 = (l5 * l12) - (l8 * l9);
  4745. var l38 = (l5 * l11) - (l7 * l9);
  4746. var l39 = (l5 * l10) - (l6 * l9);
  4747. other.m[0] = l23 * l27;
  4748. other.m[4] = l24 * l27;
  4749. other.m[8] = l25 * l27;
  4750. other.m[12] = l26 * l27;
  4751. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4752. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4753. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4754. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4755. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4756. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4757. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4758. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4759. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4760. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4761. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4762. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4763. other._markAsUpdated();
  4764. return this;
  4765. };
  4766. /**
  4767. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4768. * Returns the updated Matrix.
  4769. */
  4770. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4771. this.m[12] = x;
  4772. this.m[13] = y;
  4773. this.m[14] = z;
  4774. this._markAsUpdated();
  4775. return this;
  4776. };
  4777. /**
  4778. * Inserts the translation vector in the current Matrix.
  4779. * Returns the updated Matrix.
  4780. */
  4781. Matrix.prototype.setTranslation = function (vector3) {
  4782. this.m[12] = vector3.x;
  4783. this.m[13] = vector3.y;
  4784. this.m[14] = vector3.z;
  4785. this._markAsUpdated();
  4786. return this;
  4787. };
  4788. /**
  4789. * Returns a new Vector3 as the extracted translation from the Matrix.
  4790. */
  4791. Matrix.prototype.getTranslation = function () {
  4792. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4793. };
  4794. /**
  4795. * Fill a Vector3 with the extracted translation from the Matrix.
  4796. */
  4797. Matrix.prototype.getTranslationToRef = function (result) {
  4798. result.x = this.m[12];
  4799. result.y = this.m[13];
  4800. result.z = this.m[14];
  4801. return this;
  4802. };
  4803. /**
  4804. * Remove rotation and scaling part from the Matrix.
  4805. * Returns the updated Matrix.
  4806. */
  4807. Matrix.prototype.removeRotationAndScaling = function () {
  4808. this.setRowFromFloats(0, 1, 0, 0, 0);
  4809. this.setRowFromFloats(1, 0, 1, 0, 0);
  4810. this.setRowFromFloats(2, 0, 0, 1, 0);
  4811. return this;
  4812. };
  4813. /**
  4814. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4815. */
  4816. Matrix.prototype.multiply = function (other) {
  4817. var result = new Matrix();
  4818. this.multiplyToRef(other, result);
  4819. return result;
  4820. };
  4821. /**
  4822. * Updates the current Matrix from the passed one values.
  4823. * Returns the updated Matrix.
  4824. */
  4825. Matrix.prototype.copyFrom = function (other) {
  4826. for (var index = 0; index < 16; index++) {
  4827. this.m[index] = other.m[index];
  4828. }
  4829. this._markAsUpdated();
  4830. return this;
  4831. };
  4832. /**
  4833. * Populates the passed array from the starting index with the Matrix values.
  4834. * Returns the Matrix.
  4835. */
  4836. Matrix.prototype.copyToArray = function (array, offset) {
  4837. if (offset === void 0) { offset = 0; }
  4838. for (var index = 0; index < 16; index++) {
  4839. array[offset + index] = this.m[index];
  4840. }
  4841. return this;
  4842. };
  4843. /**
  4844. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4845. */
  4846. Matrix.prototype.multiplyToRef = function (other, result) {
  4847. this.multiplyToArray(other, result.m, 0);
  4848. result._markAsUpdated();
  4849. return this;
  4850. };
  4851. /**
  4852. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4853. */
  4854. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4855. var tm0 = this.m[0];
  4856. var tm1 = this.m[1];
  4857. var tm2 = this.m[2];
  4858. var tm3 = this.m[3];
  4859. var tm4 = this.m[4];
  4860. var tm5 = this.m[5];
  4861. var tm6 = this.m[6];
  4862. var tm7 = this.m[7];
  4863. var tm8 = this.m[8];
  4864. var tm9 = this.m[9];
  4865. var tm10 = this.m[10];
  4866. var tm11 = this.m[11];
  4867. var tm12 = this.m[12];
  4868. var tm13 = this.m[13];
  4869. var tm14 = this.m[14];
  4870. var tm15 = this.m[15];
  4871. var om0 = other.m[0];
  4872. var om1 = other.m[1];
  4873. var om2 = other.m[2];
  4874. var om3 = other.m[3];
  4875. var om4 = other.m[4];
  4876. var om5 = other.m[5];
  4877. var om6 = other.m[6];
  4878. var om7 = other.m[7];
  4879. var om8 = other.m[8];
  4880. var om9 = other.m[9];
  4881. var om10 = other.m[10];
  4882. var om11 = other.m[11];
  4883. var om12 = other.m[12];
  4884. var om13 = other.m[13];
  4885. var om14 = other.m[14];
  4886. var om15 = other.m[15];
  4887. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4888. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4889. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4890. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4891. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4892. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4893. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4894. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4895. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4896. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4897. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4898. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4899. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4900. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4901. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4902. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4903. return this;
  4904. };
  4905. /**
  4906. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4907. */
  4908. Matrix.prototype.equals = function (value) {
  4909. return value &&
  4910. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4911. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4912. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4913. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4914. };
  4915. /**
  4916. * Returns a new Matrix from the current Matrix.
  4917. */
  4918. Matrix.prototype.clone = function () {
  4919. 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]);
  4920. };
  4921. /**
  4922. * Returns the string "Matrix"
  4923. */
  4924. Matrix.prototype.getClassName = function () {
  4925. return "Matrix";
  4926. };
  4927. /**
  4928. * Returns the Matrix hash code.
  4929. */
  4930. Matrix.prototype.getHashCode = function () {
  4931. var hash = this.m[0] || 0;
  4932. for (var i = 1; i < 16; i++) {
  4933. hash = (hash * 397) ^ (this.m[i] || 0);
  4934. }
  4935. return hash;
  4936. };
  4937. /**
  4938. * Decomposes the current Matrix into :
  4939. * - a scale vector3 passed as a reference to update,
  4940. * - a rotation quaternion passed as a reference to update,
  4941. * - a translation vector3 passed as a reference to update.
  4942. * Returns the true if operation was successful.
  4943. */
  4944. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4945. translation.x = this.m[12];
  4946. translation.y = this.m[13];
  4947. translation.z = this.m[14];
  4948. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4949. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4950. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4951. if (this.determinant() <= 0) {
  4952. scale.y *= -1;
  4953. }
  4954. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4955. rotation.x = 0;
  4956. rotation.y = 0;
  4957. rotation.z = 0;
  4958. rotation.w = 1;
  4959. return false;
  4960. }
  4961. 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]);
  4962. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4963. return true;
  4964. };
  4965. /**
  4966. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4967. */
  4968. Matrix.prototype.getRotationMatrix = function () {
  4969. var result = Matrix.Identity();
  4970. this.getRotationMatrixToRef(result);
  4971. return result;
  4972. };
  4973. /**
  4974. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4975. * Returns the current Matrix.
  4976. */
  4977. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4978. var m = this.m;
  4979. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4980. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4981. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4982. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4983. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4984. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4985. 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);
  4986. return this;
  4987. };
  4988. // Statics
  4989. /**
  4990. * Returns a new Matrix set from the starting index of the passed array.
  4991. */
  4992. Matrix.FromArray = function (array, offset) {
  4993. var result = new Matrix();
  4994. if (!offset) {
  4995. offset = 0;
  4996. }
  4997. Matrix.FromArrayToRef(array, offset, result);
  4998. return result;
  4999. };
  5000. /**
  5001. * Sets the passed "result" matrix from the starting index of the passed array.
  5002. */
  5003. Matrix.FromArrayToRef = function (array, offset, result) {
  5004. for (var index = 0; index < 16; index++) {
  5005. result.m[index] = array[index + offset];
  5006. }
  5007. result._markAsUpdated();
  5008. };
  5009. /**
  5010. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5011. */
  5012. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5013. for (var index = 0; index < 16; index++) {
  5014. result.m[index] = array[index + offset] * scale;
  5015. }
  5016. result._markAsUpdated();
  5017. };
  5018. /**
  5019. * Sets the passed matrix "result" with the 16 passed floats.
  5020. */
  5021. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5022. result.m[0] = initialM11;
  5023. result.m[1] = initialM12;
  5024. result.m[2] = initialM13;
  5025. result.m[3] = initialM14;
  5026. result.m[4] = initialM21;
  5027. result.m[5] = initialM22;
  5028. result.m[6] = initialM23;
  5029. result.m[7] = initialM24;
  5030. result.m[8] = initialM31;
  5031. result.m[9] = initialM32;
  5032. result.m[10] = initialM33;
  5033. result.m[11] = initialM34;
  5034. result.m[12] = initialM41;
  5035. result.m[13] = initialM42;
  5036. result.m[14] = initialM43;
  5037. result.m[15] = initialM44;
  5038. result._markAsUpdated();
  5039. };
  5040. /**
  5041. * Returns the index-th row of the current matrix as a new Vector4.
  5042. */
  5043. Matrix.prototype.getRow = function (index) {
  5044. if (index < 0 || index > 3) {
  5045. return null;
  5046. }
  5047. var i = index * 4;
  5048. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5049. };
  5050. /**
  5051. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5052. * Returns the updated Matrix.
  5053. */
  5054. Matrix.prototype.setRow = function (index, row) {
  5055. if (index < 0 || index > 3) {
  5056. return this;
  5057. }
  5058. var i = index * 4;
  5059. this.m[i + 0] = row.x;
  5060. this.m[i + 1] = row.y;
  5061. this.m[i + 2] = row.z;
  5062. this.m[i + 3] = row.w;
  5063. this._markAsUpdated();
  5064. return this;
  5065. };
  5066. /**
  5067. * Compute the transpose of the matrix.
  5068. * Returns a new Matrix.
  5069. */
  5070. Matrix.prototype.transpose = function () {
  5071. return Matrix.Transpose(this);
  5072. };
  5073. /**
  5074. * Compute the transpose of the matrix.
  5075. * Returns the current matrix.
  5076. */
  5077. Matrix.prototype.transposeToRef = function (result) {
  5078. Matrix.TransposeToRef(this, result);
  5079. return this;
  5080. };
  5081. /**
  5082. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5083. * Returns the updated Matrix.
  5084. */
  5085. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5086. if (index < 0 || index > 3) {
  5087. return this;
  5088. }
  5089. var i = index * 4;
  5090. this.m[i + 0] = x;
  5091. this.m[i + 1] = y;
  5092. this.m[i + 2] = z;
  5093. this.m[i + 3] = w;
  5094. this._markAsUpdated();
  5095. return this;
  5096. };
  5097. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5098. /**
  5099. * Static identity matrix to be used as readonly matrix
  5100. * Must not be updated.
  5101. */
  5102. get: function () {
  5103. return Matrix._identityReadOnly;
  5104. },
  5105. enumerable: true,
  5106. configurable: true
  5107. });
  5108. /**
  5109. * Returns a new Matrix set from the 16 passed floats.
  5110. */
  5111. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5112. var result = new Matrix();
  5113. result.m[0] = initialM11;
  5114. result.m[1] = initialM12;
  5115. result.m[2] = initialM13;
  5116. result.m[3] = initialM14;
  5117. result.m[4] = initialM21;
  5118. result.m[5] = initialM22;
  5119. result.m[6] = initialM23;
  5120. result.m[7] = initialM24;
  5121. result.m[8] = initialM31;
  5122. result.m[9] = initialM32;
  5123. result.m[10] = initialM33;
  5124. result.m[11] = initialM34;
  5125. result.m[12] = initialM41;
  5126. result.m[13] = initialM42;
  5127. result.m[14] = initialM43;
  5128. result.m[15] = initialM44;
  5129. return result;
  5130. };
  5131. /**
  5132. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5133. */
  5134. Matrix.Compose = function (scale, rotation, translation) {
  5135. var result = Matrix.Identity();
  5136. Matrix.ComposeToRef(scale, rotation, translation, result);
  5137. return result;
  5138. };
  5139. /**
  5140. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5141. */
  5142. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5143. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5144. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5145. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5146. result.setTranslation(translation);
  5147. };
  5148. /**
  5149. * Returns a new indentity Matrix.
  5150. */
  5151. Matrix.Identity = function () {
  5152. 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);
  5153. };
  5154. /**
  5155. * Sets the passed "result" as an identity matrix.
  5156. */
  5157. Matrix.IdentityToRef = function (result) {
  5158. 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);
  5159. };
  5160. /**
  5161. * Returns a new zero Matrix.
  5162. */
  5163. Matrix.Zero = function () {
  5164. 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);
  5165. };
  5166. /**
  5167. * Returns a new rotation matrix for "angle" radians around the X axis.
  5168. */
  5169. Matrix.RotationX = function (angle) {
  5170. var result = new Matrix();
  5171. Matrix.RotationXToRef(angle, result);
  5172. return result;
  5173. };
  5174. /**
  5175. * Returns a new Matrix as the passed inverted one.
  5176. */
  5177. Matrix.Invert = function (source) {
  5178. var result = new Matrix();
  5179. source.invertToRef(result);
  5180. return result;
  5181. };
  5182. /**
  5183. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5184. */
  5185. Matrix.RotationXToRef = function (angle, result) {
  5186. var s = Math.sin(angle);
  5187. var c = Math.cos(angle);
  5188. result.m[0] = 1.0;
  5189. result.m[15] = 1.0;
  5190. result.m[5] = c;
  5191. result.m[10] = c;
  5192. result.m[9] = -s;
  5193. result.m[6] = s;
  5194. result.m[1] = 0.0;
  5195. result.m[2] = 0.0;
  5196. result.m[3] = 0.0;
  5197. result.m[4] = 0.0;
  5198. result.m[7] = 0.0;
  5199. result.m[8] = 0.0;
  5200. result.m[11] = 0.0;
  5201. result.m[12] = 0.0;
  5202. result.m[13] = 0.0;
  5203. result.m[14] = 0.0;
  5204. result._markAsUpdated();
  5205. };
  5206. /**
  5207. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5208. */
  5209. Matrix.RotationY = function (angle) {
  5210. var result = new Matrix();
  5211. Matrix.RotationYToRef(angle, result);
  5212. return result;
  5213. };
  5214. /**
  5215. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5216. */
  5217. Matrix.RotationYToRef = function (angle, result) {
  5218. var s = Math.sin(angle);
  5219. var c = Math.cos(angle);
  5220. result.m[5] = 1.0;
  5221. result.m[15] = 1.0;
  5222. result.m[0] = c;
  5223. result.m[2] = -s;
  5224. result.m[8] = s;
  5225. result.m[10] = c;
  5226. result.m[1] = 0.0;
  5227. result.m[3] = 0.0;
  5228. result.m[4] = 0.0;
  5229. result.m[6] = 0.0;
  5230. result.m[7] = 0.0;
  5231. result.m[9] = 0.0;
  5232. result.m[11] = 0.0;
  5233. result.m[12] = 0.0;
  5234. result.m[13] = 0.0;
  5235. result.m[14] = 0.0;
  5236. result._markAsUpdated();
  5237. };
  5238. /**
  5239. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5240. */
  5241. Matrix.RotationZ = function (angle) {
  5242. var result = new Matrix();
  5243. Matrix.RotationZToRef(angle, result);
  5244. return result;
  5245. };
  5246. /**
  5247. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5248. */
  5249. Matrix.RotationZToRef = function (angle, result) {
  5250. var s = Math.sin(angle);
  5251. var c = Math.cos(angle);
  5252. result.m[10] = 1.0;
  5253. result.m[15] = 1.0;
  5254. result.m[0] = c;
  5255. result.m[1] = s;
  5256. result.m[4] = -s;
  5257. result.m[5] = c;
  5258. result.m[2] = 0.0;
  5259. result.m[3] = 0.0;
  5260. result.m[6] = 0.0;
  5261. result.m[7] = 0.0;
  5262. result.m[8] = 0.0;
  5263. result.m[9] = 0.0;
  5264. result.m[11] = 0.0;
  5265. result.m[12] = 0.0;
  5266. result.m[13] = 0.0;
  5267. result.m[14] = 0.0;
  5268. result._markAsUpdated();
  5269. };
  5270. /**
  5271. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5272. */
  5273. Matrix.RotationAxis = function (axis, angle) {
  5274. var result = Matrix.Zero();
  5275. Matrix.RotationAxisToRef(axis, angle, result);
  5276. return result;
  5277. };
  5278. /**
  5279. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5280. */
  5281. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5282. var s = Math.sin(-angle);
  5283. var c = Math.cos(-angle);
  5284. var c1 = 1 - c;
  5285. axis.normalize();
  5286. result.m[0] = (axis.x * axis.x) * c1 + c;
  5287. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5288. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5289. result.m[3] = 0.0;
  5290. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5291. result.m[5] = (axis.y * axis.y) * c1 + c;
  5292. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5293. result.m[7] = 0.0;
  5294. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5295. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5296. result.m[10] = (axis.z * axis.z) * c1 + c;
  5297. result.m[11] = 0.0;
  5298. result.m[15] = 1.0;
  5299. result._markAsUpdated();
  5300. };
  5301. /**
  5302. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5303. */
  5304. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5305. var result = new Matrix();
  5306. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5307. return result;
  5308. };
  5309. /**
  5310. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5311. */
  5312. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5313. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5314. this._tempQuaternion.toRotationMatrix(result);
  5315. };
  5316. /**
  5317. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5318. */
  5319. Matrix.Scaling = function (x, y, z) {
  5320. var result = Matrix.Zero();
  5321. Matrix.ScalingToRef(x, y, z, result);
  5322. return result;
  5323. };
  5324. /**
  5325. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5326. */
  5327. Matrix.ScalingToRef = function (x, y, z, result) {
  5328. result.m[0] = x;
  5329. result.m[1] = 0.0;
  5330. result.m[2] = 0.0;
  5331. result.m[3] = 0.0;
  5332. result.m[4] = 0.0;
  5333. result.m[5] = y;
  5334. result.m[6] = 0.0;
  5335. result.m[7] = 0.0;
  5336. result.m[8] = 0.0;
  5337. result.m[9] = 0.0;
  5338. result.m[10] = z;
  5339. result.m[11] = 0.0;
  5340. result.m[12] = 0.0;
  5341. result.m[13] = 0.0;
  5342. result.m[14] = 0.0;
  5343. result.m[15] = 1.0;
  5344. result._markAsUpdated();
  5345. };
  5346. /**
  5347. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5348. */
  5349. Matrix.Translation = function (x, y, z) {
  5350. var result = Matrix.Identity();
  5351. Matrix.TranslationToRef(x, y, z, result);
  5352. return result;
  5353. };
  5354. /**
  5355. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5356. */
  5357. Matrix.TranslationToRef = function (x, y, z, result) {
  5358. 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);
  5359. };
  5360. /**
  5361. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5362. */
  5363. Matrix.Lerp = function (startValue, endValue, gradient) {
  5364. var result = Matrix.Zero();
  5365. for (var index = 0; index < 16; index++) {
  5366. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5367. }
  5368. result._markAsUpdated();
  5369. return result;
  5370. };
  5371. /**
  5372. * Returns a new Matrix whose values are computed by :
  5373. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5374. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5375. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5376. */
  5377. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5378. var startScale = new Vector3(0, 0, 0);
  5379. var startRotation = new Quaternion();
  5380. var startTranslation = new Vector3(0, 0, 0);
  5381. startValue.decompose(startScale, startRotation, startTranslation);
  5382. var endScale = new Vector3(0, 0, 0);
  5383. var endRotation = new Quaternion();
  5384. var endTranslation = new Vector3(0, 0, 0);
  5385. endValue.decompose(endScale, endRotation, endTranslation);
  5386. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5387. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5388. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5389. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5390. };
  5391. /**
  5392. * 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".
  5393. * This methods works for a Left-Handed system.
  5394. */
  5395. Matrix.LookAtLH = function (eye, target, up) {
  5396. var result = Matrix.Zero();
  5397. Matrix.LookAtLHToRef(eye, target, up, result);
  5398. return result;
  5399. };
  5400. /**
  5401. * 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".
  5402. * This methods works for a Left-Handed system.
  5403. */
  5404. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5405. // Z axis
  5406. target.subtractToRef(eye, this._zAxis);
  5407. this._zAxis.normalize();
  5408. // X axis
  5409. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5410. if (this._xAxis.lengthSquared() === 0) {
  5411. this._xAxis.x = 1.0;
  5412. }
  5413. else {
  5414. this._xAxis.normalize();
  5415. }
  5416. // Y axis
  5417. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5418. this._yAxis.normalize();
  5419. // Eye angles
  5420. var ex = -Vector3.Dot(this._xAxis, eye);
  5421. var ey = -Vector3.Dot(this._yAxis, eye);
  5422. var ez = -Vector3.Dot(this._zAxis, eye);
  5423. 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);
  5424. };
  5425. /**
  5426. * 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".
  5427. * This methods works for a Right-Handed system.
  5428. */
  5429. Matrix.LookAtRH = function (eye, target, up) {
  5430. var result = Matrix.Zero();
  5431. Matrix.LookAtRHToRef(eye, target, up, result);
  5432. return result;
  5433. };
  5434. /**
  5435. * 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".
  5436. * This methods works for a Left-Handed system.
  5437. */
  5438. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5439. // Z axis
  5440. eye.subtractToRef(target, this._zAxis);
  5441. this._zAxis.normalize();
  5442. // X axis
  5443. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5444. if (this._xAxis.lengthSquared() === 0) {
  5445. this._xAxis.x = 1.0;
  5446. }
  5447. else {
  5448. this._xAxis.normalize();
  5449. }
  5450. // Y axis
  5451. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5452. this._yAxis.normalize();
  5453. // Eye angles
  5454. var ex = -Vector3.Dot(this._xAxis, eye);
  5455. var ey = -Vector3.Dot(this._yAxis, eye);
  5456. var ez = -Vector3.Dot(this._zAxis, eye);
  5457. 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);
  5458. };
  5459. /**
  5460. * 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.
  5461. */
  5462. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5463. var matrix = Matrix.Zero();
  5464. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5465. return matrix;
  5466. };
  5467. /**
  5468. * 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.
  5469. */
  5470. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5471. var n = znear;
  5472. var f = zfar;
  5473. var a = 2.0 / width;
  5474. var b = 2.0 / height;
  5475. var c = 2.0 / (f - n);
  5476. var d = -(f + n) / (f - n);
  5477. 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);
  5478. };
  5479. /**
  5480. * 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.
  5481. */
  5482. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5483. var matrix = Matrix.Zero();
  5484. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, 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 : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5489. */
  5490. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5491. var n = znear;
  5492. var f = zfar;
  5493. var a = 2.0 / (right - left);
  5494. var b = 2.0 / (top - bottom);
  5495. var c = 2.0 / (f - n);
  5496. var d = -(f + n) / (f - n);
  5497. var i0 = (left + right) / (left - right);
  5498. var i1 = (top + bottom) / (bottom - top);
  5499. 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);
  5500. };
  5501. /**
  5502. * 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.
  5503. */
  5504. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5505. var matrix = Matrix.Zero();
  5506. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5507. return matrix;
  5508. };
  5509. /**
  5510. * 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.
  5511. */
  5512. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5513. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5514. result.m[10] *= -1.0;
  5515. };
  5516. /**
  5517. * 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.
  5518. */
  5519. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5520. var matrix = Matrix.Zero();
  5521. var n = znear;
  5522. var f = zfar;
  5523. var a = 2.0 * n / width;
  5524. var b = 2.0 * n / height;
  5525. var c = (f + n) / (f - n);
  5526. var d = -2.0 * f * n / (f - n);
  5527. 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);
  5528. return matrix;
  5529. };
  5530. /**
  5531. * 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.
  5532. */
  5533. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5534. var matrix = Matrix.Zero();
  5535. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5536. return matrix;
  5537. };
  5538. /**
  5539. * 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.
  5540. */
  5541. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5542. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5543. var n = znear;
  5544. var f = zfar;
  5545. var t = 1.0 / (Math.tan(fov * 0.5));
  5546. var a = isVerticalFovFixed ? (t / aspect) : t;
  5547. var b = isVerticalFovFixed ? t : (t * aspect);
  5548. var c = (f + n) / (f - n);
  5549. var d = -2.0 * f * n / (f - n);
  5550. 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);
  5551. };
  5552. /**
  5553. * 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.
  5554. */
  5555. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5556. var matrix = Matrix.Zero();
  5557. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5558. return matrix;
  5559. };
  5560. /**
  5561. * 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.
  5562. */
  5563. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5564. //alternatively this could be expressed as:
  5565. // m = PerspectiveFovLHToRef
  5566. // m[10] *= -1.0;
  5567. // m[11] *= -1.0;
  5568. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5569. var n = znear;
  5570. var f = zfar;
  5571. var t = 1.0 / (Math.tan(fov * 0.5));
  5572. var a = isVerticalFovFixed ? (t / aspect) : t;
  5573. var b = isVerticalFovFixed ? t : (t * aspect);
  5574. var c = -(f + n) / (f - n);
  5575. var d = -2 * f * n / (f - n);
  5576. 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);
  5577. };
  5578. /**
  5579. * 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.
  5580. */
  5581. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5582. if (rightHanded === void 0) { rightHanded = false; }
  5583. var rightHandedFactor = rightHanded ? -1 : 1;
  5584. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5585. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5586. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5587. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5588. var xScale = 2.0 / (leftTan + rightTan);
  5589. var yScale = 2.0 / (upTan + downTan);
  5590. result.m[0] = xScale;
  5591. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5592. result.m[5] = yScale;
  5593. result.m[6] = result.m[7] = 0.0;
  5594. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5595. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5596. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5597. result.m[10] = -zfar / (znear - zfar);
  5598. result.m[11] = 1.0 * rightHandedFactor;
  5599. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5600. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5601. // result.m[14] = (znear * zfar) / (znear - zfar);
  5602. result._markAsUpdated();
  5603. };
  5604. /**
  5605. * Returns the final transformation matrix : world * view * projection * viewport
  5606. */
  5607. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5608. var cw = viewport.width;
  5609. var ch = viewport.height;
  5610. var cx = viewport.x;
  5611. var cy = viewport.y;
  5612. 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);
  5613. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5614. };
  5615. /**
  5616. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5617. */
  5618. Matrix.GetAsMatrix2x2 = function (matrix) {
  5619. return new Float32Array([
  5620. matrix.m[0], matrix.m[1],
  5621. matrix.m[4], matrix.m[5]
  5622. ]);
  5623. };
  5624. /**
  5625. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5626. */
  5627. Matrix.GetAsMatrix3x3 = function (matrix) {
  5628. return new Float32Array([
  5629. matrix.m[0], matrix.m[1], matrix.m[2],
  5630. matrix.m[4], matrix.m[5], matrix.m[6],
  5631. matrix.m[8], matrix.m[9], matrix.m[10]
  5632. ]);
  5633. };
  5634. /**
  5635. * Compute the transpose of the passed Matrix.
  5636. * Returns a new Matrix.
  5637. */
  5638. Matrix.Transpose = function (matrix) {
  5639. var result = new Matrix();
  5640. Matrix.TransposeToRef(matrix, result);
  5641. return result;
  5642. };
  5643. /**
  5644. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5645. */
  5646. Matrix.TransposeToRef = function (matrix, result) {
  5647. result.m[0] = matrix.m[0];
  5648. result.m[1] = matrix.m[4];
  5649. result.m[2] = matrix.m[8];
  5650. result.m[3] = matrix.m[12];
  5651. result.m[4] = matrix.m[1];
  5652. result.m[5] = matrix.m[5];
  5653. result.m[6] = matrix.m[9];
  5654. result.m[7] = matrix.m[13];
  5655. result.m[8] = matrix.m[2];
  5656. result.m[9] = matrix.m[6];
  5657. result.m[10] = matrix.m[10];
  5658. result.m[11] = matrix.m[14];
  5659. result.m[12] = matrix.m[3];
  5660. result.m[13] = matrix.m[7];
  5661. result.m[14] = matrix.m[11];
  5662. result.m[15] = matrix.m[15];
  5663. };
  5664. /**
  5665. * Returns a new Matrix as the reflection matrix across the passed plane.
  5666. */
  5667. Matrix.Reflection = function (plane) {
  5668. var matrix = new Matrix();
  5669. Matrix.ReflectionToRef(plane, matrix);
  5670. return matrix;
  5671. };
  5672. /**
  5673. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5674. */
  5675. Matrix.ReflectionToRef = function (plane, result) {
  5676. plane.normalize();
  5677. var x = plane.normal.x;
  5678. var y = plane.normal.y;
  5679. var z = plane.normal.z;
  5680. var temp = -2 * x;
  5681. var temp2 = -2 * y;
  5682. var temp3 = -2 * z;
  5683. result.m[0] = (temp * x) + 1;
  5684. result.m[1] = temp2 * x;
  5685. result.m[2] = temp3 * x;
  5686. result.m[3] = 0.0;
  5687. result.m[4] = temp * y;
  5688. result.m[5] = (temp2 * y) + 1;
  5689. result.m[6] = temp3 * y;
  5690. result.m[7] = 0.0;
  5691. result.m[8] = temp * z;
  5692. result.m[9] = temp2 * z;
  5693. result.m[10] = (temp3 * z) + 1;
  5694. result.m[11] = 0.0;
  5695. result.m[12] = temp * plane.d;
  5696. result.m[13] = temp2 * plane.d;
  5697. result.m[14] = temp3 * plane.d;
  5698. result.m[15] = 1.0;
  5699. result._markAsUpdated();
  5700. };
  5701. /**
  5702. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5703. */
  5704. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5705. result.m[0] = xaxis.x;
  5706. result.m[1] = xaxis.y;
  5707. result.m[2] = xaxis.z;
  5708. result.m[3] = 0.0;
  5709. result.m[4] = yaxis.x;
  5710. result.m[5] = yaxis.y;
  5711. result.m[6] = yaxis.z;
  5712. result.m[7] = 0.0;
  5713. result.m[8] = zaxis.x;
  5714. result.m[9] = zaxis.y;
  5715. result.m[10] = zaxis.z;
  5716. result.m[11] = 0.0;
  5717. result.m[12] = 0.0;
  5718. result.m[13] = 0.0;
  5719. result.m[14] = 0.0;
  5720. result.m[15] = 1.0;
  5721. result._markAsUpdated();
  5722. };
  5723. /**
  5724. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5725. */
  5726. Matrix.FromQuaternionToRef = function (quat, result) {
  5727. var xx = quat.x * quat.x;
  5728. var yy = quat.y * quat.y;
  5729. var zz = quat.z * quat.z;
  5730. var xy = quat.x * quat.y;
  5731. var zw = quat.z * quat.w;
  5732. var zx = quat.z * quat.x;
  5733. var yw = quat.y * quat.w;
  5734. var yz = quat.y * quat.z;
  5735. var xw = quat.x * quat.w;
  5736. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5737. result.m[1] = 2.0 * (xy + zw);
  5738. result.m[2] = 2.0 * (zx - yw);
  5739. result.m[3] = 0.0;
  5740. result.m[4] = 2.0 * (xy - zw);
  5741. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5742. result.m[6] = 2.0 * (yz + xw);
  5743. result.m[7] = 0.0;
  5744. result.m[8] = 2.0 * (zx + yw);
  5745. result.m[9] = 2.0 * (yz - xw);
  5746. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5747. result.m[11] = 0.0;
  5748. result.m[12] = 0.0;
  5749. result.m[13] = 0.0;
  5750. result.m[14] = 0.0;
  5751. result.m[15] = 1.0;
  5752. result._markAsUpdated();
  5753. };
  5754. Matrix._tempQuaternion = new Quaternion();
  5755. Matrix._xAxis = Vector3.Zero();
  5756. Matrix._yAxis = Vector3.Zero();
  5757. Matrix._zAxis = Vector3.Zero();
  5758. Matrix._updateFlagSeed = 0;
  5759. Matrix._identityReadOnly = Matrix.Identity();
  5760. return Matrix;
  5761. }());
  5762. BABYLON.Matrix = Matrix;
  5763. var Plane = /** @class */ (function () {
  5764. /**
  5765. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5766. */
  5767. function Plane(a, b, c, d) {
  5768. this.normal = new Vector3(a, b, c);
  5769. this.d = d;
  5770. }
  5771. /**
  5772. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5773. */
  5774. Plane.prototype.asArray = function () {
  5775. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5776. };
  5777. // Methods
  5778. /**
  5779. * Returns a new plane copied from the current Plane.
  5780. */
  5781. Plane.prototype.clone = function () {
  5782. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5783. };
  5784. /**
  5785. * Returns the string "Plane".
  5786. */
  5787. Plane.prototype.getClassName = function () {
  5788. return "Plane";
  5789. };
  5790. /**
  5791. * Returns the Plane hash code.
  5792. */
  5793. Plane.prototype.getHashCode = function () {
  5794. var hash = this.normal.getHashCode();
  5795. hash = (hash * 397) ^ (this.d || 0);
  5796. return hash;
  5797. };
  5798. /**
  5799. * Normalize the current Plane in place.
  5800. * Returns the updated Plane.
  5801. */
  5802. Plane.prototype.normalize = function () {
  5803. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5804. var magnitude = 0.0;
  5805. if (norm !== 0) {
  5806. magnitude = 1.0 / norm;
  5807. }
  5808. this.normal.x *= magnitude;
  5809. this.normal.y *= magnitude;
  5810. this.normal.z *= magnitude;
  5811. this.d *= magnitude;
  5812. return this;
  5813. };
  5814. /**
  5815. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5816. */
  5817. Plane.prototype.transform = function (transformation) {
  5818. var transposedMatrix = Matrix.Transpose(transformation);
  5819. var x = this.normal.x;
  5820. var y = this.normal.y;
  5821. var z = this.normal.z;
  5822. var d = this.d;
  5823. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5824. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5825. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5826. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5827. return new Plane(normalX, normalY, normalZ, finalD);
  5828. };
  5829. /**
  5830. * Returns the dot product (float) of the point coordinates and the plane normal.
  5831. */
  5832. Plane.prototype.dotCoordinate = function (point) {
  5833. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5834. };
  5835. /**
  5836. * Updates the current Plane from the plane defined by the three passed points.
  5837. * Returns the updated Plane.
  5838. */
  5839. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5840. var x1 = point2.x - point1.x;
  5841. var y1 = point2.y - point1.y;
  5842. var z1 = point2.z - point1.z;
  5843. var x2 = point3.x - point1.x;
  5844. var y2 = point3.y - point1.y;
  5845. var z2 = point3.z - point1.z;
  5846. var yz = (y1 * z2) - (z1 * y2);
  5847. var xz = (z1 * x2) - (x1 * z2);
  5848. var xy = (x1 * y2) - (y1 * x2);
  5849. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5850. var invPyth;
  5851. if (pyth !== 0) {
  5852. invPyth = 1.0 / pyth;
  5853. }
  5854. else {
  5855. invPyth = 0.0;
  5856. }
  5857. this.normal.x = yz * invPyth;
  5858. this.normal.y = xz * invPyth;
  5859. this.normal.z = xy * invPyth;
  5860. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5861. return this;
  5862. };
  5863. /**
  5864. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5865. */
  5866. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5867. var dot = Vector3.Dot(this.normal, direction);
  5868. return (dot <= epsilon);
  5869. };
  5870. /**
  5871. * Returns the signed distance (float) from the passed point to the Plane.
  5872. */
  5873. Plane.prototype.signedDistanceTo = function (point) {
  5874. return Vector3.Dot(point, this.normal) + this.d;
  5875. };
  5876. // Statics
  5877. /**
  5878. * Returns a new Plane from the passed array.
  5879. */
  5880. Plane.FromArray = function (array) {
  5881. return new Plane(array[0], array[1], array[2], array[3]);
  5882. };
  5883. /**
  5884. * Returns a new Plane defined by the three passed points.
  5885. */
  5886. Plane.FromPoints = function (point1, point2, point3) {
  5887. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5888. result.copyFromPoints(point1, point2, point3);
  5889. return result;
  5890. };
  5891. /**
  5892. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5893. * Note : the vector "normal" is updated because normalized.
  5894. */
  5895. Plane.FromPositionAndNormal = function (origin, normal) {
  5896. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5897. normal.normalize();
  5898. result.normal = normal;
  5899. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5900. return result;
  5901. };
  5902. /**
  5903. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5904. */
  5905. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5906. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5907. return Vector3.Dot(point, normal) + d;
  5908. };
  5909. return Plane;
  5910. }());
  5911. BABYLON.Plane = Plane;
  5912. var Viewport = /** @class */ (function () {
  5913. /**
  5914. * Creates a Viewport object located at (x, y) and sized (width, height).
  5915. */
  5916. function Viewport(x, y, width, height) {
  5917. this.x = x;
  5918. this.y = y;
  5919. this.width = width;
  5920. this.height = height;
  5921. }
  5922. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5923. if (renderWidthOrEngine.getRenderWidth) {
  5924. var engine = renderWidthOrEngine;
  5925. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5926. }
  5927. var renderWidth = renderWidthOrEngine;
  5928. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5929. };
  5930. /**
  5931. * Returns a new Viewport copied from the current one.
  5932. */
  5933. Viewport.prototype.clone = function () {
  5934. return new Viewport(this.x, this.y, this.width, this.height);
  5935. };
  5936. return Viewport;
  5937. }());
  5938. BABYLON.Viewport = Viewport;
  5939. var Frustum = /** @class */ (function () {
  5940. function Frustum() {
  5941. }
  5942. /**
  5943. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5944. */
  5945. Frustum.GetPlanes = function (transform) {
  5946. var frustumPlanes = [];
  5947. for (var index = 0; index < 6; index++) {
  5948. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5949. }
  5950. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5951. return frustumPlanes;
  5952. };
  5953. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5954. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5955. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5956. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5957. frustumPlane.d = transform.m[15] + transform.m[14];
  5958. frustumPlane.normalize();
  5959. };
  5960. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5961. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5962. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5963. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5964. frustumPlane.d = transform.m[15] - transform.m[14];
  5965. frustumPlane.normalize();
  5966. };
  5967. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5968. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5969. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5970. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5971. frustumPlane.d = transform.m[15] + transform.m[12];
  5972. frustumPlane.normalize();
  5973. };
  5974. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5975. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5976. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5977. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5978. frustumPlane.d = transform.m[15] - transform.m[12];
  5979. frustumPlane.normalize();
  5980. };
  5981. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5982. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5983. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5984. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5985. frustumPlane.d = transform.m[15] - transform.m[13];
  5986. frustumPlane.normalize();
  5987. };
  5988. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5989. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5990. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5991. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5992. frustumPlane.d = transform.m[15] + transform.m[13];
  5993. frustumPlane.normalize();
  5994. };
  5995. /**
  5996. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5997. */
  5998. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5999. // Near
  6000. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6001. // Far
  6002. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6003. // Left
  6004. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6005. // Right
  6006. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6007. // Top
  6008. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6009. // Bottom
  6010. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6011. };
  6012. return Frustum;
  6013. }());
  6014. BABYLON.Frustum = Frustum;
  6015. var Space;
  6016. (function (Space) {
  6017. Space[Space["LOCAL"] = 0] = "LOCAL";
  6018. Space[Space["WORLD"] = 1] = "WORLD";
  6019. Space[Space["BONE"] = 2] = "BONE";
  6020. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6021. var Axis = /** @class */ (function () {
  6022. function Axis() {
  6023. }
  6024. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6025. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6026. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6027. return Axis;
  6028. }());
  6029. BABYLON.Axis = Axis;
  6030. ;
  6031. var BezierCurve = /** @class */ (function () {
  6032. function BezierCurve() {
  6033. }
  6034. /**
  6035. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6036. */
  6037. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6038. // Extract X (which is equal to time here)
  6039. var f0 = 1 - 3 * x2 + 3 * x1;
  6040. var f1 = 3 * x2 - 6 * x1;
  6041. var f2 = 3 * x1;
  6042. var refinedT = t;
  6043. for (var i = 0; i < 5; i++) {
  6044. var refinedT2 = refinedT * refinedT;
  6045. var refinedT3 = refinedT2 * refinedT;
  6046. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6047. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6048. refinedT -= (x - t) * slope;
  6049. refinedT = Math.min(1, Math.max(0, refinedT));
  6050. }
  6051. // Resolve cubic bezier for the given x
  6052. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6053. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6054. Math.pow(refinedT, 3);
  6055. };
  6056. return BezierCurve;
  6057. }());
  6058. BABYLON.BezierCurve = BezierCurve;
  6059. var Orientation;
  6060. (function (Orientation) {
  6061. Orientation[Orientation["CW"] = 0] = "CW";
  6062. Orientation[Orientation["CCW"] = 1] = "CCW";
  6063. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6064. var Angle = /** @class */ (function () {
  6065. /**
  6066. * Creates an Angle object of "radians" radians (float).
  6067. */
  6068. function Angle(radians) {
  6069. var _this = this;
  6070. /**
  6071. * Returns the Angle value in degrees (float).
  6072. */
  6073. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6074. /**
  6075. * Returns the Angle value in radians (float).
  6076. */
  6077. this.radians = function () { return _this._radians; };
  6078. this._radians = radians;
  6079. if (this._radians < 0.0)
  6080. this._radians += (2.0 * Math.PI);
  6081. }
  6082. /**
  6083. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6084. */
  6085. Angle.BetweenTwoPoints = function (a, b) {
  6086. var delta = b.subtract(a);
  6087. var theta = Math.atan2(delta.y, delta.x);
  6088. return new Angle(theta);
  6089. };
  6090. /**
  6091. * Returns a new Angle object from the passed float in radians.
  6092. */
  6093. Angle.FromRadians = function (radians) {
  6094. return new Angle(radians);
  6095. };
  6096. /**
  6097. * Returns a new Angle object from the passed float in degrees.
  6098. */
  6099. Angle.FromDegrees = function (degrees) {
  6100. return new Angle(degrees * Math.PI / 180.0);
  6101. };
  6102. return Angle;
  6103. }());
  6104. BABYLON.Angle = Angle;
  6105. var Arc2 = /** @class */ (function () {
  6106. /**
  6107. * Creates an Arc object from the three passed points : start, middle and end.
  6108. */
  6109. function Arc2(startPoint, midPoint, endPoint) {
  6110. this.startPoint = startPoint;
  6111. this.midPoint = midPoint;
  6112. this.endPoint = endPoint;
  6113. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6114. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6115. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6116. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6117. 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);
  6118. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6119. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6120. var a1 = this.startAngle.degrees();
  6121. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6122. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6123. // angles correction
  6124. if (a2 - a1 > +180.0)
  6125. a2 -= 360.0;
  6126. if (a2 - a1 < -180.0)
  6127. a2 += 360.0;
  6128. if (a3 - a2 > +180.0)
  6129. a3 -= 360.0;
  6130. if (a3 - a2 < -180.0)
  6131. a3 += 360.0;
  6132. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6133. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6134. }
  6135. return Arc2;
  6136. }());
  6137. BABYLON.Arc2 = Arc2;
  6138. var Path2 = /** @class */ (function () {
  6139. /**
  6140. * Creates a Path2 object from the starting 2D coordinates x and y.
  6141. */
  6142. function Path2(x, y) {
  6143. this._points = new Array();
  6144. this._length = 0.0;
  6145. this.closed = false;
  6146. this._points.push(new Vector2(x, y));
  6147. }
  6148. /**
  6149. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6150. * Returns the updated Path2.
  6151. */
  6152. Path2.prototype.addLineTo = function (x, y) {
  6153. if (this.closed) {
  6154. //Tools.Error("cannot add lines to closed paths");
  6155. return this;
  6156. }
  6157. var newPoint = new Vector2(x, y);
  6158. var previousPoint = this._points[this._points.length - 1];
  6159. this._points.push(newPoint);
  6160. this._length += newPoint.subtract(previousPoint).length();
  6161. return this;
  6162. };
  6163. /**
  6164. * 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.
  6165. * Returns the updated Path2.
  6166. */
  6167. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6168. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6169. if (this.closed) {
  6170. //Tools.Error("cannot add arcs to closed paths");
  6171. return this;
  6172. }
  6173. var startPoint = this._points[this._points.length - 1];
  6174. var midPoint = new Vector2(midX, midY);
  6175. var endPoint = new Vector2(endX, endY);
  6176. var arc = new Arc2(startPoint, midPoint, endPoint);
  6177. var increment = arc.angle.radians() / numberOfSegments;
  6178. if (arc.orientation === Orientation.CW)
  6179. increment *= -1;
  6180. var currentAngle = arc.startAngle.radians() + increment;
  6181. for (var i = 0; i < numberOfSegments; i++) {
  6182. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6183. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6184. this.addLineTo(x, y);
  6185. currentAngle += increment;
  6186. }
  6187. return this;
  6188. };
  6189. /**
  6190. * Closes the Path2.
  6191. * Returns the Path2.
  6192. */
  6193. Path2.prototype.close = function () {
  6194. this.closed = true;
  6195. return this;
  6196. };
  6197. /**
  6198. * Returns the Path2 total length (float).
  6199. */
  6200. Path2.prototype.length = function () {
  6201. var result = this._length;
  6202. if (!this.closed) {
  6203. var lastPoint = this._points[this._points.length - 1];
  6204. var firstPoint = this._points[0];
  6205. result += (firstPoint.subtract(lastPoint).length());
  6206. }
  6207. return result;
  6208. };
  6209. /**
  6210. * Returns the Path2 internal array of points.
  6211. */
  6212. Path2.prototype.getPoints = function () {
  6213. return this._points;
  6214. };
  6215. /**
  6216. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6217. */
  6218. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6219. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6220. //Tools.Error("normalized length position should be between 0 and 1.");
  6221. return Vector2.Zero();
  6222. }
  6223. var lengthPosition = normalizedLengthPosition * this.length();
  6224. var previousOffset = 0;
  6225. for (var i = 0; i < this._points.length; i++) {
  6226. var j = (i + 1) % this._points.length;
  6227. var a = this._points[i];
  6228. var b = this._points[j];
  6229. var bToA = b.subtract(a);
  6230. var nextOffset = (bToA.length() + previousOffset);
  6231. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6232. var dir = bToA.normalize();
  6233. var localOffset = lengthPosition - previousOffset;
  6234. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6235. }
  6236. previousOffset = nextOffset;
  6237. }
  6238. //Tools.Error("internal error");
  6239. return Vector2.Zero();
  6240. };
  6241. /**
  6242. * Returns a new Path2 starting at the coordinates (x, y).
  6243. */
  6244. Path2.StartingAt = function (x, y) {
  6245. return new Path2(x, y);
  6246. };
  6247. return Path2;
  6248. }());
  6249. BABYLON.Path2 = Path2;
  6250. var Path3D = /** @class */ (function () {
  6251. /**
  6252. * new Path3D(path, normal, raw)
  6253. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6254. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6255. * path : an array of Vector3, the curve axis of the Path3D
  6256. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6257. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6258. */
  6259. function Path3D(path, firstNormal, raw) {
  6260. if (firstNormal === void 0) { firstNormal = null; }
  6261. this.path = path;
  6262. this._curve = new Array();
  6263. this._distances = new Array();
  6264. this._tangents = new Array();
  6265. this._normals = new Array();
  6266. this._binormals = new Array();
  6267. for (var p = 0; p < path.length; p++) {
  6268. this._curve[p] = path[p].clone(); // hard copy
  6269. }
  6270. this._raw = raw || false;
  6271. this._compute(firstNormal);
  6272. }
  6273. /**
  6274. * Returns the Path3D array of successive Vector3 designing its curve.
  6275. */
  6276. Path3D.prototype.getCurve = function () {
  6277. return this._curve;
  6278. };
  6279. /**
  6280. * Returns an array populated with tangent vectors on each Path3D curve point.
  6281. */
  6282. Path3D.prototype.getTangents = function () {
  6283. return this._tangents;
  6284. };
  6285. /**
  6286. * Returns an array populated with normal vectors on each Path3D curve point.
  6287. */
  6288. Path3D.prototype.getNormals = function () {
  6289. return this._normals;
  6290. };
  6291. /**
  6292. * Returns an array populated with binormal vectors on each Path3D curve point.
  6293. */
  6294. Path3D.prototype.getBinormals = function () {
  6295. return this._binormals;
  6296. };
  6297. /**
  6298. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6299. */
  6300. Path3D.prototype.getDistances = function () {
  6301. return this._distances;
  6302. };
  6303. /**
  6304. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6305. * Returns the same object updated.
  6306. */
  6307. Path3D.prototype.update = function (path, firstNormal) {
  6308. if (firstNormal === void 0) { firstNormal = null; }
  6309. for (var p = 0; p < path.length; p++) {
  6310. this._curve[p].x = path[p].x;
  6311. this._curve[p].y = path[p].y;
  6312. this._curve[p].z = path[p].z;
  6313. }
  6314. this._compute(firstNormal);
  6315. return this;
  6316. };
  6317. // private function compute() : computes tangents, normals and binormals
  6318. Path3D.prototype._compute = function (firstNormal) {
  6319. var l = this._curve.length;
  6320. // first and last tangents
  6321. this._tangents[0] = this._getFirstNonNullVector(0);
  6322. if (!this._raw) {
  6323. this._tangents[0].normalize();
  6324. }
  6325. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6326. if (!this._raw) {
  6327. this._tangents[l - 1].normalize();
  6328. }
  6329. // normals and binormals at first point : arbitrary vector with _normalVector()
  6330. var tg0 = this._tangents[0];
  6331. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6332. this._normals[0] = pp0;
  6333. if (!this._raw) {
  6334. this._normals[0].normalize();
  6335. }
  6336. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6337. if (!this._raw) {
  6338. this._binormals[0].normalize();
  6339. }
  6340. this._distances[0] = 0.0;
  6341. // normals and binormals : next points
  6342. var prev; // previous vector (segment)
  6343. var cur; // current vector (segment)
  6344. var curTang; // current tangent
  6345. // previous normal
  6346. var prevBinor; // previous binormal
  6347. for (var i = 1; i < l; i++) {
  6348. // tangents
  6349. prev = this._getLastNonNullVector(i);
  6350. if (i < l - 1) {
  6351. cur = this._getFirstNonNullVector(i);
  6352. this._tangents[i] = prev.add(cur);
  6353. this._tangents[i].normalize();
  6354. }
  6355. this._distances[i] = this._distances[i - 1] + prev.length();
  6356. // normals and binormals
  6357. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6358. curTang = this._tangents[i];
  6359. prevBinor = this._binormals[i - 1];
  6360. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6361. if (!this._raw) {
  6362. this._normals[i].normalize();
  6363. }
  6364. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6365. if (!this._raw) {
  6366. this._binormals[i].normalize();
  6367. }
  6368. }
  6369. };
  6370. // private function getFirstNonNullVector(index)
  6371. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6372. Path3D.prototype._getFirstNonNullVector = function (index) {
  6373. var i = 1;
  6374. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6375. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6376. i++;
  6377. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6378. }
  6379. return nNVector;
  6380. };
  6381. // private function getLastNonNullVector(index)
  6382. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6383. Path3D.prototype._getLastNonNullVector = function (index) {
  6384. var i = 1;
  6385. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6386. while (nLVector.length() === 0 && index > i + 1) {
  6387. i++;
  6388. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6389. }
  6390. return nLVector;
  6391. };
  6392. // private function normalVector(v0, vt, va) :
  6393. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6394. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6395. Path3D.prototype._normalVector = function (v0, vt, va) {
  6396. var normal0;
  6397. var tgl = vt.length();
  6398. if (tgl === 0.0) {
  6399. tgl = 1.0;
  6400. }
  6401. if (va === undefined || va === null) {
  6402. var point;
  6403. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6404. point = new Vector3(0.0, -1.0, 0.0);
  6405. }
  6406. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6407. point = new Vector3(1.0, 0.0, 0.0);
  6408. }
  6409. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6410. point = new Vector3(0.0, 0.0, 1.0);
  6411. }
  6412. else {
  6413. point = Vector3.Zero();
  6414. }
  6415. normal0 = Vector3.Cross(vt, point);
  6416. }
  6417. else {
  6418. normal0 = Vector3.Cross(vt, va);
  6419. Vector3.CrossToRef(normal0, vt, normal0);
  6420. }
  6421. normal0.normalize();
  6422. return normal0;
  6423. };
  6424. return Path3D;
  6425. }());
  6426. BABYLON.Path3D = Path3D;
  6427. var Curve3 = /** @class */ (function () {
  6428. /**
  6429. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6430. * A Curve3 is designed from a series of successive Vector3.
  6431. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6432. */
  6433. function Curve3(points) {
  6434. this._length = 0.0;
  6435. this._points = points;
  6436. this._length = this._computeLength(points);
  6437. }
  6438. /**
  6439. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6440. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6441. * @param v1 (Vector3) the control point
  6442. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6443. * @param nbPoints (integer) the wanted number of points in the curve
  6444. */
  6445. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6446. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6447. var bez = new Array();
  6448. var equation = function (t, val0, val1, val2) {
  6449. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6450. return res;
  6451. };
  6452. for (var i = 0; i <= nbPoints; i++) {
  6453. 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)));
  6454. }
  6455. return new Curve3(bez);
  6456. };
  6457. /**
  6458. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6459. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6460. * @param v1 (Vector3) the first control point
  6461. * @param v2 (Vector3) the second control point
  6462. * @param v3 (Vector3) the end point of the Cubic Bezier
  6463. * @param nbPoints (integer) the wanted number of points in the curve
  6464. */
  6465. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6466. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6467. var bez = new Array();
  6468. var equation = function (t, val0, val1, val2, val3) {
  6469. 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;
  6470. return res;
  6471. };
  6472. for (var i = 0; i <= nbPoints; i++) {
  6473. 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)));
  6474. }
  6475. return new Curve3(bez);
  6476. };
  6477. /**
  6478. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6479. * @param p1 (Vector3) the origin point of the Hermite Spline
  6480. * @param t1 (Vector3) the tangent vector at the origin point
  6481. * @param p2 (Vector3) the end point of the Hermite Spline
  6482. * @param t2 (Vector3) the tangent vector at the end point
  6483. * @param nbPoints (integer) the wanted number of points in the curve
  6484. */
  6485. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6486. var hermite = new Array();
  6487. var step = 1.0 / nbPoints;
  6488. for (var i = 0; i <= nbPoints; i++) {
  6489. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6490. }
  6491. return new Curve3(hermite);
  6492. };
  6493. /**
  6494. * Returns a Curve3 object along a CatmullRom Spline curve :
  6495. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6496. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6497. */
  6498. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6499. var totalPoints = new Array();
  6500. totalPoints.push(points[0].clone());
  6501. Array.prototype.push.apply(totalPoints, points);
  6502. totalPoints.push(points[points.length - 1].clone());
  6503. var catmullRom = new Array();
  6504. var step = 1.0 / nbPoints;
  6505. var amount = 0.0;
  6506. for (var i = 0; i < totalPoints.length - 3; i++) {
  6507. amount = 0;
  6508. for (var c = 0; c < nbPoints; c++) {
  6509. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6510. amount += step;
  6511. }
  6512. }
  6513. i--;
  6514. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6515. return new Curve3(catmullRom);
  6516. };
  6517. /**
  6518. * Returns the Curve3 stored array of successive Vector3
  6519. */
  6520. Curve3.prototype.getPoints = function () {
  6521. return this._points;
  6522. };
  6523. /**
  6524. * Returns the computed length (float) of the curve.
  6525. */
  6526. Curve3.prototype.length = function () {
  6527. return this._length;
  6528. };
  6529. /**
  6530. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6531. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6532. * curveA and curveB keep unchanged.
  6533. */
  6534. Curve3.prototype.continue = function (curve) {
  6535. var lastPoint = this._points[this._points.length - 1];
  6536. var continuedPoints = this._points.slice();
  6537. var curvePoints = curve.getPoints();
  6538. for (var i = 1; i < curvePoints.length; i++) {
  6539. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6540. }
  6541. var continuedCurve = new Curve3(continuedPoints);
  6542. return continuedCurve;
  6543. };
  6544. Curve3.prototype._computeLength = function (path) {
  6545. var l = 0;
  6546. for (var i = 1; i < path.length; i++) {
  6547. l += (path[i].subtract(path[i - 1])).length();
  6548. }
  6549. return l;
  6550. };
  6551. return Curve3;
  6552. }());
  6553. BABYLON.Curve3 = Curve3;
  6554. // Vertex formats
  6555. var PositionNormalVertex = /** @class */ (function () {
  6556. function PositionNormalVertex(position, normal) {
  6557. if (position === void 0) { position = Vector3.Zero(); }
  6558. if (normal === void 0) { normal = Vector3.Up(); }
  6559. this.position = position;
  6560. this.normal = normal;
  6561. }
  6562. PositionNormalVertex.prototype.clone = function () {
  6563. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6564. };
  6565. return PositionNormalVertex;
  6566. }());
  6567. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6568. var PositionNormalTextureVertex = /** @class */ (function () {
  6569. function PositionNormalTextureVertex(position, normal, uv) {
  6570. if (position === void 0) { position = Vector3.Zero(); }
  6571. if (normal === void 0) { normal = Vector3.Up(); }
  6572. if (uv === void 0) { uv = Vector2.Zero(); }
  6573. this.position = position;
  6574. this.normal = normal;
  6575. this.uv = uv;
  6576. }
  6577. PositionNormalTextureVertex.prototype.clone = function () {
  6578. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6579. };
  6580. return PositionNormalTextureVertex;
  6581. }());
  6582. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6583. // Temporary pre-allocated objects for engine internal use
  6584. // usage in any internal function :
  6585. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6586. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6587. var Tmp = /** @class */ (function () {
  6588. function Tmp() {
  6589. }
  6590. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6591. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6592. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6593. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6594. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6595. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6596. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6597. Matrix.Zero(), Matrix.Zero(),
  6598. Matrix.Zero(), Matrix.Zero(),
  6599. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6600. return Tmp;
  6601. }());
  6602. BABYLON.Tmp = Tmp;
  6603. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6604. var MathTmp = /** @class */ (function () {
  6605. function MathTmp() {
  6606. }
  6607. MathTmp.Vector3 = [Vector3.Zero()];
  6608. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6609. MathTmp.Quaternion = [Quaternion.Zero()];
  6610. return MathTmp;
  6611. }());
  6612. })(BABYLON || (BABYLON = {}));
  6613. //# sourceMappingURL=babylon.math.js.map
  6614. var BABYLON;
  6615. (function (BABYLON) {
  6616. var Scalar = /** @class */ (function () {
  6617. function Scalar() {
  6618. }
  6619. /**
  6620. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6621. */
  6622. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6623. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6624. var num = a - b;
  6625. return -epsilon <= num && num <= epsilon;
  6626. };
  6627. /**
  6628. * Returns a string : the upper case translation of the number i to hexadecimal.
  6629. */
  6630. Scalar.ToHex = function (i) {
  6631. var str = i.toString(16);
  6632. if (i <= 15) {
  6633. return ("0" + str).toUpperCase();
  6634. }
  6635. return str.toUpperCase();
  6636. };
  6637. /**
  6638. * Returns -1 if value is negative and +1 is value is positive.
  6639. * Returns the value itself if it's equal to zero.
  6640. */
  6641. Scalar.Sign = function (value) {
  6642. value = +value; // convert to a number
  6643. if (value === 0 || isNaN(value))
  6644. return value;
  6645. return value > 0 ? 1 : -1;
  6646. };
  6647. /**
  6648. * Returns the value itself if it's between min and max.
  6649. * Returns min if the value is lower than min.
  6650. * Returns max if the value is greater than max.
  6651. */
  6652. Scalar.Clamp = function (value, min, max) {
  6653. if (min === void 0) { min = 0; }
  6654. if (max === void 0) { max = 1; }
  6655. return Math.min(max, Math.max(min, value));
  6656. };
  6657. /**
  6658. * Returns the log2 of value.
  6659. */
  6660. Scalar.Log2 = function (value) {
  6661. return Math.log(value) * Math.LOG2E;
  6662. };
  6663. /**
  6664. * Loops the value, so that it is never larger than length and never smaller than 0.
  6665. *
  6666. * This is similar to the modulo operator but it works with floating point numbers.
  6667. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6668. * With t = 5 and length = 2.5, the result would be 0.0.
  6669. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6670. */
  6671. Scalar.Repeat = function (value, length) {
  6672. return value - Math.floor(value / length) * length;
  6673. };
  6674. /**
  6675. * Normalize the value between 0.0 and 1.0 using min and max values
  6676. */
  6677. Scalar.Normalize = function (value, min, max) {
  6678. return (value - min) / (max - min);
  6679. };
  6680. /**
  6681. * Denormalize the value from 0.0 and 1.0 using min and max values
  6682. */
  6683. Scalar.Denormalize = function (normalized, min, max) {
  6684. return (normalized * (max - min) + min);
  6685. };
  6686. /**
  6687. * Calculates the shortest difference between two given angles given in degrees.
  6688. */
  6689. Scalar.DeltaAngle = function (current, target) {
  6690. var num = Scalar.Repeat(target - current, 360.0);
  6691. if (num > 180.0) {
  6692. num -= 360.0;
  6693. }
  6694. return num;
  6695. };
  6696. /**
  6697. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6698. *
  6699. * The returned value will move back and forth between 0 and length
  6700. */
  6701. Scalar.PingPong = function (tx, length) {
  6702. var t = Scalar.Repeat(tx, length * 2.0);
  6703. return length - Math.abs(t - length);
  6704. };
  6705. /**
  6706. * Interpolates between min and max with smoothing at the limits.
  6707. *
  6708. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6709. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6710. */
  6711. Scalar.SmoothStep = function (from, to, tx) {
  6712. var t = Scalar.Clamp(tx);
  6713. t = -2.0 * t * t * t + 3.0 * t * t;
  6714. return to * t + from * (1.0 - t);
  6715. };
  6716. /**
  6717. * Moves a value current towards target.
  6718. *
  6719. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6720. * Negative values of maxDelta pushes the value away from target.
  6721. */
  6722. Scalar.MoveTowards = function (current, target, maxDelta) {
  6723. var result = 0;
  6724. if (Math.abs(target - current) <= maxDelta) {
  6725. result = target;
  6726. }
  6727. else {
  6728. result = current + Scalar.Sign(target - current) * maxDelta;
  6729. }
  6730. return result;
  6731. };
  6732. /**
  6733. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6734. *
  6735. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6736. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6737. */
  6738. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6739. var num = Scalar.DeltaAngle(current, target);
  6740. var result = 0;
  6741. if (-maxDelta < num && num < maxDelta) {
  6742. result = target;
  6743. }
  6744. else {
  6745. target = current + num;
  6746. result = Scalar.MoveTowards(current, target, maxDelta);
  6747. }
  6748. return result;
  6749. };
  6750. /**
  6751. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6752. */
  6753. Scalar.Lerp = function (start, end, amount) {
  6754. return start + ((end - start) * amount);
  6755. };
  6756. /**
  6757. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6758. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6759. */
  6760. Scalar.LerpAngle = function (start, end, amount) {
  6761. var num = Scalar.Repeat(end - start, 360.0);
  6762. if (num > 180.0) {
  6763. num -= 360.0;
  6764. }
  6765. return start + num * Scalar.Clamp(amount);
  6766. };
  6767. /**
  6768. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6769. */
  6770. Scalar.InverseLerp = function (a, b, value) {
  6771. var result = 0;
  6772. if (a != b) {
  6773. result = Scalar.Clamp((value - a) / (b - a));
  6774. }
  6775. else {
  6776. result = 0.0;
  6777. }
  6778. return result;
  6779. };
  6780. /**
  6781. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6782. */
  6783. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6784. var squared = amount * amount;
  6785. var cubed = amount * squared;
  6786. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6787. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6788. var part3 = (cubed - (2.0 * squared)) + amount;
  6789. var part4 = cubed - squared;
  6790. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6791. };
  6792. /**
  6793. * Returns a random float number between and min and max values
  6794. */
  6795. Scalar.RandomRange = function (min, max) {
  6796. if (min === max)
  6797. return min;
  6798. return ((Math.random() * (max - min)) + min);
  6799. };
  6800. /**
  6801. * This function returns percentage of a number in a given range.
  6802. *
  6803. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6804. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6805. */
  6806. Scalar.RangeToPercent = function (number, min, max) {
  6807. return ((number - min) / (max - min));
  6808. };
  6809. /**
  6810. * This function returns number that corresponds to the percentage in a given range.
  6811. *
  6812. * PercentToRange(0.34,0,100) will return 34.
  6813. */
  6814. Scalar.PercentToRange = function (percent, min, max) {
  6815. return ((max - min) * percent + min);
  6816. };
  6817. /**
  6818. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6819. * @param angle The angle to normalize in radian.
  6820. * @return The converted angle.
  6821. */
  6822. Scalar.NormalizeRadians = function (angle) {
  6823. // More precise but slower version kept for reference.
  6824. // angle = angle % Tools.TwoPi;
  6825. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6826. //if (angle > Math.PI) {
  6827. // angle -= Tools.TwoPi;
  6828. //}
  6829. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6830. return angle;
  6831. };
  6832. /**
  6833. * Two pi constants convenient for computation.
  6834. */
  6835. Scalar.TwoPi = Math.PI * 2;
  6836. return Scalar;
  6837. }());
  6838. BABYLON.Scalar = Scalar;
  6839. })(BABYLON || (BABYLON = {}));
  6840. //# sourceMappingURL=babylon.math.scalar.js.map
  6841. //# sourceMappingURL=babylon.mixins.js.map
  6842. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6843. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6844. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6845. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6846. //# sourceMappingURL=babylon.webgl2.js.map
  6847. var BABYLON;
  6848. (function (BABYLON) {
  6849. var __decoratorInitialStore = {};
  6850. var __mergedStore = {};
  6851. var _copySource = function (creationFunction, source, instanciate) {
  6852. var destination = creationFunction();
  6853. // Tags
  6854. if (BABYLON.Tags) {
  6855. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6856. }
  6857. var classStore = getMergedStore(destination);
  6858. // Properties
  6859. for (var property in classStore) {
  6860. var propertyDescriptor = classStore[property];
  6861. var sourceProperty = source[property];
  6862. var propertyType = propertyDescriptor.type;
  6863. if (sourceProperty !== undefined && sourceProperty !== null) {
  6864. switch (propertyType) {
  6865. case 0: // Value
  6866. case 6:// Mesh reference
  6867. destination[property] = sourceProperty;
  6868. break;
  6869. case 1:// Texture
  6870. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6871. break;
  6872. case 2: // Color3
  6873. case 3: // FresnelParameters
  6874. case 4: // Vector2
  6875. case 5: // Vector3
  6876. case 7: // Color Curves
  6877. case 10:// Quaternion
  6878. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6879. break;
  6880. }
  6881. }
  6882. }
  6883. return destination;
  6884. };
  6885. function getDirectStore(target) {
  6886. var classKey = target.getClassName();
  6887. if (!__decoratorInitialStore[classKey]) {
  6888. __decoratorInitialStore[classKey] = {};
  6889. }
  6890. return __decoratorInitialStore[classKey];
  6891. }
  6892. /**
  6893. * Return the list of properties flagged as serializable
  6894. * @param target: host object
  6895. */
  6896. function getMergedStore(target) {
  6897. var classKey = target.getClassName();
  6898. if (__mergedStore[classKey]) {
  6899. return __mergedStore[classKey];
  6900. }
  6901. __mergedStore[classKey] = {};
  6902. var store = __mergedStore[classKey];
  6903. var currentTarget = target;
  6904. var currentKey = classKey;
  6905. while (currentKey) {
  6906. var initialStore = __decoratorInitialStore[currentKey];
  6907. for (var property in initialStore) {
  6908. store[property] = initialStore[property];
  6909. }
  6910. var parent_1 = void 0;
  6911. var done = false;
  6912. do {
  6913. parent_1 = Object.getPrototypeOf(currentTarget);
  6914. if (!parent_1.getClassName) {
  6915. done = true;
  6916. break;
  6917. }
  6918. if (parent_1.getClassName() !== currentKey) {
  6919. break;
  6920. }
  6921. currentTarget = parent_1;
  6922. } while (parent_1);
  6923. if (done) {
  6924. break;
  6925. }
  6926. currentKey = parent_1.getClassName();
  6927. currentTarget = parent_1;
  6928. }
  6929. return store;
  6930. }
  6931. function generateSerializableMember(type, sourceName) {
  6932. return function (target, propertyKey) {
  6933. var classStore = getDirectStore(target);
  6934. if (!classStore[propertyKey]) {
  6935. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6936. }
  6937. };
  6938. }
  6939. function generateExpandMember(setCallback, targetKey) {
  6940. if (targetKey === void 0) { targetKey = null; }
  6941. return function (target, propertyKey) {
  6942. var key = targetKey || ("_" + propertyKey);
  6943. Object.defineProperty(target, propertyKey, {
  6944. get: function () {
  6945. return this[key];
  6946. },
  6947. set: function (value) {
  6948. if (this[key] === value) {
  6949. return;
  6950. }
  6951. this[key] = value;
  6952. target[setCallback].apply(this);
  6953. },
  6954. enumerable: true,
  6955. configurable: true
  6956. });
  6957. };
  6958. }
  6959. function expandToProperty(callback, targetKey) {
  6960. if (targetKey === void 0) { targetKey = null; }
  6961. return generateExpandMember(callback, targetKey);
  6962. }
  6963. BABYLON.expandToProperty = expandToProperty;
  6964. function serialize(sourceName) {
  6965. return generateSerializableMember(0, sourceName); // value member
  6966. }
  6967. BABYLON.serialize = serialize;
  6968. function serializeAsTexture(sourceName) {
  6969. return generateSerializableMember(1, sourceName); // texture member
  6970. }
  6971. BABYLON.serializeAsTexture = serializeAsTexture;
  6972. function serializeAsColor3(sourceName) {
  6973. return generateSerializableMember(2, sourceName); // color3 member
  6974. }
  6975. BABYLON.serializeAsColor3 = serializeAsColor3;
  6976. function serializeAsFresnelParameters(sourceName) {
  6977. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6978. }
  6979. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6980. function serializeAsVector2(sourceName) {
  6981. return generateSerializableMember(4, sourceName); // vector2 member
  6982. }
  6983. BABYLON.serializeAsVector2 = serializeAsVector2;
  6984. function serializeAsVector3(sourceName) {
  6985. return generateSerializableMember(5, sourceName); // vector3 member
  6986. }
  6987. BABYLON.serializeAsVector3 = serializeAsVector3;
  6988. function serializeAsMeshReference(sourceName) {
  6989. return generateSerializableMember(6, sourceName); // mesh reference member
  6990. }
  6991. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6992. function serializeAsColorCurves(sourceName) {
  6993. return generateSerializableMember(7, sourceName); // color curves
  6994. }
  6995. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6996. function serializeAsColor4(sourceName) {
  6997. return generateSerializableMember(8, sourceName); // color 4
  6998. }
  6999. BABYLON.serializeAsColor4 = serializeAsColor4;
  7000. function serializeAsImageProcessingConfiguration(sourceName) {
  7001. return generateSerializableMember(9, sourceName); // image processing
  7002. }
  7003. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7004. function serializeAsQuaternion(sourceName) {
  7005. return generateSerializableMember(10, sourceName); // quaternion member
  7006. }
  7007. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7008. var SerializationHelper = /** @class */ (function () {
  7009. function SerializationHelper() {
  7010. }
  7011. SerializationHelper.Serialize = function (entity, serializationObject) {
  7012. if (!serializationObject) {
  7013. serializationObject = {};
  7014. }
  7015. // Tags
  7016. if (BABYLON.Tags) {
  7017. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7018. }
  7019. var serializedProperties = getMergedStore(entity);
  7020. // Properties
  7021. for (var property in serializedProperties) {
  7022. var propertyDescriptor = serializedProperties[property];
  7023. var targetPropertyName = propertyDescriptor.sourceName || property;
  7024. var propertyType = propertyDescriptor.type;
  7025. var sourceProperty = entity[property];
  7026. if (sourceProperty !== undefined && sourceProperty !== null) {
  7027. switch (propertyType) {
  7028. case 0:// Value
  7029. serializationObject[targetPropertyName] = sourceProperty;
  7030. break;
  7031. case 1:// Texture
  7032. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7033. break;
  7034. case 2:// Color3
  7035. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7036. break;
  7037. case 3:// FresnelParameters
  7038. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7039. break;
  7040. case 4:// Vector2
  7041. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7042. break;
  7043. case 5:// Vector3
  7044. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7045. break;
  7046. case 6:// Mesh reference
  7047. serializationObject[targetPropertyName] = sourceProperty.id;
  7048. break;
  7049. case 7:// Color Curves
  7050. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7051. break;
  7052. case 8:// Color 4
  7053. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7054. break;
  7055. case 9:// Image Processing
  7056. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7057. break;
  7058. }
  7059. }
  7060. }
  7061. return serializationObject;
  7062. };
  7063. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7064. if (rootUrl === void 0) { rootUrl = null; }
  7065. var destination = creationFunction();
  7066. if (!rootUrl) {
  7067. rootUrl = "";
  7068. }
  7069. // Tags
  7070. if (BABYLON.Tags) {
  7071. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7072. }
  7073. var classStore = getMergedStore(destination);
  7074. // Properties
  7075. for (var property in classStore) {
  7076. var propertyDescriptor = classStore[property];
  7077. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7078. var propertyType = propertyDescriptor.type;
  7079. if (sourceProperty !== undefined && sourceProperty !== null) {
  7080. var dest = destination;
  7081. switch (propertyType) {
  7082. case 0:// Value
  7083. dest[property] = sourceProperty;
  7084. break;
  7085. case 1:// Texture
  7086. if (scene) {
  7087. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7088. }
  7089. break;
  7090. case 2:// Color3
  7091. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7092. break;
  7093. case 3:// FresnelParameters
  7094. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7095. break;
  7096. case 4:// Vector2
  7097. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7098. break;
  7099. case 5:// Vector3
  7100. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7101. break;
  7102. case 6:// Mesh reference
  7103. if (scene) {
  7104. dest[property] = scene.getLastMeshByID(sourceProperty);
  7105. }
  7106. break;
  7107. case 7:// Color Curves
  7108. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7109. break;
  7110. case 8:// Color 4
  7111. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7112. break;
  7113. case 9:// Image Processing
  7114. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7115. break;
  7116. }
  7117. }
  7118. }
  7119. return destination;
  7120. };
  7121. SerializationHelper.Clone = function (creationFunction, source) {
  7122. return _copySource(creationFunction, source, false);
  7123. };
  7124. SerializationHelper.Instanciate = function (creationFunction, source) {
  7125. return _copySource(creationFunction, source, true);
  7126. };
  7127. return SerializationHelper;
  7128. }());
  7129. BABYLON.SerializationHelper = SerializationHelper;
  7130. })(BABYLON || (BABYLON = {}));
  7131. //# sourceMappingURL=babylon.decorators.js.map
  7132. var BABYLON;
  7133. (function (BABYLON) {
  7134. /**
  7135. * Wrapper class for promise with external resolve and reject.
  7136. */
  7137. var Deferred = /** @class */ (function () {
  7138. /**
  7139. * Constructor for this deferred object.
  7140. */
  7141. function Deferred() {
  7142. var _this = this;
  7143. this.promise = new Promise(function (resolve, reject) {
  7144. _this._resolve = resolve;
  7145. _this._reject = reject;
  7146. });
  7147. }
  7148. Object.defineProperty(Deferred.prototype, "resolve", {
  7149. /**
  7150. * The resolve method of the promise associated with this deferred object.
  7151. */
  7152. get: function () {
  7153. return this._resolve;
  7154. },
  7155. enumerable: true,
  7156. configurable: true
  7157. });
  7158. Object.defineProperty(Deferred.prototype, "reject", {
  7159. /**
  7160. * The reject method of the promise associated with this deferred object.
  7161. */
  7162. get: function () {
  7163. return this._reject;
  7164. },
  7165. enumerable: true,
  7166. configurable: true
  7167. });
  7168. return Deferred;
  7169. }());
  7170. BABYLON.Deferred = Deferred;
  7171. })(BABYLON || (BABYLON = {}));
  7172. //# sourceMappingURL=babylon.deferred.js.map
  7173. var BABYLON;
  7174. (function (BABYLON) {
  7175. /**
  7176. * A class serves as a medium between the observable and its observers
  7177. */
  7178. var EventState = /** @class */ (function () {
  7179. /**
  7180. * Create a new EventState
  7181. * @param mask defines the mask associated with this state
  7182. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7183. * @param target defines the original target of the state
  7184. * @param currentTarget defines the current target of the state
  7185. */
  7186. function EventState(mask, skipNextObservers, target, currentTarget) {
  7187. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7188. this.initalize(mask, skipNextObservers, target, currentTarget);
  7189. }
  7190. /**
  7191. * Initialize the current event state
  7192. * @param mask defines the mask associated with this state
  7193. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7194. * @param target defines the original target of the state
  7195. * @param currentTarget defines the current target of the state
  7196. * @returns the current event state
  7197. */
  7198. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7199. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7200. this.mask = mask;
  7201. this.skipNextObservers = skipNextObservers;
  7202. this.target = target;
  7203. this.currentTarget = currentTarget;
  7204. return this;
  7205. };
  7206. return EventState;
  7207. }());
  7208. BABYLON.EventState = EventState;
  7209. /**
  7210. * Represent an Observer registered to a given Observable object.
  7211. */
  7212. var Observer = /** @class */ (function () {
  7213. /**
  7214. * Creates a new observer
  7215. * @param callback defines the callback to call when the observer is notified
  7216. * @param mask defines the mask of the observer (used to filter notifications)
  7217. * @param scope defines the current scope used to restore the JS context
  7218. */
  7219. function Observer(
  7220. /**
  7221. * Defines the callback to call when the observer is notified
  7222. */
  7223. callback,
  7224. /**
  7225. * Defines the mask of the observer (used to filter notifications)
  7226. */
  7227. mask,
  7228. /**
  7229. * Defines the current scope used to restore the JS context
  7230. */
  7231. scope) {
  7232. if (scope === void 0) { scope = null; }
  7233. this.callback = callback;
  7234. this.mask = mask;
  7235. this.scope = scope;
  7236. /** @ignore */
  7237. this._willBeUnregistered = false;
  7238. /**
  7239. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7240. */
  7241. this.unregisterOnNextCall = false;
  7242. }
  7243. return Observer;
  7244. }());
  7245. BABYLON.Observer = Observer;
  7246. /**
  7247. * Represent a list of observers registered to multiple Observables object.
  7248. */
  7249. var MultiObserver = /** @class */ (function () {
  7250. function MultiObserver() {
  7251. }
  7252. /**
  7253. * Release associated resources
  7254. */
  7255. MultiObserver.prototype.dispose = function () {
  7256. if (this._observers && this._observables) {
  7257. for (var index = 0; index < this._observers.length; index++) {
  7258. this._observables[index].remove(this._observers[index]);
  7259. }
  7260. }
  7261. this._observers = null;
  7262. this._observables = null;
  7263. };
  7264. /**
  7265. * Raise a callback when one of the observable will notify
  7266. * @param observables defines a list of observables to watch
  7267. * @param callback defines the callback to call on notification
  7268. * @param mask defines the mask used to filter notifications
  7269. * @param scope defines the current scope used to restore the JS context
  7270. * @returns the new MultiObserver
  7271. */
  7272. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7273. if (mask === void 0) { mask = -1; }
  7274. if (scope === void 0) { scope = null; }
  7275. var result = new MultiObserver();
  7276. result._observers = new Array();
  7277. result._observables = observables;
  7278. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7279. var observable = observables_1[_i];
  7280. var observer = observable.add(callback, mask, false, scope);
  7281. if (observer) {
  7282. result._observers.push(observer);
  7283. }
  7284. }
  7285. return result;
  7286. };
  7287. return MultiObserver;
  7288. }());
  7289. BABYLON.MultiObserver = MultiObserver;
  7290. /**
  7291. * The Observable class is a simple implementation of the Observable pattern.
  7292. * 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.
  7293. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7294. * 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).
  7295. * 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.
  7296. */
  7297. var Observable = /** @class */ (function () {
  7298. /**
  7299. * Creates a new observable
  7300. * @param onObserverAdded defines a callback to call when a new observer is added
  7301. */
  7302. function Observable(onObserverAdded) {
  7303. this._observers = new Array();
  7304. this._eventState = new EventState(0);
  7305. if (onObserverAdded) {
  7306. this._onObserverAdded = onObserverAdded;
  7307. }
  7308. }
  7309. /**
  7310. * Create a new Observer with the specified callback
  7311. * @param callback the callback that will be executed for that Observer
  7312. * @param mask the mask used to filter observers
  7313. * @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.
  7314. * @param scope optional scope for the callback to be called from
  7315. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7316. * @returns the new observer created for the callback
  7317. */
  7318. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7319. if (mask === void 0) { mask = -1; }
  7320. if (insertFirst === void 0) { insertFirst = false; }
  7321. if (scope === void 0) { scope = null; }
  7322. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7323. if (!callback) {
  7324. return null;
  7325. }
  7326. var observer = new Observer(callback, mask, scope);
  7327. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7328. if (insertFirst) {
  7329. this._observers.unshift(observer);
  7330. }
  7331. else {
  7332. this._observers.push(observer);
  7333. }
  7334. if (this._onObserverAdded) {
  7335. this._onObserverAdded(observer);
  7336. }
  7337. return observer;
  7338. };
  7339. /**
  7340. * Remove an Observer from the Observable object
  7341. * @param observer the instance of the Observer to remove
  7342. * @returns false if it doesn't belong to this Observable
  7343. */
  7344. Observable.prototype.remove = function (observer) {
  7345. if (!observer) {
  7346. return false;
  7347. }
  7348. var index = this._observers.indexOf(observer);
  7349. if (index !== -1) {
  7350. this._observers.splice(index, 1);
  7351. return true;
  7352. }
  7353. return false;
  7354. };
  7355. /**
  7356. * Remove a callback from the Observable object
  7357. * @param callback the callback to remove
  7358. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7359. * @returns false if it doesn't belong to this Observable
  7360. */
  7361. Observable.prototype.removeCallback = function (callback, scope) {
  7362. for (var index = 0; index < this._observers.length; index++) {
  7363. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7364. this._observers.splice(index, 1);
  7365. return true;
  7366. }
  7367. }
  7368. return false;
  7369. };
  7370. Observable.prototype._deferUnregister = function (observer) {
  7371. var _this = this;
  7372. observer.unregisterOnNextCall = false;
  7373. observer._willBeUnregistered = true;
  7374. BABYLON.Tools.SetImmediate(function () {
  7375. _this.remove(observer);
  7376. });
  7377. };
  7378. /**
  7379. * Notify all Observers by calling their respective callback with the given data
  7380. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7381. * @param eventData defines the data to send to all observers
  7382. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7383. * @param target defines the original target of the state
  7384. * @param currentTarget defines the current target of the state
  7385. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7386. */
  7387. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7388. if (mask === void 0) { mask = -1; }
  7389. if (!this._observers.length) {
  7390. return true;
  7391. }
  7392. var state = this._eventState;
  7393. state.mask = mask;
  7394. state.target = target;
  7395. state.currentTarget = currentTarget;
  7396. state.skipNextObservers = false;
  7397. state.lastReturnValue = eventData;
  7398. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7399. var obs = _a[_i];
  7400. if (obs._willBeUnregistered) {
  7401. continue;
  7402. }
  7403. if (obs.mask & mask) {
  7404. if (obs.scope) {
  7405. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7406. }
  7407. else {
  7408. state.lastReturnValue = obs.callback(eventData, state);
  7409. }
  7410. if (obs.unregisterOnNextCall) {
  7411. this._deferUnregister(obs);
  7412. }
  7413. }
  7414. if (state.skipNextObservers) {
  7415. return false;
  7416. }
  7417. }
  7418. return true;
  7419. };
  7420. /**
  7421. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7422. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7423. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7424. * and it is crucial that all callbacks will be executed.
  7425. * The order of the callbacks is kept, callbacks are not executed parallel.
  7426. *
  7427. * @param eventData The data to be sent to each callback
  7428. * @param mask is used to filter observers defaults to -1
  7429. * @param target defines the callback target (see EventState)
  7430. * @param currentTarget defines he current object in the bubbling phase
  7431. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7432. */
  7433. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7434. var _this = this;
  7435. if (mask === void 0) { mask = -1; }
  7436. // create an empty promise
  7437. var p = Promise.resolve(eventData);
  7438. // no observers? return this promise.
  7439. if (!this._observers.length) {
  7440. return p;
  7441. }
  7442. var state = this._eventState;
  7443. state.mask = mask;
  7444. state.target = target;
  7445. state.currentTarget = currentTarget;
  7446. state.skipNextObservers = false;
  7447. // execute one callback after another (not using Promise.all, the order is important)
  7448. this._observers.forEach(function (obs) {
  7449. if (state.skipNextObservers) {
  7450. return;
  7451. }
  7452. if (obs._willBeUnregistered) {
  7453. return;
  7454. }
  7455. if (obs.mask & mask) {
  7456. if (obs.scope) {
  7457. p = p.then(function (lastReturnedValue) {
  7458. state.lastReturnValue = lastReturnedValue;
  7459. return obs.callback.apply(obs.scope, [eventData, state]);
  7460. });
  7461. }
  7462. else {
  7463. p = p.then(function (lastReturnedValue) {
  7464. state.lastReturnValue = lastReturnedValue;
  7465. return obs.callback(eventData, state);
  7466. });
  7467. }
  7468. if (obs.unregisterOnNextCall) {
  7469. _this._deferUnregister(obs);
  7470. }
  7471. }
  7472. });
  7473. // return the eventData
  7474. return p.then(function () { return eventData; });
  7475. };
  7476. /**
  7477. * Notify a specific observer
  7478. * @param observer defines the observer to notify
  7479. * @param eventData defines the data to be sent to each callback
  7480. * @param mask is used to filter observers defaults to -1
  7481. */
  7482. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7483. if (mask === void 0) { mask = -1; }
  7484. var state = this._eventState;
  7485. state.mask = mask;
  7486. state.skipNextObservers = false;
  7487. observer.callback(eventData, state);
  7488. };
  7489. /**
  7490. * Gets a boolean indicating if the observable has at least one observer
  7491. * @returns true is the Observable has at least one Observer registered
  7492. */
  7493. Observable.prototype.hasObservers = function () {
  7494. return this._observers.length > 0;
  7495. };
  7496. /**
  7497. * Clear the list of observers
  7498. */
  7499. Observable.prototype.clear = function () {
  7500. this._observers = new Array();
  7501. this._onObserverAdded = null;
  7502. };
  7503. /**
  7504. * Clone the current observable
  7505. * @returns a new observable
  7506. */
  7507. Observable.prototype.clone = function () {
  7508. var result = new Observable();
  7509. result._observers = this._observers.slice(0);
  7510. return result;
  7511. };
  7512. /**
  7513. * Does this observable handles observer registered with a given mask
  7514. * @param mask defines the mask to be tested
  7515. * @return whether or not one observer registered with the given mask is handeled
  7516. **/
  7517. Observable.prototype.hasSpecificMask = function (mask) {
  7518. if (mask === void 0) { mask = -1; }
  7519. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7520. var obs = _a[_i];
  7521. if (obs.mask & mask || obs.mask === mask) {
  7522. return true;
  7523. }
  7524. }
  7525. return false;
  7526. };
  7527. return Observable;
  7528. }());
  7529. BABYLON.Observable = Observable;
  7530. })(BABYLON || (BABYLON = {}));
  7531. //# sourceMappingURL=babylon.observable.js.map
  7532. var BABYLON;
  7533. (function (BABYLON) {
  7534. var SmartArray = /** @class */ (function () {
  7535. function SmartArray(capacity) {
  7536. this.length = 0;
  7537. this.data = new Array(capacity);
  7538. this._id = SmartArray._GlobalId++;
  7539. }
  7540. SmartArray.prototype.push = function (value) {
  7541. this.data[this.length++] = value;
  7542. if (this.length > this.data.length) {
  7543. this.data.length *= 2;
  7544. }
  7545. };
  7546. SmartArray.prototype.forEach = function (func) {
  7547. for (var index = 0; index < this.length; index++) {
  7548. func(this.data[index]);
  7549. }
  7550. };
  7551. SmartArray.prototype.sort = function (compareFn) {
  7552. this.data.sort(compareFn);
  7553. };
  7554. SmartArray.prototype.reset = function () {
  7555. this.length = 0;
  7556. };
  7557. SmartArray.prototype.dispose = function () {
  7558. this.reset();
  7559. if (this.data) {
  7560. this.data.length = 0;
  7561. this.data = [];
  7562. }
  7563. };
  7564. SmartArray.prototype.concat = function (array) {
  7565. if (array.length === 0) {
  7566. return;
  7567. }
  7568. if (this.length + array.length > this.data.length) {
  7569. this.data.length = (this.length + array.length) * 2;
  7570. }
  7571. for (var index = 0; index < array.length; index++) {
  7572. this.data[this.length++] = (array.data || array)[index];
  7573. }
  7574. };
  7575. SmartArray.prototype.indexOf = function (value) {
  7576. var position = this.data.indexOf(value);
  7577. if (position >= this.length) {
  7578. return -1;
  7579. }
  7580. return position;
  7581. };
  7582. SmartArray.prototype.contains = function (value) {
  7583. return this.data.indexOf(value) !== -1;
  7584. };
  7585. // Statics
  7586. SmartArray._GlobalId = 0;
  7587. return SmartArray;
  7588. }());
  7589. BABYLON.SmartArray = SmartArray;
  7590. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7591. __extends(SmartArrayNoDuplicate, _super);
  7592. function SmartArrayNoDuplicate() {
  7593. var _this = _super !== null && _super.apply(this, arguments) || this;
  7594. _this._duplicateId = 0;
  7595. return _this;
  7596. }
  7597. SmartArrayNoDuplicate.prototype.push = function (value) {
  7598. _super.prototype.push.call(this, value);
  7599. if (!value.__smartArrayFlags) {
  7600. value.__smartArrayFlags = {};
  7601. }
  7602. value.__smartArrayFlags[this._id] = this._duplicateId;
  7603. };
  7604. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7605. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7606. return false;
  7607. }
  7608. this.push(value);
  7609. return true;
  7610. };
  7611. SmartArrayNoDuplicate.prototype.reset = function () {
  7612. _super.prototype.reset.call(this);
  7613. this._duplicateId++;
  7614. };
  7615. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7616. if (array.length === 0) {
  7617. return;
  7618. }
  7619. if (this.length + array.length > this.data.length) {
  7620. this.data.length = (this.length + array.length) * 2;
  7621. }
  7622. for (var index = 0; index < array.length; index++) {
  7623. var item = (array.data || array)[index];
  7624. this.pushNoDuplicate(item);
  7625. }
  7626. };
  7627. return SmartArrayNoDuplicate;
  7628. }(SmartArray));
  7629. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7630. })(BABYLON || (BABYLON = {}));
  7631. //# sourceMappingURL=babylon.smartArray.js.map
  7632. var BABYLON;
  7633. (function (BABYLON) {
  7634. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7635. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7636. var LoadFileError = /** @class */ (function (_super) {
  7637. __extends(LoadFileError, _super);
  7638. function LoadFileError(message, request) {
  7639. var _this = _super.call(this, message) || this;
  7640. _this.request = request;
  7641. _this.name = "LoadFileError";
  7642. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7643. return _this;
  7644. }
  7645. // Polyfill for Object.setPrototypeOf if necessary.
  7646. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7647. return LoadFileError;
  7648. }(Error));
  7649. BABYLON.LoadFileError = LoadFileError;
  7650. var RetryStrategy = /** @class */ (function () {
  7651. function RetryStrategy() {
  7652. }
  7653. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7654. if (maxRetries === void 0) { maxRetries = 3; }
  7655. if (baseInterval === void 0) { baseInterval = 500; }
  7656. return function (url, request, retryIndex) {
  7657. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7658. return -1;
  7659. }
  7660. return Math.pow(2, retryIndex) * baseInterval;
  7661. };
  7662. };
  7663. return RetryStrategy;
  7664. }());
  7665. BABYLON.RetryStrategy = RetryStrategy;
  7666. // Screenshots
  7667. var screenshotCanvas;
  7668. var cloneValue = function (source, destinationObject) {
  7669. if (!source)
  7670. return null;
  7671. if (source instanceof BABYLON.Mesh) {
  7672. return null;
  7673. }
  7674. if (source instanceof BABYLON.SubMesh) {
  7675. return source.clone(destinationObject);
  7676. }
  7677. else if (source.clone) {
  7678. return source.clone();
  7679. }
  7680. return null;
  7681. };
  7682. var Tools = /** @class */ (function () {
  7683. function Tools() {
  7684. }
  7685. /**
  7686. * Interpolates between a and b via alpha
  7687. * @param a The lower value (returned when alpha = 0)
  7688. * @param b The upper value (returned when alpha = 1)
  7689. * @param alpha The interpolation-factor
  7690. * @return The mixed value
  7691. */
  7692. Tools.Mix = function (a, b, alpha) {
  7693. return a * (1 - alpha) + b * alpha;
  7694. };
  7695. Tools.Instantiate = function (className) {
  7696. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7697. return Tools.RegisteredExternalClasses[className];
  7698. }
  7699. var arr = className.split(".");
  7700. var fn = (window || this);
  7701. for (var i = 0, len = arr.length; i < len; i++) {
  7702. fn = fn[arr[i]];
  7703. }
  7704. if (typeof fn !== "function") {
  7705. return null;
  7706. }
  7707. return fn;
  7708. };
  7709. /**
  7710. * Provides a slice function that will work even on IE
  7711. * @param data defines the array to slice
  7712. * @returns the new sliced array
  7713. */
  7714. Tools.Slice = function (data) {
  7715. if (data.slice) {
  7716. return data.slice();
  7717. }
  7718. return Array.prototype.slice.call(data);
  7719. };
  7720. Tools.SetImmediate = function (action) {
  7721. if (window.setImmediate) {
  7722. window.setImmediate(action);
  7723. }
  7724. else {
  7725. setTimeout(action, 1);
  7726. }
  7727. };
  7728. Tools.IsExponentOfTwo = function (value) {
  7729. var count = 1;
  7730. do {
  7731. count *= 2;
  7732. } while (count < value);
  7733. return count === value;
  7734. };
  7735. /**
  7736. * Find the next highest power of two.
  7737. * @param x Number to start search from.
  7738. * @return Next highest power of two.
  7739. */
  7740. Tools.CeilingPOT = function (x) {
  7741. x--;
  7742. x |= x >> 1;
  7743. x |= x >> 2;
  7744. x |= x >> 4;
  7745. x |= x >> 8;
  7746. x |= x >> 16;
  7747. x++;
  7748. return x;
  7749. };
  7750. /**
  7751. * Find the next lowest power of two.
  7752. * @param x Number to start search from.
  7753. * @return Next lowest power of two.
  7754. */
  7755. Tools.FloorPOT = function (x) {
  7756. x = x | (x >> 1);
  7757. x = x | (x >> 2);
  7758. x = x | (x >> 4);
  7759. x = x | (x >> 8);
  7760. x = x | (x >> 16);
  7761. return x - (x >> 1);
  7762. };
  7763. /**
  7764. * Find the nearest power of two.
  7765. * @param x Number to start search from.
  7766. * @return Next nearest power of two.
  7767. */
  7768. Tools.NearestPOT = function (x) {
  7769. var c = Tools.CeilingPOT(x);
  7770. var f = Tools.FloorPOT(x);
  7771. return (c - x) > (x - f) ? f : c;
  7772. };
  7773. Tools.GetExponentOfTwo = function (value, max, mode) {
  7774. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7775. var pot;
  7776. switch (mode) {
  7777. case BABYLON.Engine.SCALEMODE_FLOOR:
  7778. pot = Tools.FloorPOT(value);
  7779. break;
  7780. case BABYLON.Engine.SCALEMODE_NEAREST:
  7781. pot = Tools.NearestPOT(value);
  7782. break;
  7783. case BABYLON.Engine.SCALEMODE_CEILING:
  7784. default:
  7785. pot = Tools.CeilingPOT(value);
  7786. break;
  7787. }
  7788. return Math.min(pot, max);
  7789. };
  7790. Tools.GetFilename = function (path) {
  7791. var index = path.lastIndexOf("/");
  7792. if (index < 0)
  7793. return path;
  7794. return path.substring(index + 1);
  7795. };
  7796. /**
  7797. * Extracts the "folder" part of a path (everything before the filename).
  7798. * @param uri The URI to extract the info from
  7799. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7800. * @returns The "folder" part of the path
  7801. */
  7802. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7803. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7804. var index = uri.lastIndexOf("/");
  7805. if (index < 0) {
  7806. if (returnUnchangedIfNoSlash) {
  7807. return uri;
  7808. }
  7809. return "";
  7810. }
  7811. return uri.substring(0, index + 1);
  7812. };
  7813. Tools.GetDOMTextContent = function (element) {
  7814. var result = "";
  7815. var child = element.firstChild;
  7816. while (child) {
  7817. if (child.nodeType === 3) {
  7818. result += child.textContent;
  7819. }
  7820. child = child.nextSibling;
  7821. }
  7822. return result;
  7823. };
  7824. Tools.ToDegrees = function (angle) {
  7825. return angle * 180 / Math.PI;
  7826. };
  7827. Tools.ToRadians = function (angle) {
  7828. return angle * Math.PI / 180;
  7829. };
  7830. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7831. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7832. var output = "";
  7833. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7834. var i = 0;
  7835. var bytes = new Uint8Array(buffer);
  7836. while (i < bytes.length) {
  7837. chr1 = bytes[i++];
  7838. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7839. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7840. enc1 = chr1 >> 2;
  7841. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7842. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7843. enc4 = chr3 & 63;
  7844. if (isNaN(chr2)) {
  7845. enc3 = enc4 = 64;
  7846. }
  7847. else if (isNaN(chr3)) {
  7848. enc4 = 64;
  7849. }
  7850. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7851. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7852. }
  7853. return "data:image/png;base64," + output;
  7854. };
  7855. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7856. if (bias === void 0) { bias = null; }
  7857. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7858. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7859. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7860. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7861. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7862. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7863. }
  7864. if (bias) {
  7865. minimum.x -= minimum.x * bias.x + bias.y;
  7866. minimum.y -= minimum.y * bias.x + bias.y;
  7867. minimum.z -= minimum.z * bias.x + bias.y;
  7868. maximum.x += maximum.x * bias.x + bias.y;
  7869. maximum.y += maximum.y * bias.x + bias.y;
  7870. maximum.z += maximum.z * bias.x + bias.y;
  7871. }
  7872. return {
  7873. minimum: minimum,
  7874. maximum: maximum
  7875. };
  7876. };
  7877. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7878. if (bias === void 0) { bias = null; }
  7879. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7880. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7881. if (!stride) {
  7882. stride = 3;
  7883. }
  7884. for (var index = start; index < start + count; index++) {
  7885. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7886. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7887. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7888. }
  7889. if (bias) {
  7890. minimum.x -= minimum.x * bias.x + bias.y;
  7891. minimum.y -= minimum.y * bias.x + bias.y;
  7892. minimum.z -= minimum.z * bias.x + bias.y;
  7893. maximum.x += maximum.x * bias.x + bias.y;
  7894. maximum.y += maximum.y * bias.x + bias.y;
  7895. maximum.z += maximum.z * bias.x + bias.y;
  7896. }
  7897. return {
  7898. minimum: minimum,
  7899. maximum: maximum
  7900. };
  7901. };
  7902. Tools.Vector2ArrayFeeder = function (array) {
  7903. return function (index) {
  7904. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7905. var length = isFloatArray ? array.length / 2 : array.length;
  7906. if (index >= length) {
  7907. return null;
  7908. }
  7909. if (isFloatArray) {
  7910. var fa = array;
  7911. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7912. }
  7913. var a = array;
  7914. return a[index];
  7915. };
  7916. };
  7917. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7918. if (bias === void 0) { bias = null; }
  7919. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7920. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7921. var i = 0;
  7922. var cur = feeder(i++);
  7923. while (cur) {
  7924. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7925. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7926. cur = feeder(i++);
  7927. }
  7928. if (bias) {
  7929. minimum.x -= minimum.x * bias.x + bias.y;
  7930. minimum.y -= minimum.y * bias.x + bias.y;
  7931. maximum.x += maximum.x * bias.x + bias.y;
  7932. maximum.y += maximum.y * bias.x + bias.y;
  7933. }
  7934. return {
  7935. minimum: minimum,
  7936. maximum: maximum
  7937. };
  7938. };
  7939. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7940. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7941. return null;
  7942. return Array.isArray(obj) ? obj : [obj];
  7943. };
  7944. // Misc.
  7945. Tools.GetPointerPrefix = function () {
  7946. var eventPrefix = "pointer";
  7947. // Check if pointer events are supported
  7948. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7949. eventPrefix = "mouse";
  7950. }
  7951. return eventPrefix;
  7952. };
  7953. /**
  7954. * @param func - the function to be called
  7955. * @param requester - the object that will request the next frame. Falls back to window.
  7956. */
  7957. Tools.QueueNewFrame = function (func, requester) {
  7958. if (!Tools.IsWindowObjectExist()) {
  7959. return setTimeout(func, 16);
  7960. }
  7961. if (!requester) {
  7962. requester = window;
  7963. }
  7964. if (requester.requestAnimationFrame) {
  7965. return requester.requestAnimationFrame(func);
  7966. }
  7967. else if (requester.msRequestAnimationFrame) {
  7968. return requester.msRequestAnimationFrame(func);
  7969. }
  7970. else if (requester.webkitRequestAnimationFrame) {
  7971. return requester.webkitRequestAnimationFrame(func);
  7972. }
  7973. else if (requester.mozRequestAnimationFrame) {
  7974. return requester.mozRequestAnimationFrame(func);
  7975. }
  7976. else if (requester.oRequestAnimationFrame) {
  7977. return requester.oRequestAnimationFrame(func);
  7978. }
  7979. else {
  7980. return window.setTimeout(func, 16);
  7981. }
  7982. };
  7983. Tools.RequestFullscreen = function (element) {
  7984. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7985. if (!requestFunction)
  7986. return;
  7987. requestFunction.call(element);
  7988. };
  7989. Tools.ExitFullscreen = function () {
  7990. if (document.exitFullscreen) {
  7991. document.exitFullscreen();
  7992. }
  7993. else if (document.mozCancelFullScreen) {
  7994. document.mozCancelFullScreen();
  7995. }
  7996. else if (document.webkitCancelFullScreen) {
  7997. document.webkitCancelFullScreen();
  7998. }
  7999. else if (document.msCancelFullScreen) {
  8000. document.msCancelFullScreen();
  8001. }
  8002. };
  8003. Tools.SetCorsBehavior = function (url, element) {
  8004. if (url && url.indexOf("data:") === 0) {
  8005. return;
  8006. }
  8007. if (Tools.CorsBehavior) {
  8008. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8009. element.crossOrigin = Tools.CorsBehavior;
  8010. }
  8011. else {
  8012. var result = Tools.CorsBehavior(url);
  8013. if (result) {
  8014. element.crossOrigin = result;
  8015. }
  8016. }
  8017. }
  8018. };
  8019. // External files
  8020. Tools.CleanUrl = function (url) {
  8021. url = url.replace(/#/mg, "%23");
  8022. return url;
  8023. };
  8024. Tools.LoadImage = function (url, onLoad, onError, database) {
  8025. if (url instanceof ArrayBuffer) {
  8026. url = Tools.EncodeArrayBufferTobase64(url);
  8027. }
  8028. url = Tools.CleanUrl(url);
  8029. url = Tools.PreprocessUrl(url);
  8030. var img = new Image();
  8031. Tools.SetCorsBehavior(url, img);
  8032. var loadHandler = function () {
  8033. img.removeEventListener("load", loadHandler);
  8034. img.removeEventListener("error", errorHandler);
  8035. onLoad(img);
  8036. };
  8037. var errorHandler = function (err) {
  8038. img.removeEventListener("load", loadHandler);
  8039. img.removeEventListener("error", errorHandler);
  8040. Tools.Error("Error while trying to load image: " + url);
  8041. if (onError) {
  8042. onError("Error while trying to load image: " + url, err);
  8043. }
  8044. };
  8045. img.addEventListener("load", loadHandler);
  8046. img.addEventListener("error", errorHandler);
  8047. var noIndexedDB = function () {
  8048. img.src = url;
  8049. };
  8050. var loadFromIndexedDB = function () {
  8051. if (database) {
  8052. database.loadImageFromDB(url, img);
  8053. }
  8054. };
  8055. //ANY database to do!
  8056. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8057. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8058. }
  8059. else {
  8060. if (url.indexOf("file:") !== -1) {
  8061. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8062. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8063. try {
  8064. var blobURL;
  8065. try {
  8066. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8067. }
  8068. catch (ex) {
  8069. // Chrome doesn't support oneTimeOnly parameter
  8070. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8071. }
  8072. img.src = blobURL;
  8073. }
  8074. catch (e) {
  8075. img.src = "";
  8076. }
  8077. return img;
  8078. }
  8079. }
  8080. noIndexedDB();
  8081. }
  8082. return img;
  8083. };
  8084. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8085. url = Tools.CleanUrl(url);
  8086. url = Tools.PreprocessUrl(url);
  8087. // If file and file input are set
  8088. if (url.indexOf("file:") !== -1) {
  8089. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8090. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8091. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8092. }
  8093. }
  8094. var loadUrl = Tools.BaseUrl + url;
  8095. var aborted = false;
  8096. var fileRequest = {
  8097. onCompleteObservable: new BABYLON.Observable(),
  8098. abort: function () { return aborted = true; },
  8099. };
  8100. var requestFile = function () {
  8101. var request = new XMLHttpRequest();
  8102. var retryHandle = null;
  8103. fileRequest.abort = function () {
  8104. aborted = true;
  8105. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8106. request.abort();
  8107. }
  8108. if (retryHandle !== null) {
  8109. clearTimeout(retryHandle);
  8110. retryHandle = null;
  8111. }
  8112. };
  8113. var retryLoop = function (retryIndex) {
  8114. request.open('GET', loadUrl, true);
  8115. if (useArrayBuffer) {
  8116. request.responseType = "arraybuffer";
  8117. }
  8118. if (onProgress) {
  8119. request.addEventListener("progress", onProgress);
  8120. }
  8121. var onLoadEnd = function () {
  8122. request.removeEventListener("loadend", onLoadEnd);
  8123. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8124. fileRequest.onCompleteObservable.clear();
  8125. };
  8126. request.addEventListener("loadend", onLoadEnd);
  8127. var onReadyStateChange = function () {
  8128. if (aborted) {
  8129. return;
  8130. }
  8131. // In case of undefined state in some browsers.
  8132. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8133. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8134. request.removeEventListener("readystatechange", onReadyStateChange);
  8135. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8136. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8137. return;
  8138. }
  8139. var retryStrategy = Tools.DefaultRetryStrategy;
  8140. if (retryStrategy) {
  8141. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8142. if (waitTime !== -1) {
  8143. // Prevent the request from completing for retry.
  8144. request.removeEventListener("loadend", onLoadEnd);
  8145. request = new XMLHttpRequest();
  8146. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8147. return;
  8148. }
  8149. }
  8150. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8151. if (onError) {
  8152. onError(request, e);
  8153. }
  8154. else {
  8155. throw e;
  8156. }
  8157. }
  8158. };
  8159. request.addEventListener("readystatechange", onReadyStateChange);
  8160. request.send();
  8161. };
  8162. retryLoop(0);
  8163. };
  8164. // Caching all files
  8165. if (database && database.enableSceneOffline) {
  8166. var noIndexedDB_1 = function () {
  8167. if (!aborted) {
  8168. requestFile();
  8169. }
  8170. };
  8171. var loadFromIndexedDB = function () {
  8172. // TODO: database needs to support aborting and should return a IFileRequest
  8173. if (aborted) {
  8174. return;
  8175. }
  8176. if (database) {
  8177. database.loadFileFromDB(url, function (data) {
  8178. if (!aborted) {
  8179. onSuccess(data);
  8180. }
  8181. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8182. }, onProgress ? function (event) {
  8183. if (!aborted) {
  8184. onProgress(event);
  8185. }
  8186. } : undefined, noIndexedDB_1, useArrayBuffer);
  8187. }
  8188. };
  8189. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8190. }
  8191. else {
  8192. requestFile();
  8193. }
  8194. return fileRequest;
  8195. };
  8196. /**
  8197. * Load a script (identified by an url). When the url returns, the
  8198. * content of this file is added into a new script element, attached to the DOM (body element)
  8199. */
  8200. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8201. var head = document.getElementsByTagName('head')[0];
  8202. var script = document.createElement('script');
  8203. script.type = 'text/javascript';
  8204. script.src = scriptUrl;
  8205. script.onload = function () {
  8206. if (onSuccess) {
  8207. onSuccess();
  8208. }
  8209. };
  8210. script.onerror = function (e) {
  8211. if (onError) {
  8212. onError("Unable to load script", e);
  8213. }
  8214. };
  8215. head.appendChild(script);
  8216. };
  8217. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8218. var reader = new FileReader();
  8219. var request = {
  8220. onCompleteObservable: new BABYLON.Observable(),
  8221. abort: function () { return reader.abort(); },
  8222. };
  8223. reader.onloadend = function (e) {
  8224. request.onCompleteObservable.notifyObservers(request);
  8225. };
  8226. reader.onload = function (e) {
  8227. //target doesn't have result from ts 1.3
  8228. callback(e.target['result']);
  8229. };
  8230. reader.onprogress = progressCallback;
  8231. reader.readAsDataURL(fileToLoad);
  8232. return request;
  8233. };
  8234. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8235. var reader = new FileReader();
  8236. var request = {
  8237. onCompleteObservable: new BABYLON.Observable(),
  8238. abort: function () { return reader.abort(); },
  8239. };
  8240. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8241. reader.onerror = function (e) {
  8242. Tools.Log("Error while reading file: " + fileToLoad.name);
  8243. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8244. };
  8245. reader.onload = function (e) {
  8246. //target doesn't have result from ts 1.3
  8247. callback(e.target['result']);
  8248. };
  8249. if (progressCallBack) {
  8250. reader.onprogress = progressCallBack;
  8251. }
  8252. if (!useArrayBuffer) {
  8253. // Asynchronous read
  8254. reader.readAsText(fileToLoad);
  8255. }
  8256. else {
  8257. reader.readAsArrayBuffer(fileToLoad);
  8258. }
  8259. return request;
  8260. };
  8261. //returns a downloadable url to a file content.
  8262. Tools.FileAsURL = function (content) {
  8263. var fileBlob = new Blob([content]);
  8264. var url = window.URL || window.webkitURL;
  8265. var link = url.createObjectURL(fileBlob);
  8266. return link;
  8267. };
  8268. // Misc.
  8269. Tools.Format = function (value, decimals) {
  8270. if (decimals === void 0) { decimals = 2; }
  8271. return value.toFixed(decimals);
  8272. };
  8273. Tools.CheckExtends = function (v, min, max) {
  8274. if (v.x < min.x)
  8275. min.x = v.x;
  8276. if (v.y < min.y)
  8277. min.y = v.y;
  8278. if (v.z < min.z)
  8279. min.z = v.z;
  8280. if (v.x > max.x)
  8281. max.x = v.x;
  8282. if (v.y > max.y)
  8283. max.y = v.y;
  8284. if (v.z > max.z)
  8285. max.z = v.z;
  8286. };
  8287. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8288. for (var prop in source) {
  8289. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8290. continue;
  8291. }
  8292. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8293. continue;
  8294. }
  8295. var sourceValue = source[prop];
  8296. var typeOfSourceValue = typeof sourceValue;
  8297. if (typeOfSourceValue === "function") {
  8298. continue;
  8299. }
  8300. if (typeOfSourceValue === "object") {
  8301. if (sourceValue instanceof Array) {
  8302. destination[prop] = [];
  8303. if (sourceValue.length > 0) {
  8304. if (typeof sourceValue[0] == "object") {
  8305. for (var index = 0; index < sourceValue.length; index++) {
  8306. var clonedValue = cloneValue(sourceValue[index], destination);
  8307. if (destination[prop].indexOf(clonedValue) === -1) {
  8308. destination[prop].push(clonedValue);
  8309. }
  8310. }
  8311. }
  8312. else {
  8313. destination[prop] = sourceValue.slice(0);
  8314. }
  8315. }
  8316. }
  8317. else {
  8318. destination[prop] = cloneValue(sourceValue, destination);
  8319. }
  8320. }
  8321. else {
  8322. destination[prop] = sourceValue;
  8323. }
  8324. }
  8325. };
  8326. Tools.IsEmpty = function (obj) {
  8327. for (var i in obj) {
  8328. if (obj.hasOwnProperty(i)) {
  8329. return false;
  8330. }
  8331. }
  8332. return true;
  8333. };
  8334. Tools.RegisterTopRootEvents = function (events) {
  8335. for (var index = 0; index < events.length; index++) {
  8336. var event = events[index];
  8337. window.addEventListener(event.name, event.handler, false);
  8338. try {
  8339. if (window.parent) {
  8340. window.parent.addEventListener(event.name, event.handler, false);
  8341. }
  8342. }
  8343. catch (e) {
  8344. // Silently fails...
  8345. }
  8346. }
  8347. };
  8348. Tools.UnregisterTopRootEvents = function (events) {
  8349. for (var index = 0; index < events.length; index++) {
  8350. var event = events[index];
  8351. window.removeEventListener(event.name, event.handler);
  8352. try {
  8353. if (window.parent) {
  8354. window.parent.removeEventListener(event.name, event.handler);
  8355. }
  8356. }
  8357. catch (e) {
  8358. // Silently fails...
  8359. }
  8360. }
  8361. };
  8362. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8363. if (mimeType === void 0) { mimeType = "image/png"; }
  8364. // Read the contents of the framebuffer
  8365. var numberOfChannelsByLine = width * 4;
  8366. var halfHeight = height / 2;
  8367. //Reading datas from WebGL
  8368. var data = engine.readPixels(0, 0, width, height);
  8369. //To flip image on Y axis.
  8370. for (var i = 0; i < halfHeight; i++) {
  8371. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8372. var currentCell = j + i * numberOfChannelsByLine;
  8373. var targetLine = height - i - 1;
  8374. var targetCell = j + targetLine * numberOfChannelsByLine;
  8375. var temp = data[currentCell];
  8376. data[currentCell] = data[targetCell];
  8377. data[targetCell] = temp;
  8378. }
  8379. }
  8380. // Create a 2D canvas to store the result
  8381. if (!screenshotCanvas) {
  8382. screenshotCanvas = document.createElement('canvas');
  8383. }
  8384. screenshotCanvas.width = width;
  8385. screenshotCanvas.height = height;
  8386. var context = screenshotCanvas.getContext('2d');
  8387. if (context) {
  8388. // Copy the pixels to a 2D canvas
  8389. var imageData = context.createImageData(width, height);
  8390. var castData = (imageData.data);
  8391. castData.set(data);
  8392. context.putImageData(imageData, 0, 0);
  8393. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8394. }
  8395. };
  8396. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8397. if (mimeType === void 0) { mimeType = "image/png"; }
  8398. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8399. if (successCallback) {
  8400. successCallback(base64Image);
  8401. }
  8402. else {
  8403. // We need HTMLCanvasElement.toBlob for HD screenshots
  8404. if (!screenshotCanvas.toBlob) {
  8405. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8406. screenshotCanvas.toBlob = function (callback, type, quality) {
  8407. var _this = this;
  8408. setTimeout(function () {
  8409. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8410. for (var i = 0; i < len; i++) {
  8411. arr[i] = binStr.charCodeAt(i);
  8412. }
  8413. callback(new Blob([arr], { type: type || 'image/png' }));
  8414. });
  8415. };
  8416. }
  8417. screenshotCanvas.toBlob(function (blob) {
  8418. var url = URL.createObjectURL(blob);
  8419. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8420. if (("download" in document.createElement("a"))) {
  8421. var a = window.document.createElement("a");
  8422. a.href = url;
  8423. if (fileName) {
  8424. a.setAttribute("download", fileName);
  8425. }
  8426. else {
  8427. var date = new Date();
  8428. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8429. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8430. }
  8431. window.document.body.appendChild(a);
  8432. a.addEventListener("click", function () {
  8433. if (a.parentElement) {
  8434. a.parentElement.removeChild(a);
  8435. }
  8436. });
  8437. a.click();
  8438. }
  8439. else {
  8440. var newWindow = window.open("");
  8441. if (!newWindow)
  8442. return;
  8443. var img = newWindow.document.createElement("img");
  8444. img.onload = function () {
  8445. // no longer need to read the blob so it's revoked
  8446. URL.revokeObjectURL(url);
  8447. };
  8448. img.src = url;
  8449. newWindow.document.body.appendChild(img);
  8450. }
  8451. });
  8452. }
  8453. };
  8454. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8455. if (mimeType === void 0) { mimeType = "image/png"; }
  8456. var width;
  8457. var height;
  8458. // If a precision value is specified
  8459. if (size.precision) {
  8460. width = Math.round(engine.getRenderWidth() * size.precision);
  8461. height = Math.round(width / engine.getAspectRatio(camera));
  8462. }
  8463. else if (size.width && size.height) {
  8464. width = size.width;
  8465. height = size.height;
  8466. }
  8467. else if (size.width && !size.height) {
  8468. width = size.width;
  8469. height = Math.round(width / engine.getAspectRatio(camera));
  8470. }
  8471. else if (size.height && !size.width) {
  8472. height = size.height;
  8473. width = Math.round(height * engine.getAspectRatio(camera));
  8474. }
  8475. else if (!isNaN(size)) {
  8476. height = size;
  8477. width = size;
  8478. }
  8479. else {
  8480. Tools.Error("Invalid 'size' parameter !");
  8481. return;
  8482. }
  8483. if (!screenshotCanvas) {
  8484. screenshotCanvas = document.createElement('canvas');
  8485. }
  8486. screenshotCanvas.width = width;
  8487. screenshotCanvas.height = height;
  8488. var renderContext = screenshotCanvas.getContext("2d");
  8489. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8490. var newWidth = width;
  8491. var newHeight = newWidth / ratio;
  8492. if (newHeight > height) {
  8493. newHeight = height;
  8494. newWidth = newHeight * ratio;
  8495. }
  8496. var offsetX = Math.max(0, width - newWidth) / 2;
  8497. var offsetY = Math.max(0, height - newHeight) / 2;
  8498. var renderingCanvas = engine.getRenderingCanvas();
  8499. if (renderContext && renderingCanvas) {
  8500. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8501. }
  8502. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8503. };
  8504. /**
  8505. * Generates an image screenshot from the specified camera.
  8506. *
  8507. * @param engine The engine to use for rendering
  8508. * @param camera The camera to use for rendering
  8509. * @param size This parameter can be set to a single number or to an object with the
  8510. * following (optional) properties: precision, width, height. If a single number is passed,
  8511. * it will be used for both width and height. If an object is passed, the screenshot size
  8512. * will be derived from the parameters. The precision property is a multiplier allowing
  8513. * rendering at a higher or lower resolution.
  8514. * @param successCallback The callback receives a single parameter which contains the
  8515. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8516. * src parameter of an <img> to display it.
  8517. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8518. * Check your browser for supported MIME types.
  8519. * @param samples Texture samples (default: 1)
  8520. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8521. * @param fileName A name for for the downloaded file.
  8522. * @constructor
  8523. */
  8524. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8525. if (mimeType === void 0) { mimeType = "image/png"; }
  8526. if (samples === void 0) { samples = 1; }
  8527. if (antialiasing === void 0) { antialiasing = false; }
  8528. var width;
  8529. var height;
  8530. //If a precision value is specified
  8531. if (size.precision) {
  8532. width = Math.round(engine.getRenderWidth() * size.precision);
  8533. height = Math.round(width / engine.getAspectRatio(camera));
  8534. size = { width: width, height: height };
  8535. }
  8536. else if (size.width && size.height) {
  8537. width = size.width;
  8538. height = size.height;
  8539. }
  8540. else if (size.width && !size.height) {
  8541. width = size.width;
  8542. height = Math.round(width / engine.getAspectRatio(camera));
  8543. size = { width: width, height: height };
  8544. }
  8545. else if (size.height && !size.width) {
  8546. height = size.height;
  8547. width = Math.round(height * engine.getAspectRatio(camera));
  8548. size = { width: width, height: height };
  8549. }
  8550. else if (!isNaN(size)) {
  8551. height = size;
  8552. width = size;
  8553. }
  8554. else {
  8555. Tools.Error("Invalid 'size' parameter !");
  8556. return;
  8557. }
  8558. var scene = camera.getScene();
  8559. var previousCamera = null;
  8560. if (scene.activeCamera !== camera) {
  8561. previousCamera = scene.activeCamera;
  8562. scene.activeCamera = camera;
  8563. }
  8564. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8565. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8566. texture.renderList = null;
  8567. texture.samples = samples;
  8568. if (antialiasing) {
  8569. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8570. }
  8571. texture.onAfterRenderObservable.add(function () {
  8572. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8573. });
  8574. scene.incrementRenderId();
  8575. scene.resetCachedMaterial();
  8576. texture.render(true);
  8577. texture.dispose();
  8578. if (previousCamera) {
  8579. scene.activeCamera = previousCamera;
  8580. }
  8581. camera.getProjectionMatrix(true); // Force cache refresh;
  8582. };
  8583. // XHR response validator for local file scenario
  8584. Tools.ValidateXHRData = function (xhr, dataType) {
  8585. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8586. if (dataType === void 0) { dataType = 7; }
  8587. try {
  8588. if (dataType & 1) {
  8589. if (xhr.responseText && xhr.responseText.length > 0) {
  8590. return true;
  8591. }
  8592. else if (dataType === 1) {
  8593. return false;
  8594. }
  8595. }
  8596. if (dataType & 2) {
  8597. // Check header width and height since there is no "TGA" magic number
  8598. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8599. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8600. return true;
  8601. }
  8602. else if (dataType === 2) {
  8603. return false;
  8604. }
  8605. }
  8606. if (dataType & 4) {
  8607. // Check for the "DDS" magic number
  8608. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8609. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8610. return true;
  8611. }
  8612. else {
  8613. return false;
  8614. }
  8615. }
  8616. }
  8617. catch (e) {
  8618. // Global protection
  8619. }
  8620. return false;
  8621. };
  8622. /**
  8623. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8624. * Be aware Math.random() could cause collisions, but:
  8625. * "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"
  8626. */
  8627. Tools.RandomId = function () {
  8628. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8629. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8630. return v.toString(16);
  8631. });
  8632. };
  8633. /**
  8634. * Test if the given uri is a base64 string.
  8635. * @param uri The uri to test
  8636. * @return True if the uri is a base64 string or false otherwise.
  8637. */
  8638. Tools.IsBase64 = function (uri) {
  8639. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8640. };
  8641. /**
  8642. * Decode the given base64 uri.
  8643. * @param uri The uri to decode
  8644. * @return The decoded base64 data.
  8645. */
  8646. Tools.DecodeBase64 = function (uri) {
  8647. var decodedString = atob(uri.split(",")[1]);
  8648. var bufferLength = decodedString.length;
  8649. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8650. for (var i = 0; i < bufferLength; i++) {
  8651. bufferView[i] = decodedString.charCodeAt(i);
  8652. }
  8653. return bufferView.buffer;
  8654. };
  8655. Object.defineProperty(Tools, "NoneLogLevel", {
  8656. get: function () {
  8657. return Tools._NoneLogLevel;
  8658. },
  8659. enumerable: true,
  8660. configurable: true
  8661. });
  8662. Object.defineProperty(Tools, "MessageLogLevel", {
  8663. get: function () {
  8664. return Tools._MessageLogLevel;
  8665. },
  8666. enumerable: true,
  8667. configurable: true
  8668. });
  8669. Object.defineProperty(Tools, "WarningLogLevel", {
  8670. get: function () {
  8671. return Tools._WarningLogLevel;
  8672. },
  8673. enumerable: true,
  8674. configurable: true
  8675. });
  8676. Object.defineProperty(Tools, "ErrorLogLevel", {
  8677. get: function () {
  8678. return Tools._ErrorLogLevel;
  8679. },
  8680. enumerable: true,
  8681. configurable: true
  8682. });
  8683. Object.defineProperty(Tools, "AllLogLevel", {
  8684. get: function () {
  8685. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8686. },
  8687. enumerable: true,
  8688. configurable: true
  8689. });
  8690. Tools._AddLogEntry = function (entry) {
  8691. Tools._LogCache = entry + Tools._LogCache;
  8692. if (Tools.OnNewCacheEntry) {
  8693. Tools.OnNewCacheEntry(entry);
  8694. }
  8695. };
  8696. Tools._FormatMessage = function (message) {
  8697. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8698. var date = new Date();
  8699. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8700. };
  8701. Tools._LogDisabled = function (message) {
  8702. // nothing to do
  8703. };
  8704. Tools._LogEnabled = function (message) {
  8705. var formattedMessage = Tools._FormatMessage(message);
  8706. console.log("BJS - " + formattedMessage);
  8707. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8708. Tools._AddLogEntry(entry);
  8709. };
  8710. Tools._WarnDisabled = function (message) {
  8711. // nothing to do
  8712. };
  8713. Tools._WarnEnabled = function (message) {
  8714. var formattedMessage = Tools._FormatMessage(message);
  8715. console.warn("BJS - " + formattedMessage);
  8716. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8717. Tools._AddLogEntry(entry);
  8718. };
  8719. Tools._ErrorDisabled = function (message) {
  8720. // nothing to do
  8721. };
  8722. Tools._ErrorEnabled = function (message) {
  8723. Tools.errorsCount++;
  8724. var formattedMessage = Tools._FormatMessage(message);
  8725. console.error("BJS - " + formattedMessage);
  8726. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8727. Tools._AddLogEntry(entry);
  8728. };
  8729. Object.defineProperty(Tools, "LogCache", {
  8730. get: function () {
  8731. return Tools._LogCache;
  8732. },
  8733. enumerable: true,
  8734. configurable: true
  8735. });
  8736. Tools.ClearLogCache = function () {
  8737. Tools._LogCache = "";
  8738. Tools.errorsCount = 0;
  8739. };
  8740. Object.defineProperty(Tools, "LogLevels", {
  8741. set: function (level) {
  8742. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8743. Tools.Log = Tools._LogEnabled;
  8744. }
  8745. else {
  8746. Tools.Log = Tools._LogDisabled;
  8747. }
  8748. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8749. Tools.Warn = Tools._WarnEnabled;
  8750. }
  8751. else {
  8752. Tools.Warn = Tools._WarnDisabled;
  8753. }
  8754. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8755. Tools.Error = Tools._ErrorEnabled;
  8756. }
  8757. else {
  8758. Tools.Error = Tools._ErrorDisabled;
  8759. }
  8760. },
  8761. enumerable: true,
  8762. configurable: true
  8763. });
  8764. Tools.IsWindowObjectExist = function () {
  8765. return (typeof window) !== "undefined";
  8766. };
  8767. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8768. get: function () {
  8769. return Tools._PerformanceNoneLogLevel;
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8775. get: function () {
  8776. return Tools._PerformanceUserMarkLogLevel;
  8777. },
  8778. enumerable: true,
  8779. configurable: true
  8780. });
  8781. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8782. get: function () {
  8783. return Tools._PerformanceConsoleLogLevel;
  8784. },
  8785. enumerable: true,
  8786. configurable: true
  8787. });
  8788. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8789. set: function (level) {
  8790. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8791. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8792. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8793. return;
  8794. }
  8795. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8796. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8797. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8798. return;
  8799. }
  8800. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8801. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8802. },
  8803. enumerable: true,
  8804. configurable: true
  8805. });
  8806. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8807. };
  8808. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8809. };
  8810. Tools._StartUserMark = function (counterName, condition) {
  8811. if (condition === void 0) { condition = true; }
  8812. if (!Tools._performance) {
  8813. if (!Tools.IsWindowObjectExist()) {
  8814. return;
  8815. }
  8816. Tools._performance = window.performance;
  8817. }
  8818. if (!condition || !Tools._performance.mark) {
  8819. return;
  8820. }
  8821. Tools._performance.mark(counterName + "-Begin");
  8822. };
  8823. Tools._EndUserMark = function (counterName, condition) {
  8824. if (condition === void 0) { condition = true; }
  8825. if (!condition || !Tools._performance.mark) {
  8826. return;
  8827. }
  8828. Tools._performance.mark(counterName + "-End");
  8829. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8830. };
  8831. Tools._StartPerformanceConsole = function (counterName, condition) {
  8832. if (condition === void 0) { condition = true; }
  8833. if (!condition) {
  8834. return;
  8835. }
  8836. Tools._StartUserMark(counterName, condition);
  8837. if (console.time) {
  8838. console.time(counterName);
  8839. }
  8840. };
  8841. Tools._EndPerformanceConsole = function (counterName, condition) {
  8842. if (condition === void 0) { condition = true; }
  8843. if (!condition) {
  8844. return;
  8845. }
  8846. Tools._EndUserMark(counterName, condition);
  8847. if (console.time) {
  8848. console.timeEnd(counterName);
  8849. }
  8850. };
  8851. Object.defineProperty(Tools, "Now", {
  8852. get: function () {
  8853. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8854. return window.performance.now();
  8855. }
  8856. return new Date().getTime();
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. /**
  8862. * This method will return the name of the class used to create the instance of the given object.
  8863. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8864. * @param object the object to get the class name from
  8865. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8866. */
  8867. Tools.GetClassName = function (object, isType) {
  8868. if (isType === void 0) { isType = false; }
  8869. var name = null;
  8870. if (!isType && object.getClassName) {
  8871. name = object.getClassName();
  8872. }
  8873. else {
  8874. if (object instanceof Object) {
  8875. var classObj = isType ? object : Object.getPrototypeOf(object);
  8876. name = classObj.constructor["__bjsclassName__"];
  8877. }
  8878. if (!name) {
  8879. name = typeof object;
  8880. }
  8881. }
  8882. return name;
  8883. };
  8884. Tools.First = function (array, predicate) {
  8885. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8886. var el = array_1[_i];
  8887. if (predicate(el)) {
  8888. return el;
  8889. }
  8890. }
  8891. return null;
  8892. };
  8893. /**
  8894. * This method will return the name of the full name of the class, including its owning module (if any).
  8895. * 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).
  8896. * @param object the object to get the class name from
  8897. * @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.
  8898. */
  8899. Tools.getFullClassName = function (object, isType) {
  8900. if (isType === void 0) { isType = false; }
  8901. var className = null;
  8902. var moduleName = null;
  8903. if (!isType && object.getClassName) {
  8904. className = object.getClassName();
  8905. }
  8906. else {
  8907. if (object instanceof Object) {
  8908. var classObj = isType ? object : Object.getPrototypeOf(object);
  8909. className = classObj.constructor["__bjsclassName__"];
  8910. moduleName = classObj.constructor["__bjsmoduleName__"];
  8911. }
  8912. if (!className) {
  8913. className = typeof object;
  8914. }
  8915. }
  8916. if (!className) {
  8917. return null;
  8918. }
  8919. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8920. };
  8921. /**
  8922. * 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.
  8923. * @param array
  8924. */
  8925. Tools.arrayOrStringFeeder = function (array) {
  8926. return function (index) {
  8927. if (index >= array.length) {
  8928. return null;
  8929. }
  8930. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8931. if (val && val.getHashCode) {
  8932. val = val.getHashCode();
  8933. }
  8934. if (typeof val === "string") {
  8935. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8936. }
  8937. return val;
  8938. };
  8939. };
  8940. /**
  8941. * Compute the hashCode of a stream of number
  8942. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8943. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8944. * @return the hash code computed
  8945. */
  8946. Tools.hashCodeFromStream = function (feeder) {
  8947. // Based from here: http://stackoverflow.com/a/7616484/802124
  8948. var hash = 0;
  8949. var index = 0;
  8950. var chr = feeder(index++);
  8951. while (chr != null) {
  8952. hash = ((hash << 5) - hash) + chr;
  8953. hash |= 0; // Convert to 32bit integer
  8954. chr = feeder(index++);
  8955. }
  8956. return hash;
  8957. };
  8958. /**
  8959. * Returns a promise that resolves after the given amount of time.
  8960. * @param delay Number of milliseconds to delay
  8961. * @returns Promise that resolves after the given amount of time
  8962. */
  8963. Tools.DelayAsync = function (delay) {
  8964. return new Promise(function (resolve) {
  8965. setTimeout(function () {
  8966. resolve();
  8967. }, delay);
  8968. });
  8969. };
  8970. Tools.BaseUrl = "";
  8971. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8972. /**
  8973. * Default behaviour for cors in the application.
  8974. * It can be a string if the expected behavior is identical in the entire app.
  8975. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8976. */
  8977. Tools.CorsBehavior = "anonymous";
  8978. Tools.UseFallbackTexture = true;
  8979. /**
  8980. * Use this object to register external classes like custom textures or material
  8981. * to allow the laoders to instantiate them
  8982. */
  8983. Tools.RegisteredExternalClasses = {};
  8984. // Used in case of a texture loading problem
  8985. 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";
  8986. Tools.PreprocessUrl = function (url) {
  8987. return url;
  8988. };
  8989. // Logs
  8990. Tools._NoneLogLevel = 0;
  8991. Tools._MessageLogLevel = 1;
  8992. Tools._WarningLogLevel = 2;
  8993. Tools._ErrorLogLevel = 4;
  8994. Tools._LogCache = "";
  8995. Tools.errorsCount = 0;
  8996. Tools.Log = Tools._LogEnabled;
  8997. Tools.Warn = Tools._WarnEnabled;
  8998. Tools.Error = Tools._ErrorEnabled;
  8999. // Performances
  9000. Tools._PerformanceNoneLogLevel = 0;
  9001. Tools._PerformanceUserMarkLogLevel = 1;
  9002. Tools._PerformanceConsoleLogLevel = 2;
  9003. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9004. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9005. return Tools;
  9006. }());
  9007. BABYLON.Tools = Tools;
  9008. /**
  9009. * This class is used to track a performance counter which is number based.
  9010. * The user has access to many properties which give statistics of different nature
  9011. *
  9012. * The implementer can track two kinds of Performance Counter: time and count
  9013. * 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.
  9014. * 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.
  9015. */
  9016. var PerfCounter = /** @class */ (function () {
  9017. function PerfCounter() {
  9018. this._startMonitoringTime = 0;
  9019. this._min = 0;
  9020. this._max = 0;
  9021. this._average = 0;
  9022. this._lastSecAverage = 0;
  9023. this._current = 0;
  9024. this._totalValueCount = 0;
  9025. this._totalAccumulated = 0;
  9026. this._lastSecAccumulated = 0;
  9027. this._lastSecTime = 0;
  9028. this._lastSecValueCount = 0;
  9029. }
  9030. Object.defineProperty(PerfCounter.prototype, "min", {
  9031. /**
  9032. * Returns the smallest value ever
  9033. */
  9034. get: function () {
  9035. return this._min;
  9036. },
  9037. enumerable: true,
  9038. configurable: true
  9039. });
  9040. Object.defineProperty(PerfCounter.prototype, "max", {
  9041. /**
  9042. * Returns the biggest value ever
  9043. */
  9044. get: function () {
  9045. return this._max;
  9046. },
  9047. enumerable: true,
  9048. configurable: true
  9049. });
  9050. Object.defineProperty(PerfCounter.prototype, "average", {
  9051. /**
  9052. * Returns the average value since the performance counter is running
  9053. */
  9054. get: function () {
  9055. return this._average;
  9056. },
  9057. enumerable: true,
  9058. configurable: true
  9059. });
  9060. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9061. /**
  9062. * Returns the average value of the last second the counter was monitored
  9063. */
  9064. get: function () {
  9065. return this._lastSecAverage;
  9066. },
  9067. enumerable: true,
  9068. configurable: true
  9069. });
  9070. Object.defineProperty(PerfCounter.prototype, "current", {
  9071. /**
  9072. * Returns the current value
  9073. */
  9074. get: function () {
  9075. return this._current;
  9076. },
  9077. enumerable: true,
  9078. configurable: true
  9079. });
  9080. Object.defineProperty(PerfCounter.prototype, "total", {
  9081. get: function () {
  9082. return this._totalAccumulated;
  9083. },
  9084. enumerable: true,
  9085. configurable: true
  9086. });
  9087. Object.defineProperty(PerfCounter.prototype, "count", {
  9088. get: function () {
  9089. return this._totalValueCount;
  9090. },
  9091. enumerable: true,
  9092. configurable: true
  9093. });
  9094. /**
  9095. * Call this method to start monitoring a new frame.
  9096. * 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.
  9097. */
  9098. PerfCounter.prototype.fetchNewFrame = function () {
  9099. this._totalValueCount++;
  9100. this._current = 0;
  9101. this._lastSecValueCount++;
  9102. };
  9103. /**
  9104. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9105. * @param newCount the count value to add to the monitored count
  9106. * @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.
  9107. */
  9108. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9109. if (!PerfCounter.Enabled) {
  9110. return;
  9111. }
  9112. this._current += newCount;
  9113. if (fetchResult) {
  9114. this._fetchResult();
  9115. }
  9116. };
  9117. /**
  9118. * Start monitoring this performance counter
  9119. */
  9120. PerfCounter.prototype.beginMonitoring = function () {
  9121. if (!PerfCounter.Enabled) {
  9122. return;
  9123. }
  9124. this._startMonitoringTime = Tools.Now;
  9125. };
  9126. /**
  9127. * Compute the time lapsed since the previous beginMonitoring() call.
  9128. * @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
  9129. */
  9130. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9131. if (newFrame === void 0) { newFrame = true; }
  9132. if (!PerfCounter.Enabled) {
  9133. return;
  9134. }
  9135. if (newFrame) {
  9136. this.fetchNewFrame();
  9137. }
  9138. var currentTime = Tools.Now;
  9139. this._current = currentTime - this._startMonitoringTime;
  9140. if (newFrame) {
  9141. this._fetchResult();
  9142. }
  9143. };
  9144. PerfCounter.prototype._fetchResult = function () {
  9145. this._totalAccumulated += this._current;
  9146. this._lastSecAccumulated += this._current;
  9147. // Min/Max update
  9148. this._min = Math.min(this._min, this._current);
  9149. this._max = Math.max(this._max, this._current);
  9150. this._average = this._totalAccumulated / this._totalValueCount;
  9151. // Reset last sec?
  9152. var now = Tools.Now;
  9153. if ((now - this._lastSecTime) > 1000) {
  9154. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9155. this._lastSecTime = now;
  9156. this._lastSecAccumulated = 0;
  9157. this._lastSecValueCount = 0;
  9158. }
  9159. };
  9160. PerfCounter.Enabled = true;
  9161. return PerfCounter;
  9162. }());
  9163. BABYLON.PerfCounter = PerfCounter;
  9164. /**
  9165. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9166. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9167. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9168. * @param name The name of the class, case should be preserved
  9169. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9170. */
  9171. function className(name, module) {
  9172. return function (target) {
  9173. target["__bjsclassName__"] = name;
  9174. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9175. };
  9176. }
  9177. BABYLON.className = className;
  9178. /**
  9179. * An implementation of a loop for asynchronous functions.
  9180. */
  9181. var AsyncLoop = /** @class */ (function () {
  9182. /**
  9183. * Constroctor.
  9184. * @param iterations the number of iterations.
  9185. * @param _fn the function to run each iteration
  9186. * @param _successCallback the callback that will be called upon succesful execution
  9187. * @param offset starting offset.
  9188. */
  9189. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9190. if (offset === void 0) { offset = 0; }
  9191. this.iterations = iterations;
  9192. this._fn = _fn;
  9193. this._successCallback = _successCallback;
  9194. this.index = offset - 1;
  9195. this._done = false;
  9196. }
  9197. /**
  9198. * Execute the next iteration. Must be called after the last iteration was finished.
  9199. */
  9200. AsyncLoop.prototype.executeNext = function () {
  9201. if (!this._done) {
  9202. if (this.index + 1 < this.iterations) {
  9203. ++this.index;
  9204. this._fn(this);
  9205. }
  9206. else {
  9207. this.breakLoop();
  9208. }
  9209. }
  9210. };
  9211. /**
  9212. * Break the loop and run the success callback.
  9213. */
  9214. AsyncLoop.prototype.breakLoop = function () {
  9215. this._done = true;
  9216. this._successCallback();
  9217. };
  9218. /**
  9219. * Helper function
  9220. */
  9221. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9222. if (offset === void 0) { offset = 0; }
  9223. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9224. loop.executeNext();
  9225. return loop;
  9226. };
  9227. /**
  9228. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9229. * @param iterations total number of iterations
  9230. * @param syncedIterations number of synchronous iterations in each async iteration.
  9231. * @param fn the function to call each iteration.
  9232. * @param callback a success call back that will be called when iterating stops.
  9233. * @param breakFunction a break condition (optional)
  9234. * @param timeout timeout settings for the setTimeout function. default - 0.
  9235. * @constructor
  9236. */
  9237. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9238. if (timeout === void 0) { timeout = 0; }
  9239. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9240. if (breakFunction && breakFunction())
  9241. loop.breakLoop();
  9242. else {
  9243. setTimeout(function () {
  9244. for (var i = 0; i < syncedIterations; ++i) {
  9245. var iteration = (loop.index * syncedIterations) + i;
  9246. if (iteration >= iterations)
  9247. break;
  9248. fn(iteration);
  9249. if (breakFunction && breakFunction()) {
  9250. loop.breakLoop();
  9251. break;
  9252. }
  9253. }
  9254. loop.executeNext();
  9255. }, timeout);
  9256. }
  9257. }, callback);
  9258. };
  9259. return AsyncLoop;
  9260. }());
  9261. BABYLON.AsyncLoop = AsyncLoop;
  9262. })(BABYLON || (BABYLON = {}));
  9263. //# sourceMappingURL=babylon.tools.js.map
  9264. var BABYLON;
  9265. (function (BABYLON) {
  9266. var PromiseStates;
  9267. (function (PromiseStates) {
  9268. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9269. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9270. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9271. })(PromiseStates || (PromiseStates = {}));
  9272. var FulFillmentAgregator = /** @class */ (function () {
  9273. function FulFillmentAgregator() {
  9274. this.count = 0;
  9275. this.target = 0;
  9276. this.results = [];
  9277. }
  9278. return FulFillmentAgregator;
  9279. }());
  9280. var InternalPromise = /** @class */ (function () {
  9281. function InternalPromise(resolver) {
  9282. var _this = this;
  9283. this._state = PromiseStates.Pending;
  9284. this._children = new Array();
  9285. this._rejectWasConsumed = false;
  9286. if (!resolver) {
  9287. return;
  9288. }
  9289. try {
  9290. resolver(function (value) {
  9291. _this._resolve(value);
  9292. }, function (reason) {
  9293. _this._reject(reason);
  9294. });
  9295. }
  9296. catch (e) {
  9297. this._reject(e);
  9298. }
  9299. }
  9300. InternalPromise.prototype.catch = function (onRejected) {
  9301. return this.then(undefined, onRejected);
  9302. };
  9303. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9304. var _this = this;
  9305. var newPromise = new InternalPromise();
  9306. newPromise._onFulfilled = onFulfilled;
  9307. newPromise._onRejected = onRejected;
  9308. // Composition
  9309. this._children.push(newPromise);
  9310. if (this._state !== PromiseStates.Pending) {
  9311. BABYLON.Tools.SetImmediate(function () {
  9312. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9313. var returnedValue = newPromise._resolve(_this._result);
  9314. if (returnedValue !== undefined && returnedValue !== null) {
  9315. if (returnedValue._state !== undefined) {
  9316. var returnedPromise = returnedValue;
  9317. newPromise._children.push(returnedPromise);
  9318. newPromise = returnedPromise;
  9319. }
  9320. else {
  9321. newPromise._result = returnedValue;
  9322. }
  9323. }
  9324. }
  9325. else {
  9326. newPromise._reject(_this._reason);
  9327. }
  9328. });
  9329. }
  9330. return newPromise;
  9331. };
  9332. InternalPromise.prototype._moveChildren = function (children) {
  9333. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9334. if (this._state === PromiseStates.Fulfilled) {
  9335. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9336. var child = _b[_i];
  9337. child._resolve(this._result);
  9338. }
  9339. }
  9340. else if (this._state === PromiseStates.Rejected) {
  9341. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9342. var child = _d[_c];
  9343. child._reject(this._reason);
  9344. }
  9345. }
  9346. var _a;
  9347. };
  9348. InternalPromise.prototype._resolve = function (value) {
  9349. try {
  9350. this._state = PromiseStates.Fulfilled;
  9351. this._result = value;
  9352. var returnedValue = null;
  9353. if (this._onFulfilled) {
  9354. returnedValue = this._onFulfilled(value);
  9355. }
  9356. if (returnedValue !== undefined && returnedValue !== null) {
  9357. if (returnedValue._state !== undefined) {
  9358. // Transmit children
  9359. var returnedPromise = returnedValue;
  9360. returnedPromise._moveChildren(this._children);
  9361. }
  9362. else {
  9363. value = returnedValue;
  9364. }
  9365. }
  9366. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9367. var child = _a[_i];
  9368. child._resolve(value);
  9369. }
  9370. this._children.length = 0;
  9371. delete this._onFulfilled;
  9372. delete this._onRejected;
  9373. return returnedValue;
  9374. }
  9375. catch (e) {
  9376. this._reject(e, true);
  9377. }
  9378. return null;
  9379. };
  9380. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9381. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9382. this._state = PromiseStates.Rejected;
  9383. this._reason = reason;
  9384. if (this._onRejected && !onLocalThrow) {
  9385. try {
  9386. this._onRejected(reason);
  9387. this._rejectWasConsumed = true;
  9388. }
  9389. catch (e) {
  9390. reason = e;
  9391. }
  9392. }
  9393. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9394. var child = _a[_i];
  9395. if (this._rejectWasConsumed) {
  9396. child._resolve(null);
  9397. }
  9398. else {
  9399. child._reject(reason);
  9400. }
  9401. }
  9402. this._children.length = 0;
  9403. delete this._onFulfilled;
  9404. delete this._onRejected;
  9405. };
  9406. InternalPromise.resolve = function (value) {
  9407. var newPromise = new InternalPromise();
  9408. newPromise._resolve(value);
  9409. return newPromise;
  9410. };
  9411. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9412. promise.then(function (value) {
  9413. agregator.results[index] = value;
  9414. agregator.count++;
  9415. if (agregator.count === agregator.target) {
  9416. agregator.rootPromise._resolve(agregator.results);
  9417. }
  9418. return null;
  9419. }, function (reason) {
  9420. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9421. agregator.rootPromise._reject(reason);
  9422. }
  9423. });
  9424. };
  9425. InternalPromise.all = function (promises) {
  9426. var newPromise = new InternalPromise();
  9427. var agregator = new FulFillmentAgregator();
  9428. agregator.target = promises.length;
  9429. agregator.rootPromise = newPromise;
  9430. if (promises.length) {
  9431. for (var index = 0; index < promises.length; index++) {
  9432. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9433. }
  9434. }
  9435. else {
  9436. newPromise._resolve([]);
  9437. }
  9438. return newPromise;
  9439. };
  9440. return InternalPromise;
  9441. }());
  9442. /**
  9443. * Helper class that provides a small promise polyfill
  9444. */
  9445. var PromisePolyfill = /** @class */ (function () {
  9446. function PromisePolyfill() {
  9447. }
  9448. /**
  9449. * Static function used to check if the polyfill is required
  9450. * If this is the case then the function will inject the polyfill to window.Promise
  9451. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9452. */
  9453. PromisePolyfill.Apply = function (force) {
  9454. if (force === void 0) { force = false; }
  9455. if (force || typeof Promise === 'undefined') {
  9456. var root = window;
  9457. root.Promise = InternalPromise;
  9458. }
  9459. };
  9460. return PromisePolyfill;
  9461. }());
  9462. BABYLON.PromisePolyfill = PromisePolyfill;
  9463. })(BABYLON || (BABYLON = {}));
  9464. //# sourceMappingURL=babylon.promise.js.map
  9465. var BABYLON;
  9466. (function (BABYLON) {
  9467. var _AlphaState = /** @class */ (function () {
  9468. /**
  9469. * Initializes the state.
  9470. */
  9471. function _AlphaState() {
  9472. this._isAlphaBlendDirty = false;
  9473. this._isBlendFunctionParametersDirty = false;
  9474. this._isBlendEquationParametersDirty = false;
  9475. this._isBlendConstantsDirty = false;
  9476. this._alphaBlend = false;
  9477. this._blendFunctionParameters = new Array(4);
  9478. this._blendEquationParameters = new Array(2);
  9479. this._blendConstants = new Array(4);
  9480. this.reset();
  9481. }
  9482. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9483. get: function () {
  9484. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9485. },
  9486. enumerable: true,
  9487. configurable: true
  9488. });
  9489. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9490. get: function () {
  9491. return this._alphaBlend;
  9492. },
  9493. set: function (value) {
  9494. if (this._alphaBlend === value) {
  9495. return;
  9496. }
  9497. this._alphaBlend = value;
  9498. this._isAlphaBlendDirty = true;
  9499. },
  9500. enumerable: true,
  9501. configurable: true
  9502. });
  9503. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9504. if (this._blendConstants[0] === r &&
  9505. this._blendConstants[1] === g &&
  9506. this._blendConstants[2] === b &&
  9507. this._blendConstants[3] === a) {
  9508. return;
  9509. }
  9510. this._blendConstants[0] = r;
  9511. this._blendConstants[1] = g;
  9512. this._blendConstants[2] = b;
  9513. this._blendConstants[3] = a;
  9514. this._isBlendConstantsDirty = true;
  9515. };
  9516. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9517. if (this._blendFunctionParameters[0] === value0 &&
  9518. this._blendFunctionParameters[1] === value1 &&
  9519. this._blendFunctionParameters[2] === value2 &&
  9520. this._blendFunctionParameters[3] === value3) {
  9521. return;
  9522. }
  9523. this._blendFunctionParameters[0] = value0;
  9524. this._blendFunctionParameters[1] = value1;
  9525. this._blendFunctionParameters[2] = value2;
  9526. this._blendFunctionParameters[3] = value3;
  9527. this._isBlendFunctionParametersDirty = true;
  9528. };
  9529. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9530. if (this._blendEquationParameters[0] === rgb &&
  9531. this._blendEquationParameters[1] === alpha) {
  9532. return;
  9533. }
  9534. this._blendEquationParameters[0] = rgb;
  9535. this._blendEquationParameters[1] = alpha;
  9536. this._isBlendEquationParametersDirty = true;
  9537. };
  9538. _AlphaState.prototype.reset = function () {
  9539. this._alphaBlend = false;
  9540. this._blendFunctionParameters[0] = null;
  9541. this._blendFunctionParameters[1] = null;
  9542. this._blendFunctionParameters[2] = null;
  9543. this._blendFunctionParameters[3] = null;
  9544. this._blendEquationParameters[0] = null;
  9545. this._blendEquationParameters[1] = null;
  9546. this._blendConstants[0] = null;
  9547. this._blendConstants[1] = null;
  9548. this._blendConstants[2] = null;
  9549. this._blendConstants[3] = null;
  9550. this._isAlphaBlendDirty = true;
  9551. this._isBlendFunctionParametersDirty = false;
  9552. this._isBlendEquationParametersDirty = false;
  9553. this._isBlendConstantsDirty = false;
  9554. };
  9555. _AlphaState.prototype.apply = function (gl) {
  9556. if (!this.isDirty) {
  9557. return;
  9558. }
  9559. // Alpha blend
  9560. if (this._isAlphaBlendDirty) {
  9561. if (this._alphaBlend) {
  9562. gl.enable(gl.BLEND);
  9563. }
  9564. else {
  9565. gl.disable(gl.BLEND);
  9566. }
  9567. this._isAlphaBlendDirty = false;
  9568. }
  9569. // Alpha function
  9570. if (this._isBlendFunctionParametersDirty) {
  9571. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9572. this._isBlendFunctionParametersDirty = false;
  9573. }
  9574. // Alpha equation
  9575. if (this._isBlendEquationParametersDirty) {
  9576. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9577. this._isBlendEquationParametersDirty = false;
  9578. }
  9579. // Constants
  9580. if (this._isBlendConstantsDirty) {
  9581. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9582. this._isBlendConstantsDirty = false;
  9583. }
  9584. };
  9585. return _AlphaState;
  9586. }());
  9587. BABYLON._AlphaState = _AlphaState;
  9588. })(BABYLON || (BABYLON = {}));
  9589. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9590. var BABYLON;
  9591. (function (BABYLON) {
  9592. var _DepthCullingState = /** @class */ (function () {
  9593. /**
  9594. * Initializes the state.
  9595. */
  9596. function _DepthCullingState() {
  9597. this._isDepthTestDirty = false;
  9598. this._isDepthMaskDirty = false;
  9599. this._isDepthFuncDirty = false;
  9600. this._isCullFaceDirty = false;
  9601. this._isCullDirty = false;
  9602. this._isZOffsetDirty = false;
  9603. this._isFrontFaceDirty = false;
  9604. this.reset();
  9605. }
  9606. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9607. get: function () {
  9608. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9609. },
  9610. enumerable: true,
  9611. configurable: true
  9612. });
  9613. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9614. get: function () {
  9615. return this._zOffset;
  9616. },
  9617. set: function (value) {
  9618. if (this._zOffset === value) {
  9619. return;
  9620. }
  9621. this._zOffset = value;
  9622. this._isZOffsetDirty = true;
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9628. get: function () {
  9629. return this._cullFace;
  9630. },
  9631. set: function (value) {
  9632. if (this._cullFace === value) {
  9633. return;
  9634. }
  9635. this._cullFace = value;
  9636. this._isCullFaceDirty = true;
  9637. },
  9638. enumerable: true,
  9639. configurable: true
  9640. });
  9641. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9642. get: function () {
  9643. return this._cull;
  9644. },
  9645. set: function (value) {
  9646. if (this._cull === value) {
  9647. return;
  9648. }
  9649. this._cull = value;
  9650. this._isCullDirty = true;
  9651. },
  9652. enumerable: true,
  9653. configurable: true
  9654. });
  9655. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9656. get: function () {
  9657. return this._depthFunc;
  9658. },
  9659. set: function (value) {
  9660. if (this._depthFunc === value) {
  9661. return;
  9662. }
  9663. this._depthFunc = value;
  9664. this._isDepthFuncDirty = true;
  9665. },
  9666. enumerable: true,
  9667. configurable: true
  9668. });
  9669. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9670. get: function () {
  9671. return this._depthMask;
  9672. },
  9673. set: function (value) {
  9674. if (this._depthMask === value) {
  9675. return;
  9676. }
  9677. this._depthMask = value;
  9678. this._isDepthMaskDirty = true;
  9679. },
  9680. enumerable: true,
  9681. configurable: true
  9682. });
  9683. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9684. get: function () {
  9685. return this._depthTest;
  9686. },
  9687. set: function (value) {
  9688. if (this._depthTest === value) {
  9689. return;
  9690. }
  9691. this._depthTest = value;
  9692. this._isDepthTestDirty = true;
  9693. },
  9694. enumerable: true,
  9695. configurable: true
  9696. });
  9697. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9698. get: function () {
  9699. return this._frontFace;
  9700. },
  9701. set: function (value) {
  9702. if (this._frontFace === value) {
  9703. return;
  9704. }
  9705. this._frontFace = value;
  9706. this._isFrontFaceDirty = true;
  9707. },
  9708. enumerable: true,
  9709. configurable: true
  9710. });
  9711. _DepthCullingState.prototype.reset = function () {
  9712. this._depthMask = true;
  9713. this._depthTest = true;
  9714. this._depthFunc = null;
  9715. this._cullFace = null;
  9716. this._cull = null;
  9717. this._zOffset = 0;
  9718. this._frontFace = null;
  9719. this._isDepthTestDirty = true;
  9720. this._isDepthMaskDirty = true;
  9721. this._isDepthFuncDirty = false;
  9722. this._isCullFaceDirty = false;
  9723. this._isCullDirty = false;
  9724. this._isZOffsetDirty = false;
  9725. this._isFrontFaceDirty = false;
  9726. };
  9727. _DepthCullingState.prototype.apply = function (gl) {
  9728. if (!this.isDirty) {
  9729. return;
  9730. }
  9731. // Cull
  9732. if (this._isCullDirty) {
  9733. if (this.cull) {
  9734. gl.enable(gl.CULL_FACE);
  9735. }
  9736. else {
  9737. gl.disable(gl.CULL_FACE);
  9738. }
  9739. this._isCullDirty = false;
  9740. }
  9741. // Cull face
  9742. if (this._isCullFaceDirty) {
  9743. gl.cullFace(this.cullFace);
  9744. this._isCullFaceDirty = false;
  9745. }
  9746. // Depth mask
  9747. if (this._isDepthMaskDirty) {
  9748. gl.depthMask(this.depthMask);
  9749. this._isDepthMaskDirty = false;
  9750. }
  9751. // Depth test
  9752. if (this._isDepthTestDirty) {
  9753. if (this.depthTest) {
  9754. gl.enable(gl.DEPTH_TEST);
  9755. }
  9756. else {
  9757. gl.disable(gl.DEPTH_TEST);
  9758. }
  9759. this._isDepthTestDirty = false;
  9760. }
  9761. // Depth func
  9762. if (this._isDepthFuncDirty) {
  9763. gl.depthFunc(this.depthFunc);
  9764. this._isDepthFuncDirty = false;
  9765. }
  9766. // zOffset
  9767. if (this._isZOffsetDirty) {
  9768. if (this.zOffset) {
  9769. gl.enable(gl.POLYGON_OFFSET_FILL);
  9770. gl.polygonOffset(this.zOffset, 0);
  9771. }
  9772. else {
  9773. gl.disable(gl.POLYGON_OFFSET_FILL);
  9774. }
  9775. this._isZOffsetDirty = false;
  9776. }
  9777. // Front face
  9778. if (this._isFrontFaceDirty) {
  9779. gl.frontFace(this.frontFace);
  9780. this._isFrontFaceDirty = false;
  9781. }
  9782. };
  9783. return _DepthCullingState;
  9784. }());
  9785. BABYLON._DepthCullingState = _DepthCullingState;
  9786. })(BABYLON || (BABYLON = {}));
  9787. //# sourceMappingURL=babylon.depthCullingState.js.map
  9788. var BABYLON;
  9789. (function (BABYLON) {
  9790. var _StencilState = /** @class */ (function () {
  9791. function _StencilState() {
  9792. this._isStencilTestDirty = false;
  9793. this._isStencilMaskDirty = false;
  9794. this._isStencilFuncDirty = false;
  9795. this._isStencilOpDirty = false;
  9796. this.reset();
  9797. }
  9798. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9799. get: function () {
  9800. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9806. get: function () {
  9807. return this._stencilFunc;
  9808. },
  9809. set: function (value) {
  9810. if (this._stencilFunc === value) {
  9811. return;
  9812. }
  9813. this._stencilFunc = value;
  9814. this._isStencilFuncDirty = true;
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9820. get: function () {
  9821. return this._stencilFuncRef;
  9822. },
  9823. set: function (value) {
  9824. if (this._stencilFuncRef === value) {
  9825. return;
  9826. }
  9827. this._stencilFuncRef = value;
  9828. this._isStencilFuncDirty = true;
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9834. get: function () {
  9835. return this._stencilFuncMask;
  9836. },
  9837. set: function (value) {
  9838. if (this._stencilFuncMask === value) {
  9839. return;
  9840. }
  9841. this._stencilFuncMask = value;
  9842. this._isStencilFuncDirty = true;
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9848. get: function () {
  9849. return this._stencilOpStencilFail;
  9850. },
  9851. set: function (value) {
  9852. if (this._stencilOpStencilFail === value) {
  9853. return;
  9854. }
  9855. this._stencilOpStencilFail = value;
  9856. this._isStencilOpDirty = true;
  9857. },
  9858. enumerable: true,
  9859. configurable: true
  9860. });
  9861. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9862. get: function () {
  9863. return this._stencilOpDepthFail;
  9864. },
  9865. set: function (value) {
  9866. if (this._stencilOpDepthFail === value) {
  9867. return;
  9868. }
  9869. this._stencilOpDepthFail = value;
  9870. this._isStencilOpDirty = true;
  9871. },
  9872. enumerable: true,
  9873. configurable: true
  9874. });
  9875. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9876. get: function () {
  9877. return this._stencilOpStencilDepthPass;
  9878. },
  9879. set: function (value) {
  9880. if (this._stencilOpStencilDepthPass === value) {
  9881. return;
  9882. }
  9883. this._stencilOpStencilDepthPass = value;
  9884. this._isStencilOpDirty = true;
  9885. },
  9886. enumerable: true,
  9887. configurable: true
  9888. });
  9889. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9890. get: function () {
  9891. return this._stencilMask;
  9892. },
  9893. set: function (value) {
  9894. if (this._stencilMask === value) {
  9895. return;
  9896. }
  9897. this._stencilMask = value;
  9898. this._isStencilMaskDirty = true;
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9904. get: function () {
  9905. return this._stencilTest;
  9906. },
  9907. set: function (value) {
  9908. if (this._stencilTest === value) {
  9909. return;
  9910. }
  9911. this._stencilTest = value;
  9912. this._isStencilTestDirty = true;
  9913. },
  9914. enumerable: true,
  9915. configurable: true
  9916. });
  9917. _StencilState.prototype.reset = function () {
  9918. this._stencilTest = false;
  9919. this._stencilMask = 0xFF;
  9920. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9921. this._stencilFuncRef = 1;
  9922. this._stencilFuncMask = 0xFF;
  9923. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9924. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9925. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9926. this._isStencilTestDirty = true;
  9927. this._isStencilMaskDirty = true;
  9928. this._isStencilFuncDirty = true;
  9929. this._isStencilOpDirty = true;
  9930. };
  9931. _StencilState.prototype.apply = function (gl) {
  9932. if (!this.isDirty) {
  9933. return;
  9934. }
  9935. // Stencil test
  9936. if (this._isStencilTestDirty) {
  9937. if (this.stencilTest) {
  9938. gl.enable(gl.STENCIL_TEST);
  9939. }
  9940. else {
  9941. gl.disable(gl.STENCIL_TEST);
  9942. }
  9943. this._isStencilTestDirty = false;
  9944. }
  9945. // Stencil mask
  9946. if (this._isStencilMaskDirty) {
  9947. gl.stencilMask(this.stencilMask);
  9948. this._isStencilMaskDirty = false;
  9949. }
  9950. // Stencil func
  9951. if (this._isStencilFuncDirty) {
  9952. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9953. this._isStencilFuncDirty = false;
  9954. }
  9955. // Stencil op
  9956. if (this._isStencilOpDirty) {
  9957. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9958. this._isStencilOpDirty = false;
  9959. }
  9960. };
  9961. return _StencilState;
  9962. }());
  9963. BABYLON._StencilState = _StencilState;
  9964. })(BABYLON || (BABYLON = {}));
  9965. //# sourceMappingURL=babylon.stencilState.js.map
  9966. var BABYLON;
  9967. (function (BABYLON) {
  9968. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9969. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9970. };
  9971. var compileRawShader = function (gl, source, type) {
  9972. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9973. gl.shaderSource(shader, source);
  9974. gl.compileShader(shader);
  9975. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9976. var log = gl.getShaderInfoLog(shader);
  9977. if (log) {
  9978. throw new Error(log);
  9979. }
  9980. }
  9981. if (!shader) {
  9982. throw new Error("Something went wrong while compile the shader.");
  9983. }
  9984. return shader;
  9985. };
  9986. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9987. var magFilter = gl.NEAREST;
  9988. var minFilter = gl.NEAREST;
  9989. switch (samplingMode) {
  9990. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9991. magFilter = gl.LINEAR;
  9992. if (generateMipMaps) {
  9993. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9994. }
  9995. else {
  9996. minFilter = gl.LINEAR;
  9997. }
  9998. break;
  9999. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10000. magFilter = gl.LINEAR;
  10001. if (generateMipMaps) {
  10002. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10003. }
  10004. else {
  10005. minFilter = gl.LINEAR;
  10006. }
  10007. break;
  10008. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10009. magFilter = gl.NEAREST;
  10010. if (generateMipMaps) {
  10011. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10012. }
  10013. else {
  10014. minFilter = gl.NEAREST;
  10015. }
  10016. break;
  10017. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10018. magFilter = gl.NEAREST;
  10019. if (generateMipMaps) {
  10020. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10021. }
  10022. else {
  10023. minFilter = gl.NEAREST;
  10024. }
  10025. break;
  10026. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10027. magFilter = gl.NEAREST;
  10028. if (generateMipMaps) {
  10029. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10030. }
  10031. else {
  10032. minFilter = gl.LINEAR;
  10033. }
  10034. break;
  10035. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10036. magFilter = gl.NEAREST;
  10037. if (generateMipMaps) {
  10038. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10039. }
  10040. else {
  10041. minFilter = gl.LINEAR;
  10042. }
  10043. break;
  10044. case BABYLON.Texture.NEAREST_LINEAR:
  10045. magFilter = gl.NEAREST;
  10046. minFilter = gl.LINEAR;
  10047. break;
  10048. case BABYLON.Texture.NEAREST_NEAREST:
  10049. magFilter = gl.NEAREST;
  10050. minFilter = gl.NEAREST;
  10051. break;
  10052. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10053. magFilter = gl.LINEAR;
  10054. if (generateMipMaps) {
  10055. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10056. }
  10057. else {
  10058. minFilter = gl.NEAREST;
  10059. }
  10060. break;
  10061. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10062. magFilter = gl.LINEAR;
  10063. if (generateMipMaps) {
  10064. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10065. }
  10066. else {
  10067. minFilter = gl.NEAREST;
  10068. }
  10069. break;
  10070. case BABYLON.Texture.LINEAR_LINEAR:
  10071. magFilter = gl.LINEAR;
  10072. minFilter = gl.LINEAR;
  10073. break;
  10074. case BABYLON.Texture.LINEAR_NEAREST:
  10075. magFilter = gl.LINEAR;
  10076. minFilter = gl.NEAREST;
  10077. break;
  10078. }
  10079. return {
  10080. min: minFilter,
  10081. mag: magFilter
  10082. };
  10083. };
  10084. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10085. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10086. var img;
  10087. var onload = function () {
  10088. loadedImages[index] = img;
  10089. loadedImages._internalCount++;
  10090. if (scene) {
  10091. scene._removePendingData(img);
  10092. }
  10093. if (loadedImages._internalCount === 6) {
  10094. onfinish(loadedImages);
  10095. }
  10096. };
  10097. var onerror = function (message, exception) {
  10098. if (scene) {
  10099. scene._removePendingData(img);
  10100. }
  10101. if (onErrorCallBack) {
  10102. onErrorCallBack(message, exception);
  10103. }
  10104. };
  10105. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10106. if (scene) {
  10107. scene._addPendingData(img);
  10108. }
  10109. };
  10110. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10111. if (onError === void 0) { onError = null; }
  10112. var loadedImages = [];
  10113. loadedImages._internalCount = 0;
  10114. for (var index = 0; index < 6; index++) {
  10115. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10116. }
  10117. };
  10118. var BufferPointer = /** @class */ (function () {
  10119. function BufferPointer() {
  10120. }
  10121. return BufferPointer;
  10122. }());
  10123. var InstancingAttributeInfo = /** @class */ (function () {
  10124. function InstancingAttributeInfo() {
  10125. }
  10126. return InstancingAttributeInfo;
  10127. }());
  10128. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10129. /**
  10130. * Define options used to create a render target texture
  10131. */
  10132. var RenderTargetCreationOptions = /** @class */ (function () {
  10133. function RenderTargetCreationOptions() {
  10134. }
  10135. return RenderTargetCreationOptions;
  10136. }());
  10137. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10138. /**
  10139. * Regroup several parameters relative to the browser in use
  10140. */
  10141. var EngineCapabilities = /** @class */ (function () {
  10142. function EngineCapabilities() {
  10143. }
  10144. return EngineCapabilities;
  10145. }());
  10146. BABYLON.EngineCapabilities = EngineCapabilities;
  10147. /**
  10148. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10149. */
  10150. var Engine = /** @class */ (function () {
  10151. /**
  10152. * @constructor
  10153. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10154. * @param antialias defines enable antialiasing (default: false)
  10155. * @param options defines further options to be sent to the getContext() function
  10156. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10157. */
  10158. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10159. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10160. var _this = this;
  10161. // Public members
  10162. this.forcePOTTextures = false;
  10163. this.isFullscreen = false;
  10164. this.isPointerLock = false;
  10165. this.cullBackFaces = true;
  10166. this.renderEvenInBackground = true;
  10167. this.preventCacheWipeBetweenFrames = false;
  10168. // To enable/disable IDB support and avoid XHR on .manifest
  10169. this.enableOfflineSupport = false;
  10170. this.scenes = new Array();
  10171. this.postProcesses = new Array();
  10172. // Observables
  10173. /**
  10174. * Observable event triggered each time the rendering canvas is resized
  10175. */
  10176. this.onResizeObservable = new BABYLON.Observable();
  10177. /**
  10178. * Observable event triggered each time the canvas loses focus
  10179. */
  10180. this.onCanvasBlurObservable = new BABYLON.Observable();
  10181. /**
  10182. * Observable event triggered each time the canvas gains focus
  10183. */
  10184. this.onCanvasFocusObservable = new BABYLON.Observable();
  10185. /**
  10186. * Observable event triggered each time the canvas receives pointerout event
  10187. */
  10188. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10189. /**
  10190. * Observable event triggered before each texture is initialized
  10191. */
  10192. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10193. //WebVR
  10194. this._vrDisplay = undefined;
  10195. this._vrSupported = false;
  10196. this._vrExclusivePointerMode = false;
  10197. // Uniform buffers list
  10198. this.disableUniformBuffers = false;
  10199. this._uniformBuffers = new Array();
  10200. // Observables
  10201. /**
  10202. * Observable raised when the engine begins a new frame
  10203. */
  10204. this.onBeginFrameObservable = new BABYLON.Observable();
  10205. /**
  10206. * Observable raised when the engine ends the current frame
  10207. */
  10208. this.onEndFrameObservable = new BABYLON.Observable();
  10209. /**
  10210. * Observable raised when the engine is about to compile a shader
  10211. */
  10212. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10213. /**
  10214. * Observable raised when the engine has jsut compiled a shader
  10215. */
  10216. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10217. this._windowIsBackground = false;
  10218. this._webGLVersion = 1.0;
  10219. this._badOS = false;
  10220. this._badDesktopOS = false;
  10221. /**
  10222. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10223. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10224. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10225. */
  10226. this.disableTextureBindingOptimization = false;
  10227. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10228. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10229. this.onVRRequestPresentStart = new BABYLON.Observable();
  10230. this._colorWrite = true;
  10231. this._drawCalls = new BABYLON.PerfCounter();
  10232. this._textureCollisions = new BABYLON.PerfCounter();
  10233. this._renderingQueueLaunched = false;
  10234. this._activeRenderLoops = new Array();
  10235. // Deterministic lockstepMaxSteps
  10236. this._deterministicLockstep = false;
  10237. this._lockstepMaxSteps = 4;
  10238. // Lost context
  10239. this.onContextLostObservable = new BABYLON.Observable();
  10240. this.onContextRestoredObservable = new BABYLON.Observable();
  10241. this._contextWasLost = false;
  10242. this._doNotHandleContextLost = false;
  10243. // FPS
  10244. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10245. this._fps = 60;
  10246. this._deltaTime = 0;
  10247. /**
  10248. * Turn this value on if you want to pause FPS computation when in background
  10249. */
  10250. this.disablePerformanceMonitorInBackground = false;
  10251. // States
  10252. this._depthCullingState = new BABYLON._DepthCullingState();
  10253. this._stencilState = new BABYLON._StencilState();
  10254. this._alphaState = new BABYLON._AlphaState();
  10255. this._alphaMode = Engine.ALPHA_DISABLE;
  10256. // Cache
  10257. this._internalTexturesCache = new Array();
  10258. this._activeChannel = 0;
  10259. this._currentTextureChannel = -1;
  10260. this._boundTexturesCache = {};
  10261. this._compiledEffects = {};
  10262. this._vertexAttribArraysEnabled = [];
  10263. this._uintIndicesCurrentlySet = false;
  10264. this._currentBoundBuffer = new Array();
  10265. this._currentBufferPointers = new Array();
  10266. this._currentInstanceLocations = new Array();
  10267. this._currentInstanceBuffers = new Array();
  10268. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10269. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10270. this._vaoRecordInProgress = false;
  10271. this._mustWipeVertexAttributes = false;
  10272. this._nextFreeTextureSlots = new Array();
  10273. this._maxSimultaneousTextures = 0;
  10274. this._activeRequests = new Array();
  10275. // Hardware supported Compressed Textures
  10276. this._texturesSupported = new Array();
  10277. this._onVRFullScreenTriggered = function () {
  10278. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10279. //get the old size before we change
  10280. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10281. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10282. //get the width and height, change the render size
  10283. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10284. _this.setHardwareScalingLevel(1);
  10285. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10286. }
  10287. else {
  10288. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10289. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10290. }
  10291. };
  10292. this._boundUniforms = {};
  10293. // Register promises
  10294. BABYLON.PromisePolyfill.Apply();
  10295. var canvas = null;
  10296. Engine.Instances.push(this);
  10297. if (!canvasOrContext) {
  10298. return;
  10299. }
  10300. options = options || {};
  10301. if (canvasOrContext.getContext) {
  10302. canvas = canvasOrContext;
  10303. this._renderingCanvas = canvas;
  10304. if (antialias != null) {
  10305. options.antialias = antialias;
  10306. }
  10307. if (options.deterministicLockstep === undefined) {
  10308. options.deterministicLockstep = false;
  10309. }
  10310. if (options.lockstepMaxSteps === undefined) {
  10311. options.lockstepMaxSteps = 4;
  10312. }
  10313. if (options.preserveDrawingBuffer === undefined) {
  10314. options.preserveDrawingBuffer = false;
  10315. }
  10316. if (options.audioEngine === undefined) {
  10317. options.audioEngine = true;
  10318. }
  10319. if (options.stencil === undefined) {
  10320. options.stencil = true;
  10321. }
  10322. this._deterministicLockstep = options.deterministicLockstep;
  10323. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10324. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10325. // Exceptions
  10326. if (navigator && navigator.userAgent) {
  10327. var ua = navigator.userAgent;
  10328. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10329. var exception = _a[_i];
  10330. var key = exception.key;
  10331. var targets = exception.targets;
  10332. if (ua.indexOf(key) > -1) {
  10333. if (exception.capture && exception.captureConstraint) {
  10334. var capture = exception.capture;
  10335. var constraint = exception.captureConstraint;
  10336. var regex = new RegExp(capture);
  10337. var matches = regex.exec(ua);
  10338. if (matches && matches.length > 0) {
  10339. var capturedValue = parseInt(matches[matches.length - 1]);
  10340. if (capturedValue >= constraint) {
  10341. continue;
  10342. }
  10343. }
  10344. }
  10345. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10346. var target = targets_1[_b];
  10347. switch (target) {
  10348. case "uniformBuffer":
  10349. this.disableUniformBuffers = true;
  10350. break;
  10351. case "textureBindingOptimization":
  10352. this.disableTextureBindingOptimization = true;
  10353. break;
  10354. }
  10355. }
  10356. break;
  10357. }
  10358. }
  10359. }
  10360. // GL
  10361. if (!options.disableWebGL2Support) {
  10362. try {
  10363. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10364. if (this._gl) {
  10365. this._webGLVersion = 2.0;
  10366. }
  10367. }
  10368. catch (e) {
  10369. // Do nothing
  10370. }
  10371. }
  10372. if (!this._gl) {
  10373. if (!canvas) {
  10374. throw new Error("The provided canvas is null or undefined.");
  10375. }
  10376. try {
  10377. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10378. }
  10379. catch (e) {
  10380. throw new Error("WebGL not supported");
  10381. }
  10382. }
  10383. if (!this._gl) {
  10384. throw new Error("WebGL not supported");
  10385. }
  10386. this._onCanvasFocus = function () {
  10387. _this.onCanvasFocusObservable.notifyObservers(_this);
  10388. };
  10389. this._onCanvasBlur = function () {
  10390. _this.onCanvasBlurObservable.notifyObservers(_this);
  10391. };
  10392. canvas.addEventListener("focus", this._onCanvasFocus);
  10393. canvas.addEventListener("blur", this._onCanvasBlur);
  10394. this._onBlur = function () {
  10395. if (_this.disablePerformanceMonitorInBackground) {
  10396. _this._performanceMonitor.disable();
  10397. }
  10398. _this._windowIsBackground = true;
  10399. };
  10400. this._onFocus = function () {
  10401. if (_this.disablePerformanceMonitorInBackground) {
  10402. _this._performanceMonitor.enable();
  10403. }
  10404. _this._windowIsBackground = false;
  10405. };
  10406. this._onCanvasPointerOut = function () {
  10407. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10408. };
  10409. window.addEventListener("blur", this._onBlur);
  10410. window.addEventListener("focus", this._onFocus);
  10411. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10412. // Context lost
  10413. if (!this._doNotHandleContextLost) {
  10414. this._onContextLost = function (evt) {
  10415. evt.preventDefault();
  10416. _this._contextWasLost = true;
  10417. BABYLON.Tools.Warn("WebGL context lost.");
  10418. _this.onContextLostObservable.notifyObservers(_this);
  10419. };
  10420. this._onContextRestored = function (evt) {
  10421. // Adding a timeout to avoid race condition at browser level
  10422. setTimeout(function () {
  10423. // Rebuild gl context
  10424. _this._initGLContext();
  10425. // Rebuild effects
  10426. _this._rebuildEffects();
  10427. // Rebuild textures
  10428. _this._rebuildInternalTextures();
  10429. // Rebuild buffers
  10430. _this._rebuildBuffers();
  10431. // Cache
  10432. _this.wipeCaches(true);
  10433. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10434. _this.onContextRestoredObservable.notifyObservers(_this);
  10435. _this._contextWasLost = false;
  10436. }, 0);
  10437. };
  10438. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10439. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10440. }
  10441. }
  10442. else {
  10443. this._gl = canvasOrContext;
  10444. this._renderingCanvas = this._gl.canvas;
  10445. if (this._gl.renderbufferStorageMultisample) {
  10446. this._webGLVersion = 2.0;
  10447. }
  10448. options.stencil = this._gl.getContextAttributes().stencil;
  10449. }
  10450. // Viewport
  10451. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10452. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10453. this.resize();
  10454. this._isStencilEnable = options.stencil ? true : false;
  10455. this._initGLContext();
  10456. if (canvas) {
  10457. // Fullscreen
  10458. this._onFullscreenChange = function () {
  10459. if (document.fullscreen !== undefined) {
  10460. _this.isFullscreen = document.fullscreen;
  10461. }
  10462. else if (document.mozFullScreen !== undefined) {
  10463. _this.isFullscreen = document.mozFullScreen;
  10464. }
  10465. else if (document.webkitIsFullScreen !== undefined) {
  10466. _this.isFullscreen = document.webkitIsFullScreen;
  10467. }
  10468. else if (document.msIsFullScreen !== undefined) {
  10469. _this.isFullscreen = document.msIsFullScreen;
  10470. }
  10471. // Pointer lock
  10472. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10473. canvas.requestPointerLock = canvas.requestPointerLock ||
  10474. canvas.msRequestPointerLock ||
  10475. canvas.mozRequestPointerLock ||
  10476. canvas.webkitRequestPointerLock;
  10477. if (canvas.requestPointerLock) {
  10478. canvas.requestPointerLock();
  10479. }
  10480. }
  10481. };
  10482. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10483. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10484. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10485. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10486. // Pointer lock
  10487. this._onPointerLockChange = function () {
  10488. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10489. document.webkitPointerLockElement === canvas ||
  10490. document.msPointerLockElement === canvas ||
  10491. document.pointerLockElement === canvas);
  10492. };
  10493. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10494. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10495. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10496. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10497. this._onVRDisplayPointerRestricted = function () {
  10498. if (canvas) {
  10499. canvas.requestPointerLock();
  10500. }
  10501. };
  10502. this._onVRDisplayPointerUnrestricted = function () {
  10503. document.exitPointerLock();
  10504. };
  10505. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10506. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10507. }
  10508. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10509. Engine.audioEngine = new BABYLON.AudioEngine();
  10510. }
  10511. // Prepare buffer pointers
  10512. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10513. this._currentBufferPointers[i] = new BufferPointer();
  10514. }
  10515. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10516. // Load WebVR Devices
  10517. if (options.autoEnableWebVR) {
  10518. this.initWebVR();
  10519. }
  10520. // Detect if we are running on a faulty buggy OS.
  10521. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10522. // Detect if we are running on a faulty buggy desktop OS.
  10523. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10524. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10525. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10526. }
  10527. Object.defineProperty(Engine, "LastCreatedEngine", {
  10528. get: function () {
  10529. if (Engine.Instances.length === 0) {
  10530. return null;
  10531. }
  10532. return Engine.Instances[Engine.Instances.length - 1];
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. Object.defineProperty(Engine, "LastCreatedScene", {
  10538. get: function () {
  10539. var lastCreatedEngine = Engine.LastCreatedEngine;
  10540. if (!lastCreatedEngine) {
  10541. return null;
  10542. }
  10543. if (lastCreatedEngine.scenes.length === 0) {
  10544. return null;
  10545. }
  10546. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10547. },
  10548. enumerable: true,
  10549. configurable: true
  10550. });
  10551. /**
  10552. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10553. */
  10554. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10555. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10556. var engine = Engine.Instances[engineIndex];
  10557. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10558. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10559. }
  10560. }
  10561. };
  10562. Object.defineProperty(Engine, "NEVER", {
  10563. get: function () {
  10564. return Engine._NEVER;
  10565. },
  10566. enumerable: true,
  10567. configurable: true
  10568. });
  10569. Object.defineProperty(Engine, "ALWAYS", {
  10570. get: function () {
  10571. return Engine._ALWAYS;
  10572. },
  10573. enumerable: true,
  10574. configurable: true
  10575. });
  10576. Object.defineProperty(Engine, "LESS", {
  10577. get: function () {
  10578. return Engine._LESS;
  10579. },
  10580. enumerable: true,
  10581. configurable: true
  10582. });
  10583. Object.defineProperty(Engine, "EQUAL", {
  10584. get: function () {
  10585. return Engine._EQUAL;
  10586. },
  10587. enumerable: true,
  10588. configurable: true
  10589. });
  10590. Object.defineProperty(Engine, "LEQUAL", {
  10591. get: function () {
  10592. return Engine._LEQUAL;
  10593. },
  10594. enumerable: true,
  10595. configurable: true
  10596. });
  10597. Object.defineProperty(Engine, "GREATER", {
  10598. get: function () {
  10599. return Engine._GREATER;
  10600. },
  10601. enumerable: true,
  10602. configurable: true
  10603. });
  10604. Object.defineProperty(Engine, "GEQUAL", {
  10605. get: function () {
  10606. return Engine._GEQUAL;
  10607. },
  10608. enumerable: true,
  10609. configurable: true
  10610. });
  10611. Object.defineProperty(Engine, "NOTEQUAL", {
  10612. get: function () {
  10613. return Engine._NOTEQUAL;
  10614. },
  10615. enumerable: true,
  10616. configurable: true
  10617. });
  10618. Object.defineProperty(Engine, "KEEP", {
  10619. get: function () {
  10620. return Engine._KEEP;
  10621. },
  10622. enumerable: true,
  10623. configurable: true
  10624. });
  10625. Object.defineProperty(Engine, "REPLACE", {
  10626. get: function () {
  10627. return Engine._REPLACE;
  10628. },
  10629. enumerable: true,
  10630. configurable: true
  10631. });
  10632. Object.defineProperty(Engine, "INCR", {
  10633. get: function () {
  10634. return Engine._INCR;
  10635. },
  10636. enumerable: true,
  10637. configurable: true
  10638. });
  10639. Object.defineProperty(Engine, "DECR", {
  10640. get: function () {
  10641. return Engine._DECR;
  10642. },
  10643. enumerable: true,
  10644. configurable: true
  10645. });
  10646. Object.defineProperty(Engine, "INVERT", {
  10647. get: function () {
  10648. return Engine._INVERT;
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. Object.defineProperty(Engine, "INCR_WRAP", {
  10654. get: function () {
  10655. return Engine._INCR_WRAP;
  10656. },
  10657. enumerable: true,
  10658. configurable: true
  10659. });
  10660. Object.defineProperty(Engine, "DECR_WRAP", {
  10661. get: function () {
  10662. return Engine._DECR_WRAP;
  10663. },
  10664. enumerable: true,
  10665. configurable: true
  10666. });
  10667. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10668. get: function () {
  10669. return Engine._ALPHA_DISABLE;
  10670. },
  10671. enumerable: true,
  10672. configurable: true
  10673. });
  10674. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10675. get: function () {
  10676. return Engine._ALPHA_ONEONE;
  10677. },
  10678. enumerable: true,
  10679. configurable: true
  10680. });
  10681. Object.defineProperty(Engine, "ALPHA_ADD", {
  10682. get: function () {
  10683. return Engine._ALPHA_ADD;
  10684. },
  10685. enumerable: true,
  10686. configurable: true
  10687. });
  10688. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10689. get: function () {
  10690. return Engine._ALPHA_COMBINE;
  10691. },
  10692. enumerable: true,
  10693. configurable: true
  10694. });
  10695. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10696. get: function () {
  10697. return Engine._ALPHA_SUBTRACT;
  10698. },
  10699. enumerable: true,
  10700. configurable: true
  10701. });
  10702. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10703. get: function () {
  10704. return Engine._ALPHA_MULTIPLY;
  10705. },
  10706. enumerable: true,
  10707. configurable: true
  10708. });
  10709. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10710. get: function () {
  10711. return Engine._ALPHA_MAXIMIZED;
  10712. },
  10713. enumerable: true,
  10714. configurable: true
  10715. });
  10716. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10717. get: function () {
  10718. return Engine._ALPHA_PREMULTIPLIED;
  10719. },
  10720. enumerable: true,
  10721. configurable: true
  10722. });
  10723. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10724. get: function () {
  10725. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10726. },
  10727. enumerable: true,
  10728. configurable: true
  10729. });
  10730. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10731. get: function () {
  10732. return Engine._ALPHA_INTERPOLATE;
  10733. },
  10734. enumerable: true,
  10735. configurable: true
  10736. });
  10737. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10738. get: function () {
  10739. return Engine._ALPHA_SCREENMODE;
  10740. },
  10741. enumerable: true,
  10742. configurable: true
  10743. });
  10744. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10745. get: function () {
  10746. return Engine._DELAYLOADSTATE_NONE;
  10747. },
  10748. enumerable: true,
  10749. configurable: true
  10750. });
  10751. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10752. get: function () {
  10753. return Engine._DELAYLOADSTATE_LOADED;
  10754. },
  10755. enumerable: true,
  10756. configurable: true
  10757. });
  10758. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10759. get: function () {
  10760. return Engine._DELAYLOADSTATE_LOADING;
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10766. get: function () {
  10767. return Engine._DELAYLOADSTATE_NOTLOADED;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10773. get: function () {
  10774. return Engine._TEXTUREFORMAT_ALPHA;
  10775. },
  10776. enumerable: true,
  10777. configurable: true
  10778. });
  10779. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10780. get: function () {
  10781. return Engine._TEXTUREFORMAT_LUMINANCE;
  10782. },
  10783. enumerable: true,
  10784. configurable: true
  10785. });
  10786. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10787. get: function () {
  10788. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10794. get: function () {
  10795. return Engine._TEXTUREFORMAT_RGB;
  10796. },
  10797. enumerable: true,
  10798. configurable: true
  10799. });
  10800. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10801. get: function () {
  10802. return Engine._TEXTUREFORMAT_RGBA;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10808. get: function () {
  10809. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10810. },
  10811. enumerable: true,
  10812. configurable: true
  10813. });
  10814. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10815. get: function () {
  10816. return Engine._TEXTURETYPE_FLOAT;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10822. get: function () {
  10823. return Engine._TEXTURETYPE_HALF_FLOAT;
  10824. },
  10825. enumerable: true,
  10826. configurable: true
  10827. });
  10828. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10829. get: function () {
  10830. return Engine._SCALEMODE_FLOOR;
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10836. get: function () {
  10837. return Engine._SCALEMODE_NEAREST;
  10838. },
  10839. enumerable: true,
  10840. configurable: true
  10841. });
  10842. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10843. get: function () {
  10844. return Engine._SCALEMODE_CEILING;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(Engine, "Version", {
  10850. get: function () {
  10851. return "3.2.0-alpha7";
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10857. get: function () {
  10858. return this._vrExclusivePointerMode;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10864. get: function () {
  10865. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10871. get: function () {
  10872. return this._webGLVersion < 2 || this.forcePOTTextures;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Engine.prototype, "badOS", {
  10878. get: function () {
  10879. return this._badOS;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10885. get: function () {
  10886. return this._badDesktopOS;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10892. get: function () {
  10893. return this._performanceMonitor;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10899. get: function () {
  10900. return this._texturesSupported;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10906. get: function () {
  10907. return this._textureFormatInUse;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine.prototype, "currentViewport", {
  10913. get: function () {
  10914. return this._cachedViewport;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10920. // Empty texture
  10921. get: function () {
  10922. if (!this._emptyTexture) {
  10923. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10924. }
  10925. return this._emptyTexture;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10931. get: function () {
  10932. if (!this._emptyTexture3D) {
  10933. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10934. }
  10935. return this._emptyTexture3D;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10941. get: function () {
  10942. if (!this._emptyCubeTexture) {
  10943. var faceData = new Uint8Array(4);
  10944. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10945. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10946. }
  10947. return this._emptyCubeTexture;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Engine.prototype._rebuildInternalTextures = function () {
  10953. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10954. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10955. var internalTexture = currentState_1[_i];
  10956. internalTexture._rebuild();
  10957. }
  10958. };
  10959. Engine.prototype._rebuildEffects = function () {
  10960. for (var key in this._compiledEffects) {
  10961. var effect = this._compiledEffects[key];
  10962. effect._prepareEffect();
  10963. }
  10964. BABYLON.Effect.ResetCache();
  10965. };
  10966. Engine.prototype._rebuildBuffers = function () {
  10967. // Index / Vertex
  10968. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10969. var scene = _a[_i];
  10970. scene.resetCachedMaterial();
  10971. scene._rebuildGeometries();
  10972. scene._rebuildTextures();
  10973. }
  10974. // Uniforms
  10975. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10976. var uniformBuffer = _c[_b];
  10977. uniformBuffer._rebuild();
  10978. }
  10979. };
  10980. Engine.prototype._initGLContext = function () {
  10981. // Caps
  10982. this._caps = new EngineCapabilities();
  10983. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10984. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10985. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10986. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10987. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10988. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10989. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10990. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10991. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10992. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10993. // Infos
  10994. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10995. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10996. if (rendererInfo != null) {
  10997. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10998. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10999. }
  11000. if (!this._glVendor) {
  11001. this._glVendor = "Unknown vendor";
  11002. }
  11003. if (!this._glRenderer) {
  11004. this._glRenderer = "Unknown renderer";
  11005. }
  11006. // Constants
  11007. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11008. if (this._gl.RGBA16F !== 0x881A) {
  11009. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11010. }
  11011. if (this._gl.RGBA32F !== 0x8814) {
  11012. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11013. }
  11014. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11015. this._gl.DEPTH24_STENCIL8 = 35056;
  11016. }
  11017. // Extensions
  11018. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11019. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11020. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11021. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11022. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11023. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11024. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11025. 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');
  11026. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11027. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11028. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11029. this._caps.highPrecisionShaderSupported = true;
  11030. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11031. if (this._caps.timerQuery) {
  11032. if (this._webGLVersion === 1) {
  11033. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11034. }
  11035. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11036. }
  11037. // Checks if some of the format renders first to allow the use of webgl inspector.
  11038. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11039. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11040. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11041. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11042. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11043. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11044. if (this._webGLVersion > 1) {
  11045. this._gl.HALF_FLOAT_OES = 0x140B;
  11046. }
  11047. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11048. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11049. // Draw buffers
  11050. if (this._webGLVersion > 1) {
  11051. this._caps.drawBuffersExtension = true;
  11052. }
  11053. else {
  11054. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11055. if (drawBuffersExtension !== null) {
  11056. this._caps.drawBuffersExtension = true;
  11057. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11058. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11059. for (var i = 0; i < 16; i++) {
  11060. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11061. }
  11062. }
  11063. else {
  11064. this._caps.drawBuffersExtension = false;
  11065. }
  11066. }
  11067. // Depth Texture
  11068. if (this._webGLVersion > 1) {
  11069. this._caps.depthTextureExtension = true;
  11070. }
  11071. else {
  11072. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11073. if (depthTextureExtension != null) {
  11074. this._caps.depthTextureExtension = true;
  11075. }
  11076. }
  11077. // Vertex array object
  11078. if (this._webGLVersion > 1) {
  11079. this._caps.vertexArrayObject = true;
  11080. }
  11081. else {
  11082. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11083. if (vertexArrayObjectExtension != null) {
  11084. this._caps.vertexArrayObject = true;
  11085. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11086. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11087. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11088. }
  11089. else {
  11090. this._caps.vertexArrayObject = false;
  11091. }
  11092. }
  11093. // Instances count
  11094. if (this._webGLVersion > 1) {
  11095. this._caps.instancedArrays = true;
  11096. }
  11097. else {
  11098. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11099. if (instanceExtension != null) {
  11100. this._caps.instancedArrays = true;
  11101. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11102. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11103. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11104. }
  11105. else {
  11106. this._caps.instancedArrays = false;
  11107. }
  11108. }
  11109. // Intelligently add supported compressed formats in order to check for.
  11110. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11111. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11112. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11113. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11114. if (this._caps.astc)
  11115. this.texturesSupported.push('-astc.ktx');
  11116. if (this._caps.s3tc)
  11117. this.texturesSupported.push('-dxt.ktx');
  11118. if (this._caps.pvrtc)
  11119. this.texturesSupported.push('-pvrtc.ktx');
  11120. if (this._caps.etc2)
  11121. this.texturesSupported.push('-etc2.ktx');
  11122. if (this._caps.etc1)
  11123. this.texturesSupported.push('-etc1.ktx');
  11124. if (this._gl.getShaderPrecisionFormat) {
  11125. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11126. if (highp) {
  11127. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11128. }
  11129. }
  11130. // Depth buffer
  11131. this.setDepthBuffer(true);
  11132. this.setDepthFunctionToLessOrEqual();
  11133. this.setDepthWrite(true);
  11134. // Texture maps
  11135. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11136. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11137. this._nextFreeTextureSlots.push(slot);
  11138. }
  11139. };
  11140. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11141. get: function () {
  11142. return this._webGLVersion;
  11143. },
  11144. enumerable: true,
  11145. configurable: true
  11146. });
  11147. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11148. /**
  11149. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11150. */
  11151. get: function () {
  11152. return this._isStencilEnable;
  11153. },
  11154. enumerable: true,
  11155. configurable: true
  11156. });
  11157. Engine.prototype._prepareWorkingCanvas = function () {
  11158. if (this._workingCanvas) {
  11159. return;
  11160. }
  11161. this._workingCanvas = document.createElement("canvas");
  11162. var context = this._workingCanvas.getContext("2d");
  11163. if (context) {
  11164. this._workingContext = context;
  11165. }
  11166. };
  11167. Engine.prototype.resetTextureCache = function () {
  11168. for (var key in this._boundTexturesCache) {
  11169. var boundTexture = this._boundTexturesCache[key];
  11170. if (boundTexture) {
  11171. this._removeDesignatedSlot(boundTexture);
  11172. }
  11173. this._boundTexturesCache[key] = null;
  11174. }
  11175. if (!this.disableTextureBindingOptimization) {
  11176. this._nextFreeTextureSlots = [];
  11177. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11178. this._nextFreeTextureSlots.push(slot);
  11179. }
  11180. }
  11181. this._currentTextureChannel = -1;
  11182. };
  11183. Engine.prototype.isDeterministicLockStep = function () {
  11184. return this._deterministicLockstep;
  11185. };
  11186. Engine.prototype.getLockstepMaxSteps = function () {
  11187. return this._lockstepMaxSteps;
  11188. };
  11189. Engine.prototype.getGlInfo = function () {
  11190. return {
  11191. vendor: this._glVendor,
  11192. renderer: this._glRenderer,
  11193. version: this._glVersion
  11194. };
  11195. };
  11196. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11197. if (useScreen === void 0) { useScreen = false; }
  11198. var viewport = camera.viewport;
  11199. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11200. };
  11201. Engine.prototype.getRenderWidth = function (useScreen) {
  11202. if (useScreen === void 0) { useScreen = false; }
  11203. if (!useScreen && this._currentRenderTarget) {
  11204. return this._currentRenderTarget.width;
  11205. }
  11206. return this._gl.drawingBufferWidth;
  11207. };
  11208. Engine.prototype.getRenderHeight = function (useScreen) {
  11209. if (useScreen === void 0) { useScreen = false; }
  11210. if (!useScreen && this._currentRenderTarget) {
  11211. return this._currentRenderTarget.height;
  11212. }
  11213. return this._gl.drawingBufferHeight;
  11214. };
  11215. Engine.prototype.getRenderingCanvas = function () {
  11216. return this._renderingCanvas;
  11217. };
  11218. Engine.prototype.getRenderingCanvasClientRect = function () {
  11219. if (!this._renderingCanvas) {
  11220. return null;
  11221. }
  11222. return this._renderingCanvas.getBoundingClientRect();
  11223. };
  11224. Engine.prototype.setHardwareScalingLevel = function (level) {
  11225. this._hardwareScalingLevel = level;
  11226. this.resize();
  11227. };
  11228. Engine.prototype.getHardwareScalingLevel = function () {
  11229. return this._hardwareScalingLevel;
  11230. };
  11231. Engine.prototype.getLoadedTexturesCache = function () {
  11232. return this._internalTexturesCache;
  11233. };
  11234. Engine.prototype.getCaps = function () {
  11235. return this._caps;
  11236. };
  11237. Object.defineProperty(Engine.prototype, "drawCalls", {
  11238. /** The number of draw calls submitted last frame */
  11239. get: function () {
  11240. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11241. return 0;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11247. get: function () {
  11248. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11249. return null;
  11250. },
  11251. enumerable: true,
  11252. configurable: true
  11253. });
  11254. Engine.prototype.getDepthFunction = function () {
  11255. return this._depthCullingState.depthFunc;
  11256. };
  11257. Engine.prototype.setDepthFunction = function (depthFunc) {
  11258. this._depthCullingState.depthFunc = depthFunc;
  11259. };
  11260. Engine.prototype.setDepthFunctionToGreater = function () {
  11261. this._depthCullingState.depthFunc = this._gl.GREATER;
  11262. };
  11263. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11264. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11265. };
  11266. Engine.prototype.setDepthFunctionToLess = function () {
  11267. this._depthCullingState.depthFunc = this._gl.LESS;
  11268. };
  11269. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11270. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11271. };
  11272. Engine.prototype.getStencilBuffer = function () {
  11273. return this._stencilState.stencilTest;
  11274. };
  11275. Engine.prototype.setStencilBuffer = function (enable) {
  11276. this._stencilState.stencilTest = enable;
  11277. };
  11278. Engine.prototype.getStencilMask = function () {
  11279. return this._stencilState.stencilMask;
  11280. };
  11281. Engine.prototype.setStencilMask = function (mask) {
  11282. this._stencilState.stencilMask = mask;
  11283. };
  11284. Engine.prototype.getStencilFunction = function () {
  11285. return this._stencilState.stencilFunc;
  11286. };
  11287. Engine.prototype.getStencilFunctionReference = function () {
  11288. return this._stencilState.stencilFuncRef;
  11289. };
  11290. Engine.prototype.getStencilFunctionMask = function () {
  11291. return this._stencilState.stencilFuncMask;
  11292. };
  11293. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11294. this._stencilState.stencilFunc = stencilFunc;
  11295. };
  11296. Engine.prototype.setStencilFunctionReference = function (reference) {
  11297. this._stencilState.stencilFuncRef = reference;
  11298. };
  11299. Engine.prototype.setStencilFunctionMask = function (mask) {
  11300. this._stencilState.stencilFuncMask = mask;
  11301. };
  11302. Engine.prototype.getStencilOperationFail = function () {
  11303. return this._stencilState.stencilOpStencilFail;
  11304. };
  11305. Engine.prototype.getStencilOperationDepthFail = function () {
  11306. return this._stencilState.stencilOpDepthFail;
  11307. };
  11308. Engine.prototype.getStencilOperationPass = function () {
  11309. return this._stencilState.stencilOpStencilDepthPass;
  11310. };
  11311. Engine.prototype.setStencilOperationFail = function (operation) {
  11312. this._stencilState.stencilOpStencilFail = operation;
  11313. };
  11314. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11315. this._stencilState.stencilOpDepthFail = operation;
  11316. };
  11317. Engine.prototype.setStencilOperationPass = function (operation) {
  11318. this._stencilState.stencilOpStencilDepthPass = operation;
  11319. };
  11320. Engine.prototype.setDitheringState = function (value) {
  11321. if (value) {
  11322. this._gl.enable(this._gl.DITHER);
  11323. }
  11324. else {
  11325. this._gl.disable(this._gl.DITHER);
  11326. }
  11327. };
  11328. Engine.prototype.setRasterizerState = function (value) {
  11329. if (value) {
  11330. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11331. }
  11332. else {
  11333. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11334. }
  11335. };
  11336. /**
  11337. * stop executing a render loop function and remove it from the execution array
  11338. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11339. */
  11340. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11341. if (!renderFunction) {
  11342. this._activeRenderLoops = [];
  11343. return;
  11344. }
  11345. var index = this._activeRenderLoops.indexOf(renderFunction);
  11346. if (index >= 0) {
  11347. this._activeRenderLoops.splice(index, 1);
  11348. }
  11349. };
  11350. Engine.prototype._renderLoop = function () {
  11351. if (!this._contextWasLost) {
  11352. var shouldRender = true;
  11353. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11354. shouldRender = false;
  11355. }
  11356. if (shouldRender) {
  11357. // Start new frame
  11358. this.beginFrame();
  11359. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11360. var renderFunction = this._activeRenderLoops[index];
  11361. renderFunction();
  11362. }
  11363. // Present
  11364. this.endFrame();
  11365. }
  11366. }
  11367. if (this._activeRenderLoops.length > 0) {
  11368. // Register new frame
  11369. var requester = null;
  11370. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11371. requester = this._vrDisplay;
  11372. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11373. }
  11374. else {
  11375. this._renderingQueueLaunched = false;
  11376. }
  11377. };
  11378. /**
  11379. * Register and execute a render loop. The engine can have more than one render function.
  11380. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11381. * @example
  11382. * engine.runRenderLoop(function () {
  11383. * scene.render()
  11384. * })
  11385. */
  11386. Engine.prototype.runRenderLoop = function (renderFunction) {
  11387. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11388. return;
  11389. }
  11390. this._activeRenderLoops.push(renderFunction);
  11391. if (!this._renderingQueueLaunched) {
  11392. this._renderingQueueLaunched = true;
  11393. this._bindedRenderFunction = this._renderLoop.bind(this);
  11394. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11395. }
  11396. };
  11397. /**
  11398. * Toggle full screen mode.
  11399. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11400. * @param {any} options - an options object to be sent to the requestFullscreen function
  11401. */
  11402. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11403. if (this.isFullscreen) {
  11404. BABYLON.Tools.ExitFullscreen();
  11405. }
  11406. else {
  11407. this._pointerLockRequested = requestPointerLock;
  11408. if (this._renderingCanvas) {
  11409. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11410. }
  11411. }
  11412. };
  11413. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11414. if (stencil === void 0) { stencil = false; }
  11415. this.applyStates();
  11416. var mode = 0;
  11417. if (backBuffer && color) {
  11418. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11419. mode |= this._gl.COLOR_BUFFER_BIT;
  11420. }
  11421. if (depth) {
  11422. this._gl.clearDepth(1.0);
  11423. mode |= this._gl.DEPTH_BUFFER_BIT;
  11424. }
  11425. if (stencil) {
  11426. this._gl.clearStencil(0);
  11427. mode |= this._gl.STENCIL_BUFFER_BIT;
  11428. }
  11429. this._gl.clear(mode);
  11430. };
  11431. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11432. var gl = this._gl;
  11433. // Save state
  11434. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11435. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11436. // Change state
  11437. gl.enable(gl.SCISSOR_TEST);
  11438. gl.scissor(x, y, width, height);
  11439. // Clear
  11440. this.clear(clearColor, true, true, true);
  11441. // Restore state
  11442. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11443. if (curScissor === true) {
  11444. gl.enable(gl.SCISSOR_TEST);
  11445. }
  11446. else {
  11447. gl.disable(gl.SCISSOR_TEST);
  11448. }
  11449. };
  11450. /**
  11451. * Set the WebGL's viewport
  11452. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11453. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11454. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11455. */
  11456. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11457. var width = requiredWidth || this.getRenderWidth();
  11458. var height = requiredHeight || this.getRenderHeight();
  11459. var x = viewport.x || 0;
  11460. var y = viewport.y || 0;
  11461. this._cachedViewport = viewport;
  11462. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11463. };
  11464. /**
  11465. * Directly set the WebGL Viewport
  11466. * The x, y, width & height are directly passed to the WebGL call
  11467. * @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.
  11468. */
  11469. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11470. var currentViewport = this._cachedViewport;
  11471. this._cachedViewport = null;
  11472. this._gl.viewport(x, y, width, height);
  11473. return currentViewport;
  11474. };
  11475. Engine.prototype.beginFrame = function () {
  11476. this.onBeginFrameObservable.notifyObservers(this);
  11477. this._measureFps();
  11478. };
  11479. Engine.prototype.endFrame = function () {
  11480. //force a flush in case we are using a bad OS.
  11481. if (this._badOS) {
  11482. this.flushFramebuffer();
  11483. }
  11484. //submit frame to the vr device, if enabled
  11485. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11486. // TODO: We should only submit the frame if we read frameData successfully.
  11487. this._vrDisplay.submitFrame();
  11488. }
  11489. this.onEndFrameObservable.notifyObservers(this);
  11490. };
  11491. /**
  11492. * resize the view according to the canvas' size.
  11493. * @example
  11494. * window.addEventListener("resize", function () {
  11495. * engine.resize();
  11496. * });
  11497. */
  11498. Engine.prototype.resize = function () {
  11499. // We're not resizing the size of the canvas while in VR mode & presenting
  11500. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11501. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11502. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11503. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11504. }
  11505. };
  11506. /**
  11507. * force a specific size of the canvas
  11508. * @param {number} width - the new canvas' width
  11509. * @param {number} height - the new canvas' height
  11510. */
  11511. Engine.prototype.setSize = function (width, height) {
  11512. if (!this._renderingCanvas) {
  11513. return;
  11514. }
  11515. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11516. return;
  11517. }
  11518. this._renderingCanvas.width = width;
  11519. this._renderingCanvas.height = height;
  11520. for (var index = 0; index < this.scenes.length; index++) {
  11521. var scene = this.scenes[index];
  11522. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11523. var cam = scene.cameras[camIndex];
  11524. cam._currentRenderId = 0;
  11525. }
  11526. }
  11527. if (this.onResizeObservable.hasObservers) {
  11528. this.onResizeObservable.notifyObservers(this);
  11529. }
  11530. };
  11531. // WebVR functions
  11532. Engine.prototype.isVRDevicePresent = function () {
  11533. return !!this._vrDisplay;
  11534. };
  11535. Engine.prototype.getVRDevice = function () {
  11536. return this._vrDisplay;
  11537. };
  11538. Engine.prototype.initWebVR = function () {
  11539. var _this = this;
  11540. var notifyObservers = function () {
  11541. var eventArgs = {
  11542. vrDisplay: _this._vrDisplay,
  11543. vrSupported: _this._vrSupported
  11544. };
  11545. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11546. };
  11547. if (!this._onVrDisplayConnect) {
  11548. this._onVrDisplayConnect = function (event) {
  11549. _this._vrDisplay = event.display;
  11550. notifyObservers();
  11551. };
  11552. this._onVrDisplayDisconnect = function () {
  11553. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11554. _this._vrDisplay = undefined;
  11555. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11556. notifyObservers();
  11557. };
  11558. this._onVrDisplayPresentChange = function () {
  11559. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11560. };
  11561. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11562. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11563. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11564. }
  11565. this._getVRDisplays(notifyObservers);
  11566. return this.onVRDisplayChangedObservable;
  11567. };
  11568. Engine.prototype.enableVR = function () {
  11569. var _this = this;
  11570. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11571. var onResolved = function () {
  11572. _this.onVRRequestPresentComplete.notifyObservers(true);
  11573. _this._onVRFullScreenTriggered();
  11574. };
  11575. var onRejected = function () {
  11576. _this.onVRRequestPresentComplete.notifyObservers(false);
  11577. };
  11578. this.onVRRequestPresentStart.notifyObservers(this);
  11579. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11580. }
  11581. };
  11582. Engine.prototype.disableVR = function () {
  11583. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11584. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11585. }
  11586. };
  11587. Engine.prototype._getVRDisplays = function (callback) {
  11588. var _this = this;
  11589. var getWebVRDevices = function (devices) {
  11590. _this._vrSupported = true;
  11591. // note that devices may actually be an empty array. This is fine;
  11592. // we expect this._vrDisplay to be undefined in this case.
  11593. return _this._vrDisplay = devices[0];
  11594. };
  11595. if (navigator.getVRDisplays) {
  11596. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11597. // TODO: System CANNOT support WebVR, despite API presence.
  11598. _this._vrSupported = false;
  11599. callback();
  11600. });
  11601. }
  11602. else {
  11603. // TODO: Browser does not support WebVR
  11604. this._vrDisplay = undefined;
  11605. this._vrSupported = false;
  11606. callback();
  11607. }
  11608. };
  11609. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11610. if (this._currentRenderTarget) {
  11611. this.unBindFramebuffer(this._currentRenderTarget);
  11612. }
  11613. this._currentRenderTarget = texture;
  11614. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11615. var gl = this._gl;
  11616. if (texture.isCube) {
  11617. if (faceIndex === undefined) {
  11618. faceIndex = 0;
  11619. }
  11620. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11621. }
  11622. if (this._cachedViewport && !forceFullscreenViewport) {
  11623. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11624. }
  11625. else {
  11626. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11627. }
  11628. this.wipeCaches();
  11629. };
  11630. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11631. if (this._currentFramebuffer !== framebuffer) {
  11632. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11633. this._currentFramebuffer = framebuffer;
  11634. }
  11635. };
  11636. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11637. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11638. this._currentRenderTarget = null;
  11639. // If MSAA, we need to bitblt back to main texture
  11640. var gl = this._gl;
  11641. if (texture._MSAAFramebuffer) {
  11642. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11643. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11644. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11645. }
  11646. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11647. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11648. gl.generateMipmap(gl.TEXTURE_2D);
  11649. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11650. }
  11651. if (onBeforeUnbind) {
  11652. if (texture._MSAAFramebuffer) {
  11653. // Bind the correct framebuffer
  11654. this.bindUnboundFramebuffer(texture._framebuffer);
  11655. }
  11656. onBeforeUnbind();
  11657. }
  11658. this.bindUnboundFramebuffer(null);
  11659. };
  11660. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11661. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11662. this._currentRenderTarget = null;
  11663. // If MSAA, we need to bitblt back to main texture
  11664. var gl = this._gl;
  11665. if (textures[0]._MSAAFramebuffer) {
  11666. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11667. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11668. var attachments = textures[0]._attachments;
  11669. if (!attachments) {
  11670. attachments = new Array(textures.length);
  11671. textures[0]._attachments = attachments;
  11672. }
  11673. for (var i = 0; i < textures.length; i++) {
  11674. var texture = textures[i];
  11675. for (var j = 0; j < attachments.length; j++) {
  11676. attachments[j] = gl.NONE;
  11677. }
  11678. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11679. gl.readBuffer(attachments[i]);
  11680. gl.drawBuffers(attachments);
  11681. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11682. }
  11683. for (var i = 0; i < attachments.length; i++) {
  11684. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11685. }
  11686. gl.drawBuffers(attachments);
  11687. }
  11688. for (var i = 0; i < textures.length; i++) {
  11689. var texture = textures[i];
  11690. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11691. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11692. gl.generateMipmap(gl.TEXTURE_2D);
  11693. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11694. }
  11695. }
  11696. if (onBeforeUnbind) {
  11697. if (textures[0]._MSAAFramebuffer) {
  11698. // Bind the correct framebuffer
  11699. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11700. }
  11701. onBeforeUnbind();
  11702. }
  11703. this.bindUnboundFramebuffer(null);
  11704. };
  11705. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11706. if (texture.generateMipMaps) {
  11707. var gl = this._gl;
  11708. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11709. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11710. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11711. }
  11712. };
  11713. Engine.prototype.flushFramebuffer = function () {
  11714. this._gl.flush();
  11715. };
  11716. Engine.prototype.restoreDefaultFramebuffer = function () {
  11717. if (this._currentRenderTarget) {
  11718. this.unBindFramebuffer(this._currentRenderTarget);
  11719. }
  11720. else {
  11721. this.bindUnboundFramebuffer(null);
  11722. }
  11723. if (this._cachedViewport) {
  11724. this.setViewport(this._cachedViewport);
  11725. }
  11726. this.wipeCaches();
  11727. };
  11728. // UBOs
  11729. Engine.prototype.createUniformBuffer = function (elements) {
  11730. var ubo = this._gl.createBuffer();
  11731. if (!ubo) {
  11732. throw new Error("Unable to create uniform buffer");
  11733. }
  11734. this.bindUniformBuffer(ubo);
  11735. if (elements instanceof Float32Array) {
  11736. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11737. }
  11738. else {
  11739. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11740. }
  11741. this.bindUniformBuffer(null);
  11742. ubo.references = 1;
  11743. return ubo;
  11744. };
  11745. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11746. var ubo = this._gl.createBuffer();
  11747. if (!ubo) {
  11748. throw new Error("Unable to create dynamic uniform buffer");
  11749. }
  11750. this.bindUniformBuffer(ubo);
  11751. if (elements instanceof Float32Array) {
  11752. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11753. }
  11754. else {
  11755. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11756. }
  11757. this.bindUniformBuffer(null);
  11758. ubo.references = 1;
  11759. return ubo;
  11760. };
  11761. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11762. this.bindUniformBuffer(uniformBuffer);
  11763. if (offset === undefined) {
  11764. offset = 0;
  11765. }
  11766. if (count === undefined) {
  11767. if (elements instanceof Float32Array) {
  11768. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11769. }
  11770. else {
  11771. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11772. }
  11773. }
  11774. else {
  11775. if (elements instanceof Float32Array) {
  11776. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11777. }
  11778. else {
  11779. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11780. }
  11781. }
  11782. this.bindUniformBuffer(null);
  11783. };
  11784. // VBOs
  11785. Engine.prototype._resetVertexBufferBinding = function () {
  11786. this.bindArrayBuffer(null);
  11787. this._cachedVertexBuffers = null;
  11788. };
  11789. Engine.prototype.createVertexBuffer = function (vertices) {
  11790. var vbo = this._gl.createBuffer();
  11791. if (!vbo) {
  11792. throw new Error("Unable to create vertex buffer");
  11793. }
  11794. this.bindArrayBuffer(vbo);
  11795. if (vertices instanceof Float32Array) {
  11796. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11797. }
  11798. else {
  11799. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11800. }
  11801. this._resetVertexBufferBinding();
  11802. vbo.references = 1;
  11803. return vbo;
  11804. };
  11805. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11806. var vbo = this._gl.createBuffer();
  11807. if (!vbo) {
  11808. throw new Error("Unable to create dynamic vertex buffer");
  11809. }
  11810. this.bindArrayBuffer(vbo);
  11811. if (vertices instanceof Float32Array) {
  11812. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11813. }
  11814. else {
  11815. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11816. }
  11817. this._resetVertexBufferBinding();
  11818. vbo.references = 1;
  11819. return vbo;
  11820. };
  11821. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11822. if (offset === void 0) { offset = 0; }
  11823. // Force cache update
  11824. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11825. this.bindIndexBuffer(indexBuffer);
  11826. var arrayBuffer;
  11827. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11828. arrayBuffer = indices;
  11829. }
  11830. else {
  11831. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11832. }
  11833. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11834. this._resetIndexBufferBinding();
  11835. };
  11836. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11837. this.bindArrayBuffer(vertexBuffer);
  11838. if (offset === undefined) {
  11839. offset = 0;
  11840. }
  11841. if (count === undefined) {
  11842. if (vertices instanceof Float32Array) {
  11843. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11844. }
  11845. else {
  11846. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11847. }
  11848. }
  11849. else {
  11850. if (vertices instanceof Float32Array) {
  11851. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11852. }
  11853. else {
  11854. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11855. }
  11856. }
  11857. this._resetVertexBufferBinding();
  11858. };
  11859. Engine.prototype._resetIndexBufferBinding = function () {
  11860. this.bindIndexBuffer(null);
  11861. this._cachedIndexBuffer = null;
  11862. };
  11863. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11864. var vbo = this._gl.createBuffer();
  11865. if (!vbo) {
  11866. throw new Error("Unable to create index buffer");
  11867. }
  11868. this.bindIndexBuffer(vbo);
  11869. // Check for 32 bits indices
  11870. var arrayBuffer;
  11871. var need32Bits = false;
  11872. if (indices instanceof Uint16Array) {
  11873. arrayBuffer = indices;
  11874. }
  11875. else {
  11876. //check 32 bit support
  11877. if (this._caps.uintIndices) {
  11878. if (indices instanceof Uint32Array) {
  11879. arrayBuffer = indices;
  11880. need32Bits = true;
  11881. }
  11882. else {
  11883. //number[] or Int32Array, check if 32 bit is necessary
  11884. for (var index = 0; index < indices.length; index++) {
  11885. if (indices[index] > 65535) {
  11886. need32Bits = true;
  11887. break;
  11888. }
  11889. }
  11890. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11891. }
  11892. }
  11893. else {
  11894. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11895. arrayBuffer = new Uint16Array(indices);
  11896. }
  11897. }
  11898. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11899. this._resetIndexBufferBinding();
  11900. vbo.references = 1;
  11901. vbo.is32Bits = need32Bits;
  11902. return vbo;
  11903. };
  11904. Engine.prototype.bindArrayBuffer = function (buffer) {
  11905. if (!this._vaoRecordInProgress) {
  11906. this._unbindVertexArrayObject();
  11907. }
  11908. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11909. };
  11910. Engine.prototype.bindUniformBuffer = function (buffer) {
  11911. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11912. };
  11913. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11914. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11915. };
  11916. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11917. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11918. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11919. };
  11920. ;
  11921. Engine.prototype.bindIndexBuffer = function (buffer) {
  11922. if (!this._vaoRecordInProgress) {
  11923. this._unbindVertexArrayObject();
  11924. }
  11925. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11926. };
  11927. Engine.prototype.bindBuffer = function (buffer, target) {
  11928. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11929. this._gl.bindBuffer(target, buffer);
  11930. this._currentBoundBuffer[target] = buffer;
  11931. }
  11932. };
  11933. Engine.prototype.updateArrayBuffer = function (data) {
  11934. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11935. };
  11936. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11937. var pointer = this._currentBufferPointers[indx];
  11938. var changed = false;
  11939. if (!pointer.active) {
  11940. changed = true;
  11941. pointer.active = true;
  11942. pointer.index = indx;
  11943. pointer.size = size;
  11944. pointer.type = type;
  11945. pointer.normalized = normalized;
  11946. pointer.stride = stride;
  11947. pointer.offset = offset;
  11948. pointer.buffer = buffer;
  11949. }
  11950. else {
  11951. if (pointer.buffer !== buffer) {
  11952. pointer.buffer = buffer;
  11953. changed = true;
  11954. }
  11955. if (pointer.size !== size) {
  11956. pointer.size = size;
  11957. changed = true;
  11958. }
  11959. if (pointer.type !== type) {
  11960. pointer.type = type;
  11961. changed = true;
  11962. }
  11963. if (pointer.normalized !== normalized) {
  11964. pointer.normalized = normalized;
  11965. changed = true;
  11966. }
  11967. if (pointer.stride !== stride) {
  11968. pointer.stride = stride;
  11969. changed = true;
  11970. }
  11971. if (pointer.offset !== offset) {
  11972. pointer.offset = offset;
  11973. changed = true;
  11974. }
  11975. }
  11976. if (changed || this._vaoRecordInProgress) {
  11977. this.bindArrayBuffer(buffer);
  11978. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11979. }
  11980. };
  11981. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11982. if (indexBuffer == null) {
  11983. return;
  11984. }
  11985. if (this._cachedIndexBuffer !== indexBuffer) {
  11986. this._cachedIndexBuffer = indexBuffer;
  11987. this.bindIndexBuffer(indexBuffer);
  11988. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11989. }
  11990. };
  11991. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11992. var attributes = effect.getAttributesNames();
  11993. if (!this._vaoRecordInProgress) {
  11994. this._unbindVertexArrayObject();
  11995. }
  11996. this.unbindAllAttributes();
  11997. for (var index = 0; index < attributes.length; index++) {
  11998. var order = effect.getAttributeLocation(index);
  11999. if (order >= 0) {
  12000. var vertexBuffer = vertexBuffers[attributes[index]];
  12001. if (!vertexBuffer) {
  12002. continue;
  12003. }
  12004. this._gl.enableVertexAttribArray(order);
  12005. if (!this._vaoRecordInProgress) {
  12006. this._vertexAttribArraysEnabled[order] = true;
  12007. }
  12008. var buffer = vertexBuffer.getBuffer();
  12009. if (buffer) {
  12010. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12011. if (vertexBuffer.getIsInstanced()) {
  12012. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12013. if (!this._vaoRecordInProgress) {
  12014. this._currentInstanceLocations.push(order);
  12015. this._currentInstanceBuffers.push(buffer);
  12016. }
  12017. }
  12018. }
  12019. }
  12020. }
  12021. };
  12022. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12023. var vao = this._gl.createVertexArray();
  12024. this._vaoRecordInProgress = true;
  12025. this._gl.bindVertexArray(vao);
  12026. this._mustWipeVertexAttributes = true;
  12027. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12028. this.bindIndexBuffer(indexBuffer);
  12029. this._vaoRecordInProgress = false;
  12030. this._gl.bindVertexArray(null);
  12031. return vao;
  12032. };
  12033. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12034. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12035. this._cachedVertexArrayObject = vertexArrayObject;
  12036. this._gl.bindVertexArray(vertexArrayObject);
  12037. this._cachedVertexBuffers = null;
  12038. this._cachedIndexBuffer = null;
  12039. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12040. this._mustWipeVertexAttributes = true;
  12041. }
  12042. };
  12043. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12044. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12045. this._cachedVertexBuffers = vertexBuffer;
  12046. this._cachedEffectForVertexBuffers = effect;
  12047. var attributesCount = effect.getAttributesCount();
  12048. this._unbindVertexArrayObject();
  12049. this.unbindAllAttributes();
  12050. var offset = 0;
  12051. for (var index = 0; index < attributesCount; index++) {
  12052. if (index < vertexDeclaration.length) {
  12053. var order = effect.getAttributeLocation(index);
  12054. if (order >= 0) {
  12055. this._gl.enableVertexAttribArray(order);
  12056. this._vertexAttribArraysEnabled[order] = true;
  12057. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12058. }
  12059. offset += vertexDeclaration[index] * 4;
  12060. }
  12061. }
  12062. }
  12063. this._bindIndexBufferWithCache(indexBuffer);
  12064. };
  12065. Engine.prototype._unbindVertexArrayObject = function () {
  12066. if (!this._cachedVertexArrayObject) {
  12067. return;
  12068. }
  12069. this._cachedVertexArrayObject = null;
  12070. this._gl.bindVertexArray(null);
  12071. };
  12072. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12073. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12074. this._cachedVertexBuffers = vertexBuffers;
  12075. this._cachedEffectForVertexBuffers = effect;
  12076. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12077. }
  12078. this._bindIndexBufferWithCache(indexBuffer);
  12079. };
  12080. Engine.prototype.unbindInstanceAttributes = function () {
  12081. var boundBuffer;
  12082. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12083. var instancesBuffer = this._currentInstanceBuffers[i];
  12084. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12085. boundBuffer = instancesBuffer;
  12086. this.bindArrayBuffer(instancesBuffer);
  12087. }
  12088. var offsetLocation = this._currentInstanceLocations[i];
  12089. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12090. }
  12091. this._currentInstanceBuffers.length = 0;
  12092. this._currentInstanceLocations.length = 0;
  12093. };
  12094. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12095. this._gl.deleteVertexArray(vao);
  12096. };
  12097. Engine.prototype._releaseBuffer = function (buffer) {
  12098. buffer.references--;
  12099. if (buffer.references === 0) {
  12100. this._gl.deleteBuffer(buffer);
  12101. return true;
  12102. }
  12103. return false;
  12104. };
  12105. Engine.prototype.createInstancesBuffer = function (capacity) {
  12106. var buffer = this._gl.createBuffer();
  12107. if (!buffer) {
  12108. throw new Error("Unable to create instance buffer");
  12109. }
  12110. buffer.capacity = capacity;
  12111. this.bindArrayBuffer(buffer);
  12112. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12113. return buffer;
  12114. };
  12115. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12116. this._gl.deleteBuffer(buffer);
  12117. };
  12118. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12119. this.bindArrayBuffer(instancesBuffer);
  12120. if (data) {
  12121. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12122. }
  12123. if (offsetLocations[0].index !== undefined) {
  12124. var stride = 0;
  12125. for (var i = 0; i < offsetLocations.length; i++) {
  12126. var ai = offsetLocations[i];
  12127. stride += ai.attributeSize * 4;
  12128. }
  12129. for (var i = 0; i < offsetLocations.length; i++) {
  12130. var ai = offsetLocations[i];
  12131. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12132. this._gl.enableVertexAttribArray(ai.index);
  12133. this._vertexAttribArraysEnabled[ai.index] = true;
  12134. }
  12135. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12136. this._gl.vertexAttribDivisor(ai.index, 1);
  12137. this._currentInstanceLocations.push(ai.index);
  12138. this._currentInstanceBuffers.push(instancesBuffer);
  12139. }
  12140. }
  12141. else {
  12142. for (var index = 0; index < 4; index++) {
  12143. var offsetLocation = offsetLocations[index];
  12144. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12145. this._gl.enableVertexAttribArray(offsetLocation);
  12146. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12147. }
  12148. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12149. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12150. this._currentInstanceLocations.push(offsetLocation);
  12151. this._currentInstanceBuffers.push(instancesBuffer);
  12152. }
  12153. }
  12154. };
  12155. Engine.prototype.applyStates = function () {
  12156. this._depthCullingState.apply(this._gl);
  12157. this._stencilState.apply(this._gl);
  12158. this._alphaState.apply(this._gl);
  12159. };
  12160. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12161. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12162. };
  12163. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12164. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12165. };
  12166. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12167. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12168. };
  12169. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12170. // Apply states
  12171. this.applyStates();
  12172. this._drawCalls.addCount(1, false);
  12173. // Render
  12174. var drawMode = this.DrawMode(fillMode);
  12175. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12176. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12177. if (instancesCount) {
  12178. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12179. }
  12180. else {
  12181. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12182. }
  12183. };
  12184. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12185. // Apply states
  12186. this.applyStates();
  12187. this._drawCalls.addCount(1, false);
  12188. var drawMode = this.DrawMode(fillMode);
  12189. if (instancesCount) {
  12190. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12191. }
  12192. else {
  12193. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12194. }
  12195. };
  12196. Engine.prototype.DrawMode = function (fillMode) {
  12197. switch (fillMode) {
  12198. // Triangle views
  12199. case BABYLON.Material.TriangleFillMode:
  12200. return this._gl.TRIANGLES;
  12201. case BABYLON.Material.PointFillMode:
  12202. return this._gl.POINTS;
  12203. case BABYLON.Material.WireFrameFillMode:
  12204. return this._gl.LINES;
  12205. // Draw modes
  12206. case BABYLON.Material.PointListDrawMode:
  12207. return this._gl.POINTS;
  12208. case BABYLON.Material.LineListDrawMode:
  12209. return this._gl.LINES;
  12210. case BABYLON.Material.LineLoopDrawMode:
  12211. return this._gl.LINE_LOOP;
  12212. case BABYLON.Material.LineStripDrawMode:
  12213. return this._gl.LINE_STRIP;
  12214. case BABYLON.Material.TriangleStripDrawMode:
  12215. return this._gl.TRIANGLE_STRIP;
  12216. case BABYLON.Material.TriangleFanDrawMode:
  12217. return this._gl.TRIANGLE_FAN;
  12218. default:
  12219. return this._gl.TRIANGLES;
  12220. }
  12221. };
  12222. // Shaders
  12223. Engine.prototype._releaseEffect = function (effect) {
  12224. if (this._compiledEffects[effect._key]) {
  12225. delete this._compiledEffects[effect._key];
  12226. this._deleteProgram(effect.getProgram());
  12227. }
  12228. };
  12229. Engine.prototype._deleteProgram = function (program) {
  12230. if (program) {
  12231. program.__SPECTOR_rebuildProgram = null;
  12232. if (program.transformFeedback) {
  12233. this.deleteTransformFeedback(program.transformFeedback);
  12234. program.transformFeedback = null;
  12235. }
  12236. this._gl.deleteProgram(program);
  12237. }
  12238. };
  12239. /**
  12240. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12241. * @param samplers An array of string used to represent textures
  12242. */
  12243. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12244. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12245. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12246. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12247. if (this._compiledEffects[name]) {
  12248. var compiledEffect = this._compiledEffects[name];
  12249. if (onCompiled && compiledEffect.isReady()) {
  12250. onCompiled(compiledEffect);
  12251. }
  12252. return compiledEffect;
  12253. }
  12254. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12255. effect._key = name;
  12256. this._compiledEffects[name] = effect;
  12257. return effect;
  12258. };
  12259. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12260. if (uniformsNames === void 0) { uniformsNames = []; }
  12261. if (samplers === void 0) { samplers = []; }
  12262. if (defines === void 0) { defines = ""; }
  12263. return this.createEffect({
  12264. vertex: "particles",
  12265. fragmentElement: fragmentName
  12266. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12267. };
  12268. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12269. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12270. context = context || this._gl;
  12271. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12272. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12273. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12274. };
  12275. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12276. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12277. context = context || this._gl;
  12278. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12279. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12280. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12281. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12282. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12283. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12284. return program;
  12285. };
  12286. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12287. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12288. var shaderProgram = context.createProgram();
  12289. if (!shaderProgram) {
  12290. throw new Error("Unable to create program");
  12291. }
  12292. context.attachShader(shaderProgram, vertexShader);
  12293. context.attachShader(shaderProgram, fragmentShader);
  12294. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12295. var transformFeedback = this.createTransformFeedback();
  12296. this.bindTransformFeedback(transformFeedback);
  12297. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12298. shaderProgram.transformFeedback = transformFeedback;
  12299. }
  12300. context.linkProgram(shaderProgram);
  12301. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12302. this.bindTransformFeedback(null);
  12303. }
  12304. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12305. if (!linked) {
  12306. context.validateProgram(shaderProgram);
  12307. var error = context.getProgramInfoLog(shaderProgram);
  12308. if (error) {
  12309. throw new Error(error);
  12310. }
  12311. }
  12312. context.deleteShader(vertexShader);
  12313. context.deleteShader(fragmentShader);
  12314. return shaderProgram;
  12315. };
  12316. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12317. var results = new Array();
  12318. for (var index = 0; index < uniformsNames.length; index++) {
  12319. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12320. }
  12321. return results;
  12322. };
  12323. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12324. var results = [];
  12325. for (var index = 0; index < attributesNames.length; index++) {
  12326. try {
  12327. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12328. }
  12329. catch (e) {
  12330. results.push(-1);
  12331. }
  12332. }
  12333. return results;
  12334. };
  12335. Engine.prototype.enableEffect = function (effect) {
  12336. if (!effect) {
  12337. return;
  12338. }
  12339. // Use program
  12340. this.bindSamplers(effect);
  12341. this._currentEffect = effect;
  12342. if (effect.onBind) {
  12343. effect.onBind(effect);
  12344. }
  12345. effect.onBindObservable.notifyObservers(effect);
  12346. };
  12347. Engine.prototype.setIntArray = function (uniform, array) {
  12348. if (!uniform)
  12349. return;
  12350. this._gl.uniform1iv(uniform, array);
  12351. };
  12352. Engine.prototype.setIntArray2 = function (uniform, array) {
  12353. if (!uniform || array.length % 2 !== 0)
  12354. return;
  12355. this._gl.uniform2iv(uniform, array);
  12356. };
  12357. Engine.prototype.setIntArray3 = function (uniform, array) {
  12358. if (!uniform || array.length % 3 !== 0)
  12359. return;
  12360. this._gl.uniform3iv(uniform, array);
  12361. };
  12362. Engine.prototype.setIntArray4 = function (uniform, array) {
  12363. if (!uniform || array.length % 4 !== 0)
  12364. return;
  12365. this._gl.uniform4iv(uniform, array);
  12366. };
  12367. Engine.prototype.setFloatArray = function (uniform, array) {
  12368. if (!uniform)
  12369. return;
  12370. this._gl.uniform1fv(uniform, array);
  12371. };
  12372. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12373. if (!uniform || array.length % 2 !== 0)
  12374. return;
  12375. this._gl.uniform2fv(uniform, array);
  12376. };
  12377. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12378. if (!uniform || array.length % 3 !== 0)
  12379. return;
  12380. this._gl.uniform3fv(uniform, array);
  12381. };
  12382. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12383. if (!uniform || array.length % 4 !== 0)
  12384. return;
  12385. this._gl.uniform4fv(uniform, array);
  12386. };
  12387. Engine.prototype.setArray = function (uniform, array) {
  12388. if (!uniform)
  12389. return;
  12390. this._gl.uniform1fv(uniform, array);
  12391. };
  12392. Engine.prototype.setArray2 = function (uniform, array) {
  12393. if (!uniform || array.length % 2 !== 0)
  12394. return;
  12395. this._gl.uniform2fv(uniform, array);
  12396. };
  12397. Engine.prototype.setArray3 = function (uniform, array) {
  12398. if (!uniform || array.length % 3 !== 0)
  12399. return;
  12400. this._gl.uniform3fv(uniform, array);
  12401. };
  12402. Engine.prototype.setArray4 = function (uniform, array) {
  12403. if (!uniform || array.length % 4 !== 0)
  12404. return;
  12405. this._gl.uniform4fv(uniform, array);
  12406. };
  12407. Engine.prototype.setMatrices = function (uniform, matrices) {
  12408. if (!uniform)
  12409. return;
  12410. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12411. };
  12412. Engine.prototype.setMatrix = function (uniform, matrix) {
  12413. if (!uniform)
  12414. return;
  12415. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12416. };
  12417. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12418. if (!uniform)
  12419. return;
  12420. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12421. };
  12422. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12423. if (!uniform)
  12424. return;
  12425. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12426. };
  12427. Engine.prototype.setInt = function (uniform, value) {
  12428. if (!uniform)
  12429. return;
  12430. this._gl.uniform1i(uniform, value);
  12431. };
  12432. Engine.prototype.setFloat = function (uniform, value) {
  12433. if (!uniform)
  12434. return;
  12435. this._gl.uniform1f(uniform, value);
  12436. };
  12437. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12438. if (!uniform)
  12439. return;
  12440. this._gl.uniform2f(uniform, x, y);
  12441. };
  12442. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12443. if (!uniform)
  12444. return;
  12445. this._gl.uniform3f(uniform, x, y, z);
  12446. };
  12447. Engine.prototype.setBool = function (uniform, bool) {
  12448. if (!uniform)
  12449. return;
  12450. this._gl.uniform1i(uniform, bool);
  12451. };
  12452. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12453. if (!uniform)
  12454. return;
  12455. this._gl.uniform4f(uniform, x, y, z, w);
  12456. };
  12457. Engine.prototype.setColor3 = function (uniform, color3) {
  12458. if (!uniform)
  12459. return;
  12460. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12461. };
  12462. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12463. if (!uniform)
  12464. return;
  12465. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12466. };
  12467. // States
  12468. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12469. if (zOffset === void 0) { zOffset = 0; }
  12470. if (reverseSide === void 0) { reverseSide = false; }
  12471. // Culling
  12472. if (this._depthCullingState.cull !== culling || force) {
  12473. this._depthCullingState.cull = culling;
  12474. }
  12475. // Cull face
  12476. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12477. if (this._depthCullingState.cullFace !== cullFace || force) {
  12478. this._depthCullingState.cullFace = cullFace;
  12479. }
  12480. // Z offset
  12481. this.setZOffset(zOffset);
  12482. // Front face
  12483. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12484. if (this._depthCullingState.frontFace !== frontFace || force) {
  12485. this._depthCullingState.frontFace = frontFace;
  12486. }
  12487. };
  12488. Engine.prototype.setZOffset = function (value) {
  12489. this._depthCullingState.zOffset = value;
  12490. };
  12491. Engine.prototype.getZOffset = function () {
  12492. return this._depthCullingState.zOffset;
  12493. };
  12494. Engine.prototype.setDepthBuffer = function (enable) {
  12495. this._depthCullingState.depthTest = enable;
  12496. };
  12497. Engine.prototype.getDepthWrite = function () {
  12498. return this._depthCullingState.depthMask;
  12499. };
  12500. Engine.prototype.setDepthWrite = function (enable) {
  12501. this._depthCullingState.depthMask = enable;
  12502. };
  12503. Engine.prototype.setColorWrite = function (enable) {
  12504. this._gl.colorMask(enable, enable, enable, enable);
  12505. this._colorWrite = enable;
  12506. };
  12507. Engine.prototype.getColorWrite = function () {
  12508. return this._colorWrite;
  12509. };
  12510. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12511. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12512. };
  12513. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12514. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12515. if (this._alphaMode === mode) {
  12516. return;
  12517. }
  12518. switch (mode) {
  12519. case Engine.ALPHA_DISABLE:
  12520. this._alphaState.alphaBlend = false;
  12521. break;
  12522. case Engine.ALPHA_PREMULTIPLIED:
  12523. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12524. this._alphaState.alphaBlend = true;
  12525. break;
  12526. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12527. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12528. this._alphaState.alphaBlend = true;
  12529. break;
  12530. case Engine.ALPHA_COMBINE:
  12531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12532. this._alphaState.alphaBlend = true;
  12533. break;
  12534. case Engine.ALPHA_ONEONE:
  12535. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12536. this._alphaState.alphaBlend = true;
  12537. break;
  12538. case Engine.ALPHA_ADD:
  12539. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12540. this._alphaState.alphaBlend = true;
  12541. break;
  12542. case Engine.ALPHA_SUBTRACT:
  12543. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12544. this._alphaState.alphaBlend = true;
  12545. break;
  12546. case Engine.ALPHA_MULTIPLY:
  12547. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12548. this._alphaState.alphaBlend = true;
  12549. break;
  12550. case Engine.ALPHA_MAXIMIZED:
  12551. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12552. this._alphaState.alphaBlend = true;
  12553. break;
  12554. case Engine.ALPHA_INTERPOLATE:
  12555. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12556. this._alphaState.alphaBlend = true;
  12557. break;
  12558. case Engine.ALPHA_SCREENMODE:
  12559. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12560. this._alphaState.alphaBlend = true;
  12561. break;
  12562. }
  12563. if (!noDepthWriteChange) {
  12564. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12565. }
  12566. this._alphaMode = mode;
  12567. };
  12568. Engine.prototype.getAlphaMode = function () {
  12569. return this._alphaMode;
  12570. };
  12571. // Textures
  12572. Engine.prototype.wipeCaches = function (bruteForce) {
  12573. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12574. return;
  12575. }
  12576. this._currentEffect = null;
  12577. // 6/8/2017: deltakosh: Should not be required anymore.
  12578. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12579. if (bruteForce) {
  12580. this.resetTextureCache();
  12581. this._currentProgram = null;
  12582. this._stencilState.reset();
  12583. this._depthCullingState.reset();
  12584. this.setDepthFunctionToLessOrEqual();
  12585. this._alphaState.reset();
  12586. }
  12587. this._resetVertexBufferBinding();
  12588. this._cachedIndexBuffer = null;
  12589. this._cachedEffectForVertexBuffers = null;
  12590. this._unbindVertexArrayObject();
  12591. this.bindIndexBuffer(null);
  12592. };
  12593. /**
  12594. * Set the compressed texture format to use, based on the formats you have, and the formats
  12595. * supported by the hardware / browser.
  12596. *
  12597. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12598. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12599. * to API arguments needed to compressed textures. This puts the burden on the container
  12600. * generator to house the arcane code for determining these for current & future formats.
  12601. *
  12602. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12603. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12604. *
  12605. * Note: The result of this call is not taken into account when a texture is base64.
  12606. *
  12607. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12608. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12609. *
  12610. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12611. * @returns The extension selected.
  12612. */
  12613. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12614. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12615. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12616. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12617. return this._textureFormatInUse = this._texturesSupported[i];
  12618. }
  12619. }
  12620. }
  12621. // actively set format to nothing, to allow this to be called more than once
  12622. // and possibly fail the 2nd time
  12623. this._textureFormatInUse = null;
  12624. return null;
  12625. };
  12626. Engine.prototype._createTexture = function () {
  12627. var texture = this._gl.createTexture();
  12628. if (!texture) {
  12629. throw new Error("Unable to create texture");
  12630. }
  12631. return texture;
  12632. };
  12633. /**
  12634. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12635. * @param {string} urlArg- This contains one of the following:
  12636. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12637. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12638. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12639. *
  12640. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12641. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12642. * @param {Scene} scene- Needed for loading to the correct scene.
  12643. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12644. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12645. * @param {callback} onError- Optional callback to be called upon failure.
  12646. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12647. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12648. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12649. *
  12650. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12651. */
  12652. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12653. var _this = this;
  12654. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12655. if (onLoad === void 0) { onLoad = null; }
  12656. if (onError === void 0) { onError = null; }
  12657. if (buffer === void 0) { buffer = null; }
  12658. if (fallBack === void 0) { fallBack = null; }
  12659. if (format === void 0) { format = null; }
  12660. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12661. var fromData = url.substr(0, 5) === "data:";
  12662. var fromBlob = url.substr(0, 5) === "blob:";
  12663. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12664. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12665. // establish the file extension, if possible
  12666. var lastDot = url.lastIndexOf('.');
  12667. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12668. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12669. var isTGA = (extension.indexOf(".tga") === 0);
  12670. // determine if a ktx file should be substituted
  12671. var isKTX = false;
  12672. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12673. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12674. isKTX = true;
  12675. }
  12676. if (scene) {
  12677. scene._addPendingData(texture);
  12678. }
  12679. texture.url = url;
  12680. texture.generateMipMaps = !noMipmap;
  12681. texture.samplingMode = samplingMode;
  12682. texture.invertY = invertY;
  12683. if (!this._doNotHandleContextLost) {
  12684. // Keep a link to the buffer only if we plan to handle context lost
  12685. texture._buffer = buffer;
  12686. }
  12687. var onLoadObserver = null;
  12688. if (onLoad && !fallBack) {
  12689. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12690. }
  12691. if (!fallBack)
  12692. this._internalTexturesCache.push(texture);
  12693. var onerror = function (message, exception) {
  12694. if (scene) {
  12695. scene._removePendingData(texture);
  12696. }
  12697. if (onLoadObserver) {
  12698. texture.onLoadedObservable.remove(onLoadObserver);
  12699. }
  12700. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12701. if (isKTX) {
  12702. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12703. }
  12704. else if (BABYLON.Tools.UseFallbackTexture) {
  12705. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12706. }
  12707. if (onError) {
  12708. onError(message || "Unknown error", exception);
  12709. }
  12710. };
  12711. var callback = null;
  12712. // processing for non-image formats
  12713. if (isKTX || isTGA || isDDS) {
  12714. if (isKTX) {
  12715. callback = function (data) {
  12716. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12717. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12718. ktx.uploadLevels(_this._gl, !noMipmap);
  12719. return false;
  12720. }, samplingMode);
  12721. };
  12722. }
  12723. else if (isTGA) {
  12724. callback = function (arrayBuffer) {
  12725. var data = new Uint8Array(arrayBuffer);
  12726. var header = BABYLON.TGATools.GetTGAHeader(data);
  12727. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12728. BABYLON.TGATools.UploadContent(_this._gl, data);
  12729. return false;
  12730. }, samplingMode);
  12731. };
  12732. }
  12733. else if (isDDS) {
  12734. callback = function (data) {
  12735. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12736. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12737. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12738. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12739. return false;
  12740. }, samplingMode);
  12741. };
  12742. }
  12743. if (!buffer) {
  12744. this._loadFile(url, function (data) {
  12745. if (callback) {
  12746. callback(data);
  12747. }
  12748. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12749. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12750. });
  12751. }
  12752. else {
  12753. if (callback) {
  12754. callback(buffer);
  12755. }
  12756. }
  12757. // image format processing
  12758. }
  12759. else {
  12760. var onload = function (img) {
  12761. if (fromBlob && !_this._doNotHandleContextLost) {
  12762. // We need to store the image if we need to rebuild the texture
  12763. // in case of a webgl context lost
  12764. texture._buffer = img;
  12765. }
  12766. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12767. var gl = _this._gl;
  12768. var isPot = (img.width === potWidth && img.height === potHeight);
  12769. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12770. if (isPot) {
  12771. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12772. return false;
  12773. }
  12774. // Using shaders to rescale because canvas.drawImage is lossy
  12775. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12776. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12777. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12782. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12783. _this._releaseTexture(source);
  12784. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12785. continuationCallback();
  12786. });
  12787. return true;
  12788. }, samplingMode);
  12789. };
  12790. if (!fromData || isBase64)
  12791. if (buffer instanceof HTMLImageElement) {
  12792. onload(buffer);
  12793. }
  12794. else {
  12795. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12796. }
  12797. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12798. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12799. else
  12800. onload(buffer);
  12801. }
  12802. return texture;
  12803. };
  12804. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12805. var _this = this;
  12806. var rtt = this.createRenderTargetTexture({
  12807. width: destination.width,
  12808. height: destination.height,
  12809. }, {
  12810. generateMipMaps: false,
  12811. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12812. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12813. generateDepthBuffer: false,
  12814. generateStencilBuffer: false
  12815. });
  12816. if (!this._rescalePostProcess) {
  12817. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12818. }
  12819. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12820. _this._rescalePostProcess.onApply = function (effect) {
  12821. effect._bindTexture("textureSampler", source);
  12822. };
  12823. var hostingScene = scene;
  12824. if (!hostingScene) {
  12825. hostingScene = _this.scenes[_this.scenes.length - 1];
  12826. }
  12827. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12828. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12829. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12830. _this.unBindFramebuffer(rtt);
  12831. _this._releaseTexture(rtt);
  12832. if (onComplete) {
  12833. onComplete();
  12834. }
  12835. });
  12836. };
  12837. Engine.prototype._getInternalFormat = function (format) {
  12838. var internalFormat = this._gl.RGBA;
  12839. switch (format) {
  12840. case Engine.TEXTUREFORMAT_ALPHA:
  12841. internalFormat = this._gl.ALPHA;
  12842. break;
  12843. case Engine.TEXTUREFORMAT_LUMINANCE:
  12844. internalFormat = this._gl.LUMINANCE;
  12845. break;
  12846. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12847. internalFormat = this._gl.LUMINANCE_ALPHA;
  12848. break;
  12849. case Engine.TEXTUREFORMAT_RGB:
  12850. internalFormat = this._gl.RGB;
  12851. break;
  12852. case Engine.TEXTUREFORMAT_RGBA:
  12853. internalFormat = this._gl.RGBA;
  12854. break;
  12855. }
  12856. return internalFormat;
  12857. };
  12858. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12859. if (compression === void 0) { compression = null; }
  12860. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12861. if (!texture) {
  12862. return;
  12863. }
  12864. var internalFormat = this._getInternalFormat(format);
  12865. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12866. var textureType = this._getWebGLTextureType(type);
  12867. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12868. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12869. if (!this._doNotHandleContextLost) {
  12870. texture._bufferView = data;
  12871. texture.format = format;
  12872. texture.type = type;
  12873. texture.invertY = invertY;
  12874. texture._compression = compression;
  12875. }
  12876. if (texture.width % 4 !== 0) {
  12877. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12878. }
  12879. if (compression && data) {
  12880. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12881. }
  12882. else {
  12883. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12884. }
  12885. if (texture.generateMipMaps) {
  12886. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12887. }
  12888. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12889. // this.resetTextureCache();
  12890. texture.isReady = true;
  12891. };
  12892. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12893. if (compression === void 0) { compression = null; }
  12894. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12895. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12896. texture.baseWidth = width;
  12897. texture.baseHeight = height;
  12898. texture.width = width;
  12899. texture.height = height;
  12900. texture.format = format;
  12901. texture.generateMipMaps = generateMipMaps;
  12902. texture.samplingMode = samplingMode;
  12903. texture.invertY = invertY;
  12904. texture._compression = compression;
  12905. texture.type = type;
  12906. if (!this._doNotHandleContextLost) {
  12907. texture._bufferView = data;
  12908. }
  12909. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12910. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12911. // Filters
  12912. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12915. if (generateMipMaps) {
  12916. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12917. }
  12918. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12919. this._internalTexturesCache.push(texture);
  12920. return texture;
  12921. };
  12922. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12923. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12924. texture.baseWidth = width;
  12925. texture.baseHeight = height;
  12926. if (generateMipMaps) {
  12927. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12928. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12929. }
  12930. // this.resetTextureCache();
  12931. texture.width = width;
  12932. texture.height = height;
  12933. texture.isReady = false;
  12934. texture.generateMipMaps = generateMipMaps;
  12935. texture.samplingMode = samplingMode;
  12936. this.updateTextureSamplingMode(samplingMode, texture);
  12937. this._internalTexturesCache.push(texture);
  12938. return texture;
  12939. };
  12940. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12941. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12942. if (texture.isCube) {
  12943. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12944. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12945. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12946. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12947. }
  12948. else if (texture.is3D) {
  12949. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12950. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12951. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12952. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12953. }
  12954. else {
  12955. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12956. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12957. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12958. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12959. }
  12960. texture.samplingMode = samplingMode;
  12961. };
  12962. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12963. if (premulAlpha === void 0) { premulAlpha = false; }
  12964. if (!texture) {
  12965. return;
  12966. }
  12967. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12968. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12969. if (premulAlpha) {
  12970. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12971. }
  12972. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12973. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12974. if (texture.generateMipMaps) {
  12975. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12976. }
  12977. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12978. if (premulAlpha) {
  12979. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12980. }
  12981. texture.isReady = true;
  12982. };
  12983. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12984. if (!texture || texture._isDisabled) {
  12985. return;
  12986. }
  12987. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12988. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12989. try {
  12990. // Testing video texture support
  12991. if (this._videoTextureSupported === undefined) {
  12992. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12993. if (this._gl.getError() !== 0) {
  12994. this._videoTextureSupported = false;
  12995. }
  12996. else {
  12997. this._videoTextureSupported = true;
  12998. }
  12999. }
  13000. // Copy video through the current working canvas if video texture is not supported
  13001. if (!this._videoTextureSupported) {
  13002. if (!texture._workingCanvas) {
  13003. texture._workingCanvas = document.createElement("canvas");
  13004. var context = texture._workingCanvas.getContext("2d");
  13005. if (!context) {
  13006. throw new Error("Unable to get 2d context");
  13007. }
  13008. texture._workingContext = context;
  13009. texture._workingCanvas.width = texture.width;
  13010. texture._workingCanvas.height = texture.height;
  13011. }
  13012. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13013. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13014. }
  13015. else {
  13016. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13017. }
  13018. if (texture.generateMipMaps) {
  13019. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13020. }
  13021. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13022. // this.resetTextureCache();
  13023. texture.isReady = true;
  13024. }
  13025. catch (ex) {
  13026. // Something unexpected
  13027. // Let's disable the texture
  13028. texture._isDisabled = true;
  13029. }
  13030. };
  13031. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13032. var fullOptions = new RenderTargetCreationOptions();
  13033. if (options !== undefined && typeof options === "object") {
  13034. fullOptions.generateMipMaps = options.generateMipMaps;
  13035. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13036. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13037. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13038. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13039. }
  13040. else {
  13041. fullOptions.generateMipMaps = options;
  13042. fullOptions.generateDepthBuffer = true;
  13043. fullOptions.generateStencilBuffer = false;
  13044. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13045. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13046. }
  13047. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13048. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13049. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13050. }
  13051. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13052. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13053. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13054. }
  13055. var gl = this._gl;
  13056. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13057. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13058. var width = size.width || size;
  13059. var height = size.height || size;
  13060. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13061. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13062. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13063. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13064. }
  13065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13067. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13069. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13070. // Create the framebuffer
  13071. var framebuffer = gl.createFramebuffer();
  13072. this.bindUnboundFramebuffer(framebuffer);
  13073. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13074. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13075. if (fullOptions.generateMipMaps) {
  13076. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13077. }
  13078. // Unbind
  13079. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13080. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13081. this.bindUnboundFramebuffer(null);
  13082. texture._framebuffer = framebuffer;
  13083. texture.baseWidth = width;
  13084. texture.baseHeight = height;
  13085. texture.width = width;
  13086. texture.height = height;
  13087. texture.isReady = true;
  13088. texture.samples = 1;
  13089. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13090. texture.samplingMode = fullOptions.samplingMode;
  13091. texture.type = fullOptions.type;
  13092. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13093. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13094. // this.resetTextureCache();
  13095. this._internalTexturesCache.push(texture);
  13096. return texture;
  13097. };
  13098. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13099. var generateMipMaps = false;
  13100. var generateDepthBuffer = true;
  13101. var generateStencilBuffer = false;
  13102. var generateDepthTexture = false;
  13103. var textureCount = 1;
  13104. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13105. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13106. var types = [], samplingModes = [];
  13107. if (options !== undefined) {
  13108. generateMipMaps = options.generateMipMaps;
  13109. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13110. generateStencilBuffer = options.generateStencilBuffer;
  13111. generateDepthTexture = options.generateDepthTexture;
  13112. textureCount = options.textureCount || 1;
  13113. if (options.types) {
  13114. types = options.types;
  13115. }
  13116. if (options.samplingModes) {
  13117. samplingModes = options.samplingModes;
  13118. }
  13119. }
  13120. var gl = this._gl;
  13121. // Create the framebuffer
  13122. var framebuffer = gl.createFramebuffer();
  13123. this.bindUnboundFramebuffer(framebuffer);
  13124. var width = size.width || size;
  13125. var height = size.height || size;
  13126. var textures = [];
  13127. var attachments = [];
  13128. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13129. for (var i = 0; i < textureCount; i++) {
  13130. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13131. var type = types[i] || defaultType;
  13132. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13133. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13134. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13135. }
  13136. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13137. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13138. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13139. }
  13140. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13141. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13142. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13143. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13144. }
  13145. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13146. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13147. textures.push(texture);
  13148. attachments.push(attachment);
  13149. gl.activeTexture(gl["TEXTURE" + i]);
  13150. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13155. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13156. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13157. if (generateMipMaps) {
  13158. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13159. }
  13160. // Unbind
  13161. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13162. texture._framebuffer = framebuffer;
  13163. texture._depthStencilBuffer = depthStencilBuffer;
  13164. texture.baseWidth = width;
  13165. texture.baseHeight = height;
  13166. texture.width = width;
  13167. texture.height = height;
  13168. texture.isReady = true;
  13169. texture.samples = 1;
  13170. texture.generateMipMaps = generateMipMaps;
  13171. texture.samplingMode = samplingMode;
  13172. texture.type = type;
  13173. texture._generateDepthBuffer = generateDepthBuffer;
  13174. texture._generateStencilBuffer = generateStencilBuffer;
  13175. texture._attachments = attachments;
  13176. this._internalTexturesCache.push(texture);
  13177. }
  13178. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13179. // Depth texture
  13180. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13181. gl.activeTexture(gl.TEXTURE0);
  13182. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13187. 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);
  13188. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13189. depthTexture._framebuffer = framebuffer;
  13190. depthTexture.baseWidth = width;
  13191. depthTexture.baseHeight = height;
  13192. depthTexture.width = width;
  13193. depthTexture.height = height;
  13194. depthTexture.isReady = true;
  13195. depthTexture.samples = 1;
  13196. depthTexture.generateMipMaps = generateMipMaps;
  13197. depthTexture.samplingMode = gl.NEAREST;
  13198. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13199. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13200. textures.push(depthTexture);
  13201. this._internalTexturesCache.push(depthTexture);
  13202. }
  13203. gl.drawBuffers(attachments);
  13204. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13205. this.bindUnboundFramebuffer(null);
  13206. this.resetTextureCache();
  13207. return textures;
  13208. };
  13209. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13210. if (samples === void 0) { samples = 1; }
  13211. var depthStencilBuffer = null;
  13212. var gl = this._gl;
  13213. // Create the depth/stencil buffer
  13214. if (generateStencilBuffer) {
  13215. depthStencilBuffer = gl.createRenderbuffer();
  13216. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13217. if (samples > 1) {
  13218. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13219. }
  13220. else {
  13221. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13222. }
  13223. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13224. }
  13225. else if (generateDepthBuffer) {
  13226. depthStencilBuffer = gl.createRenderbuffer();
  13227. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13228. if (samples > 1) {
  13229. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13230. }
  13231. else {
  13232. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13233. }
  13234. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13235. }
  13236. return depthStencilBuffer;
  13237. };
  13238. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13239. if (this.webGLVersion < 2 || !texture) {
  13240. return 1;
  13241. }
  13242. if (texture.samples === samples) {
  13243. return samples;
  13244. }
  13245. var gl = this._gl;
  13246. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13247. // Dispose previous render buffers
  13248. if (texture._depthStencilBuffer) {
  13249. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13250. texture._depthStencilBuffer = null;
  13251. }
  13252. if (texture._MSAAFramebuffer) {
  13253. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13254. texture._MSAAFramebuffer = null;
  13255. }
  13256. if (texture._MSAARenderBuffer) {
  13257. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13258. texture._MSAARenderBuffer = null;
  13259. }
  13260. if (samples > 1) {
  13261. var framebuffer = gl.createFramebuffer();
  13262. if (!framebuffer) {
  13263. throw new Error("Unable to create multi sampled framebuffer");
  13264. }
  13265. texture._MSAAFramebuffer = framebuffer;
  13266. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13267. var colorRenderbuffer = gl.createRenderbuffer();
  13268. if (!colorRenderbuffer) {
  13269. throw new Error("Unable to create multi sampled framebuffer");
  13270. }
  13271. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13272. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13273. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13274. texture._MSAARenderBuffer = colorRenderbuffer;
  13275. }
  13276. else {
  13277. this.bindUnboundFramebuffer(texture._framebuffer);
  13278. }
  13279. texture.samples = samples;
  13280. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13281. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13282. this.bindUnboundFramebuffer(null);
  13283. return samples;
  13284. };
  13285. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13286. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13287. return 1;
  13288. }
  13289. if (textures[0].samples === samples) {
  13290. return samples;
  13291. }
  13292. var gl = this._gl;
  13293. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13294. // Dispose previous render buffers
  13295. if (textures[0]._depthStencilBuffer) {
  13296. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13297. textures[0]._depthStencilBuffer = null;
  13298. }
  13299. if (textures[0]._MSAAFramebuffer) {
  13300. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13301. textures[0]._MSAAFramebuffer = null;
  13302. }
  13303. for (var i = 0; i < textures.length; i++) {
  13304. if (textures[i]._MSAARenderBuffer) {
  13305. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13306. textures[i]._MSAARenderBuffer = null;
  13307. }
  13308. }
  13309. if (samples > 1) {
  13310. var framebuffer = gl.createFramebuffer();
  13311. if (!framebuffer) {
  13312. throw new Error("Unable to create multi sampled framebuffer");
  13313. }
  13314. this.bindUnboundFramebuffer(framebuffer);
  13315. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13316. var attachments = [];
  13317. for (var i = 0; i < textures.length; i++) {
  13318. var texture = textures[i];
  13319. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13320. var colorRenderbuffer = gl.createRenderbuffer();
  13321. if (!colorRenderbuffer) {
  13322. throw new Error("Unable to create multi sampled framebuffer");
  13323. }
  13324. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13325. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13326. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13327. texture._MSAAFramebuffer = framebuffer;
  13328. texture._MSAARenderBuffer = colorRenderbuffer;
  13329. texture.samples = samples;
  13330. texture._depthStencilBuffer = depthStencilBuffer;
  13331. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13332. attachments.push(attachment);
  13333. }
  13334. gl.drawBuffers(attachments);
  13335. }
  13336. else {
  13337. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13338. }
  13339. this.bindUnboundFramebuffer(null);
  13340. return samples;
  13341. };
  13342. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13343. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13344. };
  13345. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13346. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13347. };
  13348. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13349. var gl = this._gl;
  13350. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13351. var generateMipMaps = true;
  13352. var generateDepthBuffer = true;
  13353. var generateStencilBuffer = false;
  13354. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13355. if (options !== undefined) {
  13356. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13357. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13358. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13359. if (options.samplingMode !== undefined) {
  13360. samplingMode = options.samplingMode;
  13361. }
  13362. }
  13363. texture.isCube = true;
  13364. texture.generateMipMaps = generateMipMaps;
  13365. texture.samples = 1;
  13366. texture.samplingMode = samplingMode;
  13367. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13368. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13369. for (var face = 0; face < 6; face++) {
  13370. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13371. }
  13372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13374. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13375. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13376. // Create the framebuffer
  13377. var framebuffer = gl.createFramebuffer();
  13378. this.bindUnboundFramebuffer(framebuffer);
  13379. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13380. // Mipmaps
  13381. if (texture.generateMipMaps) {
  13382. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13383. }
  13384. // Unbind
  13385. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13386. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13387. this.bindUnboundFramebuffer(null);
  13388. texture._framebuffer = framebuffer;
  13389. texture.width = size;
  13390. texture.height = size;
  13391. texture.isReady = true;
  13392. //this.resetTextureCache();
  13393. this._internalTexturesCache.push(texture);
  13394. return texture;
  13395. };
  13396. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13397. var _this = this;
  13398. if (onLoad === void 0) { onLoad = null; }
  13399. if (onError === void 0) { onError = null; }
  13400. if (forcedExtension === void 0) { forcedExtension = null; }
  13401. var callback = function (loadData) {
  13402. if (!loadData) {
  13403. if (onLoad) {
  13404. onLoad(null);
  13405. }
  13406. return;
  13407. }
  13408. var texture = loadData.texture;
  13409. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13410. texture._lodGenerationScale = scale;
  13411. texture._lodGenerationOffset = offset;
  13412. if (_this._caps.textureLOD) {
  13413. // Do not add extra process if texture lod is supported.
  13414. if (onLoad) {
  13415. onLoad(texture);
  13416. }
  13417. return;
  13418. }
  13419. var mipSlices = 3;
  13420. var gl = _this._gl;
  13421. var width = loadData.width;
  13422. if (!width) {
  13423. return;
  13424. }
  13425. var textures = [];
  13426. for (var i = 0; i < mipSlices; i++) {
  13427. //compute LOD from even spacing in smoothness (matching shader calculation)
  13428. var smoothness = i / (mipSlices - 1);
  13429. var roughness = 1 - smoothness;
  13430. var minLODIndex = offset; // roughness = 0
  13431. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13432. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13433. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13434. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13435. glTextureFromLod.isCube = true;
  13436. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13439. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13441. if (loadData.isDDS) {
  13442. var info = loadData.info;
  13443. var data = loadData.data;
  13444. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13445. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13446. }
  13447. else {
  13448. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13449. }
  13450. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13451. // Wrap in a base texture for easy binding.
  13452. var lodTexture = new BABYLON.BaseTexture(scene);
  13453. lodTexture.isCube = true;
  13454. lodTexture._texture = glTextureFromLod;
  13455. glTextureFromLod.isReady = true;
  13456. textures.push(lodTexture);
  13457. }
  13458. texture._lodTextureHigh = textures[2];
  13459. texture._lodTextureMid = textures[1];
  13460. texture._lodTextureLow = textures[0];
  13461. if (onLoad) {
  13462. onLoad(texture);
  13463. }
  13464. };
  13465. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13466. };
  13467. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13468. var _this = this;
  13469. if (onLoad === void 0) { onLoad = null; }
  13470. if (onError === void 0) { onError = null; }
  13471. if (forcedExtension === void 0) { forcedExtension = null; }
  13472. var gl = this._gl;
  13473. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13474. texture.isCube = true;
  13475. texture.url = rootUrl;
  13476. texture.generateMipMaps = !noMipmap;
  13477. if (!this._doNotHandleContextLost) {
  13478. texture._extension = forcedExtension;
  13479. texture._files = files;
  13480. }
  13481. var isKTX = false;
  13482. var isDDS = false;
  13483. var lastDot = rootUrl.lastIndexOf('.');
  13484. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13485. if (this._textureFormatInUse) {
  13486. extension = this._textureFormatInUse;
  13487. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13488. isKTX = true;
  13489. }
  13490. else {
  13491. isDDS = (extension === ".dds");
  13492. }
  13493. var onerror = function (request, exception) {
  13494. if (onError && request) {
  13495. onError(request.status + " " + request.statusText, exception);
  13496. }
  13497. };
  13498. if (isKTX) {
  13499. this._loadFile(rootUrl, function (data) {
  13500. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13501. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13502. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13503. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13504. ktx.uploadLevels(_this._gl, !noMipmap);
  13505. _this.setCubeMapTextureParams(gl, loadMipmap);
  13506. texture.width = ktx.pixelWidth;
  13507. texture.height = ktx.pixelHeight;
  13508. texture.isReady = true;
  13509. }, undefined, undefined, true, onerror);
  13510. }
  13511. else if (isDDS) {
  13512. if (files && files.length === 6) {
  13513. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13514. var info;
  13515. var loadMipmap = false;
  13516. var width = 0;
  13517. for (var index = 0; index < imgs.length; index++) {
  13518. var data = imgs[index];
  13519. info = BABYLON.DDSTools.GetDDSInfo(data);
  13520. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13521. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13522. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13523. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13524. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13525. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13526. }
  13527. texture.width = info.width;
  13528. texture.height = info.height;
  13529. texture.type = info.textureType;
  13530. width = info.width;
  13531. }
  13532. _this.setCubeMapTextureParams(gl, loadMipmap);
  13533. texture.isReady = true;
  13534. if (onLoad) {
  13535. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13536. }
  13537. }, files, onError);
  13538. }
  13539. else {
  13540. this._loadFile(rootUrl, function (data) {
  13541. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13542. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13543. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13544. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13545. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13546. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13547. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13548. }
  13549. _this.setCubeMapTextureParams(gl, loadMipmap);
  13550. texture.width = info.width;
  13551. texture.height = info.height;
  13552. texture.isReady = true;
  13553. texture.type = info.textureType;
  13554. if (onLoad) {
  13555. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13556. }
  13557. }, undefined, undefined, true, onerror);
  13558. }
  13559. }
  13560. else {
  13561. if (!files) {
  13562. throw new Error("Cannot load cubemap because files were not defined");
  13563. }
  13564. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13565. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13566. var height = width;
  13567. _this._prepareWorkingCanvas();
  13568. if (!_this._workingCanvas || !_this._workingContext) {
  13569. return;
  13570. }
  13571. _this._workingCanvas.width = width;
  13572. _this._workingCanvas.height = height;
  13573. var faces = [
  13574. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13575. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13576. ];
  13577. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13578. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13579. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13580. for (var index = 0; index < faces.length; index++) {
  13581. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13582. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13583. }
  13584. if (!noMipmap) {
  13585. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13586. }
  13587. _this.setCubeMapTextureParams(gl, !noMipmap);
  13588. texture.width = width;
  13589. texture.height = height;
  13590. texture.isReady = true;
  13591. if (format) {
  13592. texture.format = format;
  13593. }
  13594. texture.onLoadedObservable.notifyObservers(texture);
  13595. texture.onLoadedObservable.clear();
  13596. if (onLoad) {
  13597. onLoad();
  13598. }
  13599. }, files, onError);
  13600. }
  13601. this._internalTexturesCache.push(texture);
  13602. return texture;
  13603. };
  13604. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13605. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13609. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13610. // this.resetTextureCache();
  13611. };
  13612. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13613. if (compression === void 0) { compression = null; }
  13614. if (level === void 0) { level = 0; }
  13615. texture._bufferViewArray = data;
  13616. texture.format = format;
  13617. texture.type = type;
  13618. texture.invertY = invertY;
  13619. texture._compression = compression;
  13620. var gl = this._gl;
  13621. var textureType = this._getWebGLTextureType(type);
  13622. var internalFormat = this._getInternalFormat(format);
  13623. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13624. var needConversion = false;
  13625. if (internalFormat === gl.RGB) {
  13626. internalFormat = gl.RGBA;
  13627. needConversion = true;
  13628. }
  13629. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13630. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13631. if (texture.width % 4 !== 0) {
  13632. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13633. }
  13634. // Data are known to be in +X +Y +Z -X -Y -Z
  13635. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13636. var faceData = data[faceIndex];
  13637. if (compression) {
  13638. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13639. }
  13640. else {
  13641. if (needConversion) {
  13642. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13643. }
  13644. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13645. }
  13646. }
  13647. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13648. if (isPot && texture.generateMipMaps && level === 0) {
  13649. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13650. }
  13651. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13652. // this.resetTextureCache();
  13653. texture.isReady = true;
  13654. };
  13655. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13656. if (compression === void 0) { compression = null; }
  13657. var gl = this._gl;
  13658. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13659. texture.isCube = true;
  13660. texture.generateMipMaps = generateMipMaps;
  13661. texture.format = format;
  13662. texture.type = type;
  13663. if (!this._doNotHandleContextLost) {
  13664. texture._bufferViewArray = data;
  13665. }
  13666. var textureType = this._getWebGLTextureType(type);
  13667. var internalFormat = this._getInternalFormat(format);
  13668. if (internalFormat === gl.RGB) {
  13669. internalFormat = gl.RGBA;
  13670. }
  13671. var width = size;
  13672. var height = width;
  13673. texture.width = width;
  13674. texture.height = height;
  13675. // Double check on POT to generate Mips.
  13676. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13677. if (!isPot) {
  13678. generateMipMaps = false;
  13679. }
  13680. // Upload data if needed. The texture won't be ready until then.
  13681. if (data) {
  13682. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13683. }
  13684. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13685. // Filters
  13686. if (data && generateMipMaps) {
  13687. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13688. }
  13689. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13692. }
  13693. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13696. }
  13697. else {
  13698. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13701. }
  13702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13704. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13705. return texture;
  13706. };
  13707. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13708. var _this = this;
  13709. if (onLoad === void 0) { onLoad = null; }
  13710. if (onError === void 0) { onError = null; }
  13711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13712. if (invertY === void 0) { invertY = false; }
  13713. var gl = this._gl;
  13714. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13715. scene._addPendingData(texture);
  13716. texture.url = url;
  13717. this._internalTexturesCache.push(texture);
  13718. var onerror = function (request, exception) {
  13719. scene._removePendingData(texture);
  13720. if (onError && request) {
  13721. onError(request.status + " " + request.statusText, exception);
  13722. }
  13723. };
  13724. var internalCallback = function (data) {
  13725. var width = texture.width;
  13726. var faceDataArrays = callback(data);
  13727. if (!faceDataArrays) {
  13728. return;
  13729. }
  13730. if (mipmmapGenerator) {
  13731. var textureType = _this._getWebGLTextureType(type);
  13732. var internalFormat = _this._getInternalFormat(format);
  13733. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13734. var needConversion = false;
  13735. if (internalFormat === gl.RGB) {
  13736. internalFormat = gl.RGBA;
  13737. needConversion = true;
  13738. }
  13739. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13740. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13741. var mipData = mipmmapGenerator(faceDataArrays);
  13742. for (var level = 0; level < mipData.length; level++) {
  13743. var mipSize = width >> level;
  13744. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13745. var mipFaceData = mipData[level][faceIndex];
  13746. if (needConversion) {
  13747. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13748. }
  13749. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13750. }
  13751. }
  13752. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13753. }
  13754. else {
  13755. texture.generateMipMaps = !noMipmap;
  13756. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13757. }
  13758. texture.isReady = true;
  13759. // this.resetTextureCache();
  13760. scene._removePendingData(texture);
  13761. if (onLoad) {
  13762. onLoad();
  13763. }
  13764. };
  13765. this._loadFile(url, function (data) {
  13766. internalCallback(data);
  13767. }, undefined, scene.database, true, onerror);
  13768. return texture;
  13769. };
  13770. ;
  13771. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13772. if (compression === void 0) { compression = null; }
  13773. var internalFormat = this._getInternalFormat(format);
  13774. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13775. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13776. if (!this._doNotHandleContextLost) {
  13777. texture._bufferView = data;
  13778. texture.format = format;
  13779. texture.invertY = invertY;
  13780. texture._compression = compression;
  13781. }
  13782. if (texture.width % 4 !== 0) {
  13783. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13784. }
  13785. if (compression && data) {
  13786. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13787. }
  13788. else {
  13789. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13790. }
  13791. if (texture.generateMipMaps) {
  13792. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13793. }
  13794. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13795. // this.resetTextureCache();
  13796. texture.isReady = true;
  13797. };
  13798. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13799. if (compression === void 0) { compression = null; }
  13800. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13801. texture.baseWidth = width;
  13802. texture.baseHeight = height;
  13803. texture.baseDepth = depth;
  13804. texture.width = width;
  13805. texture.height = height;
  13806. texture.depth = depth;
  13807. texture.format = format;
  13808. texture.generateMipMaps = generateMipMaps;
  13809. texture.samplingMode = samplingMode;
  13810. texture.is3D = true;
  13811. if (!this._doNotHandleContextLost) {
  13812. texture._bufferView = data;
  13813. }
  13814. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13815. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13816. // Filters
  13817. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13818. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13819. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13820. if (generateMipMaps) {
  13821. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13822. }
  13823. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13824. this._internalTexturesCache.push(texture);
  13825. return texture;
  13826. };
  13827. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13828. var gl = this._gl;
  13829. if (!gl) {
  13830. return;
  13831. }
  13832. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13833. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13835. if (!noMipmap && !isCompressed) {
  13836. gl.generateMipmap(gl.TEXTURE_2D);
  13837. }
  13838. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13839. // this.resetTextureCache();
  13840. if (scene) {
  13841. scene._removePendingData(texture);
  13842. }
  13843. texture.onLoadedObservable.notifyObservers(texture);
  13844. texture.onLoadedObservable.clear();
  13845. };
  13846. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13847. var _this = this;
  13848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13849. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13850. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13851. var gl = this._gl;
  13852. if (!gl) {
  13853. return;
  13854. }
  13855. if (!texture._webGLTexture) {
  13856. // this.resetTextureCache();
  13857. if (scene) {
  13858. scene._removePendingData(texture);
  13859. }
  13860. return;
  13861. }
  13862. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13863. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13864. texture.baseWidth = width;
  13865. texture.baseHeight = height;
  13866. texture.width = potWidth;
  13867. texture.height = potHeight;
  13868. texture.isReady = true;
  13869. if (processFunction(potWidth, potHeight, function () {
  13870. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13871. })) {
  13872. // Returning as texture needs extra async steps
  13873. return;
  13874. }
  13875. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13876. };
  13877. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13878. // Create new RGBA data container.
  13879. var rgbaData;
  13880. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13881. rgbaData = new Float32Array(width * height * 4);
  13882. }
  13883. else {
  13884. rgbaData = new Uint32Array(width * height * 4);
  13885. }
  13886. // Convert each pixel.
  13887. for (var x = 0; x < width; x++) {
  13888. for (var y = 0; y < height; y++) {
  13889. var index = (y * width + x) * 3;
  13890. var newIndex = (y * width + x) * 4;
  13891. // Map Old Value to new value.
  13892. rgbaData[newIndex + 0] = rgbData[index + 0];
  13893. rgbaData[newIndex + 1] = rgbData[index + 1];
  13894. rgbaData[newIndex + 2] = rgbData[index + 2];
  13895. // Add fully opaque alpha channel.
  13896. rgbaData[newIndex + 3] = 1;
  13897. }
  13898. }
  13899. return rgbaData;
  13900. };
  13901. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13902. var gl = this._gl;
  13903. if (texture._framebuffer) {
  13904. gl.deleteFramebuffer(texture._framebuffer);
  13905. texture._framebuffer = null;
  13906. }
  13907. if (texture._depthStencilBuffer) {
  13908. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13909. texture._depthStencilBuffer = null;
  13910. }
  13911. if (texture._MSAAFramebuffer) {
  13912. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13913. texture._MSAAFramebuffer = null;
  13914. }
  13915. if (texture._MSAARenderBuffer) {
  13916. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13917. texture._MSAARenderBuffer = null;
  13918. }
  13919. };
  13920. Engine.prototype._releaseTexture = function (texture) {
  13921. var gl = this._gl;
  13922. this._releaseFramebufferObjects(texture);
  13923. gl.deleteTexture(texture._webGLTexture);
  13924. // Unbind channels
  13925. this.unbindAllTextures();
  13926. var index = this._internalTexturesCache.indexOf(texture);
  13927. if (index !== -1) {
  13928. this._internalTexturesCache.splice(index, 1);
  13929. }
  13930. // Integrated fixed lod samplers.
  13931. if (texture._lodTextureHigh) {
  13932. texture._lodTextureHigh.dispose();
  13933. }
  13934. if (texture._lodTextureMid) {
  13935. texture._lodTextureMid.dispose();
  13936. }
  13937. if (texture._lodTextureLow) {
  13938. texture._lodTextureLow.dispose();
  13939. }
  13940. };
  13941. Engine.prototype.setProgram = function (program) {
  13942. if (this._currentProgram !== program) {
  13943. this._gl.useProgram(program);
  13944. this._currentProgram = program;
  13945. }
  13946. };
  13947. Engine.prototype.bindSamplers = function (effect) {
  13948. this.setProgram(effect.getProgram());
  13949. var samplers = effect.getSamplers();
  13950. for (var index = 0; index < samplers.length; index++) {
  13951. var uniform = effect.getUniform(samplers[index]);
  13952. if (uniform) {
  13953. this._boundUniforms[index] = uniform;
  13954. }
  13955. }
  13956. this._currentEffect = null;
  13957. };
  13958. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13959. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13960. return;
  13961. }
  13962. // Remove
  13963. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13964. // Bind last to it
  13965. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13966. // Bind to dummy
  13967. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13968. };
  13969. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13970. if (!internalTexture) {
  13971. return -1;
  13972. }
  13973. internalTexture._initialSlot = channel;
  13974. if (this.disableTextureBindingOptimization) {
  13975. if (channel !== internalTexture._designatedSlot) {
  13976. this._textureCollisions.addCount(1, false);
  13977. }
  13978. }
  13979. else {
  13980. if (channel !== internalTexture._designatedSlot) {
  13981. if (internalTexture._designatedSlot > -1) {
  13982. return internalTexture._designatedSlot;
  13983. }
  13984. else {
  13985. // No slot for this texture, let's pick a new one (if we find a free slot)
  13986. if (this._nextFreeTextureSlots.length) {
  13987. return this._nextFreeTextureSlots[0];
  13988. }
  13989. // We need to recycle the oldest bound texture, sorry.
  13990. this._textureCollisions.addCount(1, false);
  13991. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13992. }
  13993. }
  13994. }
  13995. return channel;
  13996. };
  13997. Engine.prototype._linkTrackers = function (previous, next) {
  13998. previous.next = next;
  13999. next.previous = previous;
  14000. };
  14001. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14002. var currentSlot = internalTexture._designatedSlot;
  14003. if (currentSlot === -1) {
  14004. return -1;
  14005. }
  14006. internalTexture._designatedSlot = -1;
  14007. if (this.disableTextureBindingOptimization) {
  14008. return -1;
  14009. }
  14010. // Remove from bound list
  14011. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14012. // Free the slot
  14013. this._boundTexturesCache[currentSlot] = null;
  14014. this._nextFreeTextureSlots.push(currentSlot);
  14015. return currentSlot;
  14016. };
  14017. Engine.prototype._activateCurrentTexture = function () {
  14018. if (this._currentTextureChannel !== this._activeChannel) {
  14019. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14020. this._currentTextureChannel = this._activeChannel;
  14021. }
  14022. };
  14023. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14024. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14025. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14026. this._activeChannel = texture._designatedSlot;
  14027. }
  14028. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14029. var isTextureForRendering = texture && texture._initialSlot > -1;
  14030. if (currentTextureBound !== texture) {
  14031. if (currentTextureBound) {
  14032. this._removeDesignatedSlot(currentTextureBound);
  14033. }
  14034. this._activateCurrentTexture();
  14035. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14036. this._boundTexturesCache[this._activeChannel] = texture;
  14037. if (texture) {
  14038. if (!this.disableTextureBindingOptimization) {
  14039. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14040. if (slotIndex > -1) {
  14041. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14042. }
  14043. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14044. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14045. }
  14046. texture._designatedSlot = this._activeChannel;
  14047. }
  14048. }
  14049. else if (forTextureDataUpdate) {
  14050. this._activateCurrentTexture();
  14051. }
  14052. if (isTextureForRendering && !forTextureDataUpdate) {
  14053. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14054. }
  14055. };
  14056. Engine.prototype._bindTexture = function (channel, texture) {
  14057. if (channel < 0) {
  14058. return;
  14059. }
  14060. if (texture) {
  14061. channel = this._getCorrectTextureChannel(channel, texture);
  14062. }
  14063. this._activeChannel = channel;
  14064. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14065. };
  14066. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14067. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14068. };
  14069. Engine.prototype.unbindAllTextures = function () {
  14070. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14071. this._activeChannel = channel;
  14072. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14073. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14074. if (this.webGLVersion > 1) {
  14075. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14076. }
  14077. }
  14078. };
  14079. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14080. if (channel < 0) {
  14081. return;
  14082. }
  14083. if (uniform) {
  14084. this._boundUniforms[channel] = uniform;
  14085. }
  14086. this._setTexture(channel, texture);
  14087. };
  14088. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14089. var uniform = this._boundUniforms[sourceSlot];
  14090. if (uniform._currentState === destination) {
  14091. return;
  14092. }
  14093. this._gl.uniform1i(uniform, destination);
  14094. uniform._currentState = destination;
  14095. };
  14096. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14097. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14098. // Not ready?
  14099. if (!texture) {
  14100. if (this._boundTexturesCache[channel] != null) {
  14101. this._activeChannel = channel;
  14102. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14103. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14104. if (this.webGLVersion > 1) {
  14105. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14106. }
  14107. }
  14108. return false;
  14109. }
  14110. // Video
  14111. if (texture.video) {
  14112. this._activeChannel = channel;
  14113. texture.update();
  14114. }
  14115. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14116. texture.delayLoad();
  14117. return false;
  14118. }
  14119. var internalTexture;
  14120. if (texture.isReady()) {
  14121. internalTexture = texture.getInternalTexture();
  14122. }
  14123. else if (texture.isCube) {
  14124. internalTexture = this.emptyCubeTexture;
  14125. }
  14126. else if (texture.is3D) {
  14127. internalTexture = this.emptyTexture3D;
  14128. }
  14129. else {
  14130. internalTexture = this.emptyTexture;
  14131. }
  14132. if (!isPartOfTextureArray) {
  14133. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14134. }
  14135. if (this._boundTexturesCache[channel] === internalTexture) {
  14136. this._moveBoundTextureOnTop(internalTexture);
  14137. if (!isPartOfTextureArray) {
  14138. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14139. }
  14140. return false;
  14141. }
  14142. this._activeChannel = channel;
  14143. if (internalTexture && internalTexture.is3D) {
  14144. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14145. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14146. internalTexture._cachedWrapU = texture.wrapU;
  14147. switch (texture.wrapU) {
  14148. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14149. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14150. break;
  14151. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14152. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14153. break;
  14154. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14155. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14156. break;
  14157. }
  14158. }
  14159. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14160. internalTexture._cachedWrapV = texture.wrapV;
  14161. switch (texture.wrapV) {
  14162. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14163. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14164. break;
  14165. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14166. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14167. break;
  14168. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14169. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14170. break;
  14171. }
  14172. }
  14173. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14174. internalTexture._cachedWrapR = texture.wrapR;
  14175. switch (texture.wrapR) {
  14176. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14177. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14178. break;
  14179. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14180. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14181. break;
  14182. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14183. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14184. break;
  14185. }
  14186. }
  14187. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14188. }
  14189. else if (internalTexture && internalTexture.isCube) {
  14190. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14191. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14192. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14193. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14194. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14195. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14196. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14197. }
  14198. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14199. }
  14200. else {
  14201. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14202. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14203. internalTexture._cachedWrapU = texture.wrapU;
  14204. switch (texture.wrapU) {
  14205. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14207. break;
  14208. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14210. break;
  14211. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14212. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14213. break;
  14214. }
  14215. }
  14216. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14217. internalTexture._cachedWrapV = texture.wrapV;
  14218. switch (texture.wrapV) {
  14219. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14220. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14221. break;
  14222. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14223. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14224. break;
  14225. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14226. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14227. break;
  14228. }
  14229. }
  14230. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14231. }
  14232. return true;
  14233. };
  14234. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14235. if (channel < 0 || !uniform) {
  14236. return;
  14237. }
  14238. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14239. this._textureUnits = new Int32Array(textures.length);
  14240. }
  14241. for (var i = 0; i < textures.length; i++) {
  14242. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14243. }
  14244. this._gl.uniform1iv(uniform, this._textureUnits);
  14245. for (var index = 0; index < textures.length; index++) {
  14246. this._setTexture(this._textureUnits[index], textures[index], true);
  14247. }
  14248. };
  14249. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14250. var internalTexture = texture.getInternalTexture();
  14251. if (!internalTexture) {
  14252. return;
  14253. }
  14254. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14255. var value = texture.anisotropicFilteringLevel;
  14256. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14257. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14258. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14259. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14260. }
  14261. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14262. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14263. internalTexture._cachedAnisotropicFilteringLevel = value;
  14264. }
  14265. };
  14266. Engine.prototype.readPixels = function (x, y, width, height) {
  14267. var data = new Uint8Array(height * width * 4);
  14268. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14269. return data;
  14270. };
  14271. /**
  14272. * Add an externaly attached data from its key.
  14273. * This method call will fail and return false, if such key already exists.
  14274. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14275. * @param key the unique key that identifies the data
  14276. * @param data the data object to associate to the key for this Engine instance
  14277. * @return true if no such key were already present and the data was added successfully, false otherwise
  14278. */
  14279. Engine.prototype.addExternalData = function (key, data) {
  14280. if (!this._externalData) {
  14281. this._externalData = new BABYLON.StringDictionary();
  14282. }
  14283. return this._externalData.add(key, data);
  14284. };
  14285. /**
  14286. * Get an externaly attached data from its key
  14287. * @param key the unique key that identifies the data
  14288. * @return the associated data, if present (can be null), or undefined if not present
  14289. */
  14290. Engine.prototype.getExternalData = function (key) {
  14291. if (!this._externalData) {
  14292. this._externalData = new BABYLON.StringDictionary();
  14293. }
  14294. return this._externalData.get(key);
  14295. };
  14296. /**
  14297. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14298. * @param key the unique key that identifies the data
  14299. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14300. * @return the associated data, can be null if the factory returned null.
  14301. */
  14302. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14303. if (!this._externalData) {
  14304. this._externalData = new BABYLON.StringDictionary();
  14305. }
  14306. return this._externalData.getOrAddWithFactory(key, factory);
  14307. };
  14308. /**
  14309. * Remove an externaly attached data from the Engine instance
  14310. * @param key the unique key that identifies the data
  14311. * @return true if the data was successfully removed, false if it doesn't exist
  14312. */
  14313. Engine.prototype.removeExternalData = function (key) {
  14314. if (!this._externalData) {
  14315. this._externalData = new BABYLON.StringDictionary();
  14316. }
  14317. return this._externalData.remove(key);
  14318. };
  14319. Engine.prototype.unbindAllAttributes = function () {
  14320. if (this._mustWipeVertexAttributes) {
  14321. this._mustWipeVertexAttributes = false;
  14322. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14323. this._gl.disableVertexAttribArray(i);
  14324. this._vertexAttribArraysEnabled[i] = false;
  14325. this._currentBufferPointers[i].active = false;
  14326. }
  14327. return;
  14328. }
  14329. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14330. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14331. continue;
  14332. }
  14333. this._gl.disableVertexAttribArray(i);
  14334. this._vertexAttribArraysEnabled[i] = false;
  14335. this._currentBufferPointers[i].active = false;
  14336. }
  14337. };
  14338. Engine.prototype.releaseEffects = function () {
  14339. for (var name in this._compiledEffects) {
  14340. this._deleteProgram(this._compiledEffects[name]._program);
  14341. }
  14342. this._compiledEffects = {};
  14343. };
  14344. // Dispose
  14345. Engine.prototype.dispose = function () {
  14346. this.hideLoadingUI();
  14347. this.stopRenderLoop();
  14348. // Release postProcesses
  14349. while (this.postProcesses.length) {
  14350. this.postProcesses[0].dispose();
  14351. }
  14352. // Empty texture
  14353. if (this._emptyTexture) {
  14354. this._releaseTexture(this._emptyTexture);
  14355. this._emptyTexture = null;
  14356. }
  14357. if (this._emptyCubeTexture) {
  14358. this._releaseTexture(this._emptyCubeTexture);
  14359. this._emptyCubeTexture = null;
  14360. }
  14361. // Rescale PP
  14362. if (this._rescalePostProcess) {
  14363. this._rescalePostProcess.dispose();
  14364. }
  14365. // Release scenes
  14366. while (this.scenes.length) {
  14367. this.scenes[0].dispose();
  14368. }
  14369. // Release audio engine
  14370. if (Engine.audioEngine) {
  14371. Engine.audioEngine.dispose();
  14372. }
  14373. // Release effects
  14374. this.releaseEffects();
  14375. // Unbind
  14376. this.unbindAllAttributes();
  14377. if (this._dummyFramebuffer) {
  14378. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14379. }
  14380. //WebVR
  14381. this.disableVR();
  14382. // Events
  14383. if (BABYLON.Tools.IsWindowObjectExist()) {
  14384. window.removeEventListener("blur", this._onBlur);
  14385. window.removeEventListener("focus", this._onFocus);
  14386. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14387. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14388. if (this._renderingCanvas) {
  14389. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14390. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14391. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14392. if (!this._doNotHandleContextLost) {
  14393. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14394. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14395. }
  14396. }
  14397. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14398. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14399. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14400. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14401. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14402. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14403. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14404. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14405. if (this._onVrDisplayConnect) {
  14406. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14407. if (this._onVrDisplayDisconnect) {
  14408. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14409. }
  14410. if (this._onVrDisplayPresentChange) {
  14411. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14412. }
  14413. this._onVrDisplayConnect = null;
  14414. this._onVrDisplayDisconnect = null;
  14415. }
  14416. }
  14417. // Remove from Instances
  14418. var index = Engine.Instances.indexOf(this);
  14419. if (index >= 0) {
  14420. Engine.Instances.splice(index, 1);
  14421. }
  14422. this._workingCanvas = null;
  14423. this._workingContext = null;
  14424. this._currentBufferPointers = [];
  14425. this._renderingCanvas = null;
  14426. this._currentProgram = null;
  14427. this.onResizeObservable.clear();
  14428. this.onCanvasBlurObservable.clear();
  14429. this.onCanvasFocusObservable.clear();
  14430. this.onCanvasPointerOutObservable.clear();
  14431. this.onBeginFrameObservable.clear();
  14432. this.onEndFrameObservable.clear();
  14433. BABYLON.Effect.ResetCache();
  14434. // Abort active requests
  14435. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14436. var request = _a[_i];
  14437. request.abort();
  14438. }
  14439. };
  14440. // Loading screen
  14441. Engine.prototype.displayLoadingUI = function () {
  14442. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14443. return;
  14444. }
  14445. var loadingScreen = this.loadingScreen;
  14446. if (loadingScreen) {
  14447. loadingScreen.displayLoadingUI();
  14448. }
  14449. };
  14450. Engine.prototype.hideLoadingUI = function () {
  14451. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14452. return;
  14453. }
  14454. var loadingScreen = this.loadingScreen;
  14455. if (loadingScreen) {
  14456. loadingScreen.hideLoadingUI();
  14457. }
  14458. };
  14459. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14460. get: function () {
  14461. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14462. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14463. return this._loadingScreen;
  14464. },
  14465. set: function (loadingScreen) {
  14466. this._loadingScreen = loadingScreen;
  14467. },
  14468. enumerable: true,
  14469. configurable: true
  14470. });
  14471. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14472. set: function (text) {
  14473. this.loadingScreen.loadingUIText = text;
  14474. },
  14475. enumerable: true,
  14476. configurable: true
  14477. });
  14478. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14479. set: function (color) {
  14480. this.loadingScreen.loadingUIBackgroundColor = color;
  14481. },
  14482. enumerable: true,
  14483. configurable: true
  14484. });
  14485. Engine.prototype.attachContextLostEvent = function (callback) {
  14486. if (this._renderingCanvas) {
  14487. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14488. }
  14489. };
  14490. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14491. if (this._renderingCanvas) {
  14492. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14493. }
  14494. };
  14495. Engine.prototype.getVertexShaderSource = function (program) {
  14496. var shaders = this._gl.getAttachedShaders(program);
  14497. if (!shaders) {
  14498. return null;
  14499. }
  14500. return this._gl.getShaderSource(shaders[0]);
  14501. };
  14502. Engine.prototype.getFragmentShaderSource = function (program) {
  14503. var shaders = this._gl.getAttachedShaders(program);
  14504. if (!shaders) {
  14505. return null;
  14506. }
  14507. return this._gl.getShaderSource(shaders[1]);
  14508. };
  14509. Engine.prototype.getError = function () {
  14510. return this._gl.getError();
  14511. };
  14512. // FPS
  14513. Engine.prototype.getFps = function () {
  14514. return this._fps;
  14515. };
  14516. Engine.prototype.getDeltaTime = function () {
  14517. return this._deltaTime;
  14518. };
  14519. Engine.prototype._measureFps = function () {
  14520. this._performanceMonitor.sampleFrame();
  14521. this._fps = this._performanceMonitor.averageFPS;
  14522. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14523. };
  14524. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14525. if (faceIndex === void 0) { faceIndex = -1; }
  14526. var gl = this._gl;
  14527. if (!this._dummyFramebuffer) {
  14528. var dummy = gl.createFramebuffer();
  14529. if (!dummy) {
  14530. throw new Error("Unable to create dummy framebuffer");
  14531. }
  14532. this._dummyFramebuffer = dummy;
  14533. }
  14534. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14535. if (faceIndex > -1) {
  14536. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14537. }
  14538. else {
  14539. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14540. }
  14541. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14542. var buffer;
  14543. switch (readType) {
  14544. case gl.UNSIGNED_BYTE:
  14545. buffer = new Uint8Array(4 * width * height);
  14546. readType = gl.UNSIGNED_BYTE;
  14547. break;
  14548. default:
  14549. buffer = new Float32Array(4 * width * height);
  14550. readType = gl.FLOAT;
  14551. break;
  14552. }
  14553. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14554. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14555. return buffer;
  14556. };
  14557. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14558. if (this._webGLVersion > 1) {
  14559. return this._caps.colorBufferFloat;
  14560. }
  14561. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14562. };
  14563. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14564. if (this._webGLVersion > 1) {
  14565. return this._caps.colorBufferFloat;
  14566. }
  14567. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14568. };
  14569. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14570. Engine.prototype._canRenderToFramebuffer = function (type) {
  14571. var gl = this._gl;
  14572. //clear existing errors
  14573. while (gl.getError() !== gl.NO_ERROR) { }
  14574. var successful = true;
  14575. var texture = gl.createTexture();
  14576. gl.bindTexture(gl.TEXTURE_2D, texture);
  14577. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14580. var fb = gl.createFramebuffer();
  14581. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14582. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14583. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14584. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14585. successful = successful && (gl.getError() === gl.NO_ERROR);
  14586. //try render by clearing frame buffer's color buffer
  14587. if (successful) {
  14588. gl.clear(gl.COLOR_BUFFER_BIT);
  14589. successful = successful && (gl.getError() === gl.NO_ERROR);
  14590. }
  14591. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14592. if (successful) {
  14593. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14594. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14595. var readFormat = gl.RGBA;
  14596. var readType = gl.UNSIGNED_BYTE;
  14597. var buffer = new Uint8Array(4);
  14598. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14599. successful = successful && (gl.getError() === gl.NO_ERROR);
  14600. }
  14601. //clean up
  14602. gl.deleteTexture(texture);
  14603. gl.deleteFramebuffer(fb);
  14604. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14605. //clear accumulated errors
  14606. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14607. return successful;
  14608. };
  14609. Engine.prototype._getWebGLTextureType = function (type) {
  14610. if (type === Engine.TEXTURETYPE_FLOAT) {
  14611. return this._gl.FLOAT;
  14612. }
  14613. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14614. // Add Half Float Constant.
  14615. return this._gl.HALF_FLOAT_OES;
  14616. }
  14617. return this._gl.UNSIGNED_BYTE;
  14618. };
  14619. ;
  14620. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14621. if (this._webGLVersion === 1) {
  14622. return this._gl.RGBA;
  14623. }
  14624. if (type === Engine.TEXTURETYPE_FLOAT) {
  14625. return this._gl.RGBA32F;
  14626. }
  14627. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14628. return this._gl.RGBA16F;
  14629. }
  14630. return this._gl.RGBA;
  14631. };
  14632. ;
  14633. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14634. if (type === Engine.TEXTURETYPE_FLOAT) {
  14635. return this._gl.RGBA32F;
  14636. }
  14637. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14638. return this._gl.RGBA16F;
  14639. }
  14640. return this._gl.RGBA8;
  14641. };
  14642. ;
  14643. Engine.prototype.createQuery = function () {
  14644. return this._gl.createQuery();
  14645. };
  14646. Engine.prototype.deleteQuery = function (query) {
  14647. this._gl.deleteQuery(query);
  14648. return this;
  14649. };
  14650. Engine.prototype.isQueryResultAvailable = function (query) {
  14651. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14652. };
  14653. Engine.prototype.getQueryResult = function (query) {
  14654. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14655. };
  14656. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14657. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14658. this._gl.beginQuery(glAlgorithm, query);
  14659. return this;
  14660. };
  14661. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14662. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14663. this._gl.endQuery(glAlgorithm);
  14664. return this;
  14665. };
  14666. /* Time queries */
  14667. Engine.prototype._createTimeQuery = function () {
  14668. var timerQuery = this._caps.timerQuery;
  14669. if (timerQuery.createQueryEXT) {
  14670. return timerQuery.createQueryEXT();
  14671. }
  14672. return this.createQuery();
  14673. };
  14674. Engine.prototype._deleteTimeQuery = function (query) {
  14675. var timerQuery = this._caps.timerQuery;
  14676. if (timerQuery.deleteQueryEXT) {
  14677. timerQuery.deleteQueryEXT(query);
  14678. return;
  14679. }
  14680. this.deleteQuery(query);
  14681. };
  14682. Engine.prototype._getTimeQueryResult = function (query) {
  14683. var timerQuery = this._caps.timerQuery;
  14684. if (timerQuery.getQueryObjectEXT) {
  14685. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14686. }
  14687. return this.getQueryResult(query);
  14688. };
  14689. Engine.prototype._getTimeQueryAvailability = function (query) {
  14690. var timerQuery = this._caps.timerQuery;
  14691. if (timerQuery.getQueryObjectEXT) {
  14692. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14693. }
  14694. return this.isQueryResultAvailable(query);
  14695. };
  14696. Engine.prototype.startTimeQuery = function () {
  14697. var timerQuery = this._caps.timerQuery;
  14698. if (!timerQuery) {
  14699. return null;
  14700. }
  14701. var token = new BABYLON._TimeToken();
  14702. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14703. if (this._caps.canUseTimestampForTimerQuery) {
  14704. token._startTimeQuery = this._createTimeQuery();
  14705. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14706. }
  14707. else {
  14708. if (this._currentNonTimestampToken) {
  14709. return this._currentNonTimestampToken;
  14710. }
  14711. token._timeElapsedQuery = this._createTimeQuery();
  14712. if (timerQuery.beginQueryEXT) {
  14713. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14714. }
  14715. else {
  14716. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14717. }
  14718. this._currentNonTimestampToken = token;
  14719. }
  14720. return token;
  14721. };
  14722. Engine.prototype.endTimeQuery = function (token) {
  14723. var timerQuery = this._caps.timerQuery;
  14724. if (!timerQuery || !token) {
  14725. return -1;
  14726. }
  14727. if (this._caps.canUseTimestampForTimerQuery) {
  14728. if (!token._startTimeQuery) {
  14729. return -1;
  14730. }
  14731. if (!token._endTimeQuery) {
  14732. token._endTimeQuery = this._createTimeQuery();
  14733. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14734. }
  14735. }
  14736. else if (!token._timeElapsedQueryEnded) {
  14737. if (!token._timeElapsedQuery) {
  14738. return -1;
  14739. }
  14740. if (timerQuery.endQueryEXT) {
  14741. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14742. }
  14743. else {
  14744. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14745. }
  14746. token._timeElapsedQueryEnded = true;
  14747. }
  14748. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14749. var available = false;
  14750. if (token._endTimeQuery) {
  14751. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14752. }
  14753. else if (token._timeElapsedQuery) {
  14754. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14755. }
  14756. if (available && !disjoint) {
  14757. var result = 0;
  14758. if (this._caps.canUseTimestampForTimerQuery) {
  14759. if (!token._startTimeQuery || !token._endTimeQuery) {
  14760. return -1;
  14761. }
  14762. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14763. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14764. result = timeEnd - timeStart;
  14765. this._deleteTimeQuery(token._startTimeQuery);
  14766. this._deleteTimeQuery(token._endTimeQuery);
  14767. token._startTimeQuery = null;
  14768. token._endTimeQuery = null;
  14769. }
  14770. else {
  14771. if (!token._timeElapsedQuery) {
  14772. return -1;
  14773. }
  14774. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14775. this._deleteTimeQuery(token._timeElapsedQuery);
  14776. token._timeElapsedQuery = null;
  14777. token._timeElapsedQueryEnded = false;
  14778. this._currentNonTimestampToken = null;
  14779. }
  14780. return result;
  14781. }
  14782. return -1;
  14783. };
  14784. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14785. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14786. };
  14787. // Transform feedback
  14788. Engine.prototype.createTransformFeedback = function () {
  14789. return this._gl.createTransformFeedback();
  14790. };
  14791. Engine.prototype.deleteTransformFeedback = function (value) {
  14792. this._gl.deleteTransformFeedback(value);
  14793. };
  14794. Engine.prototype.bindTransformFeedback = function (value) {
  14795. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14796. };
  14797. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14798. if (usePoints === void 0) { usePoints = true; }
  14799. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14800. };
  14801. Engine.prototype.endTransformFeedback = function () {
  14802. this._gl.endTransformFeedback();
  14803. };
  14804. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14805. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14806. };
  14807. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14808. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14809. };
  14810. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14811. var _this = this;
  14812. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14813. this._activeRequests.push(request);
  14814. request.onCompleteObservable.add(function (request) {
  14815. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14816. });
  14817. return request;
  14818. };
  14819. /** @ignore */
  14820. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14821. var _this = this;
  14822. return new Promise(function (resolve, reject) {
  14823. _this._loadFile(url, function (data) {
  14824. resolve(data);
  14825. }, undefined, database, useArrayBuffer, function (request, exception) {
  14826. reject(exception);
  14827. });
  14828. });
  14829. };
  14830. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14831. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14832. var onload = function (data) {
  14833. loadedFiles[index] = data;
  14834. loadedFiles._internalCount++;
  14835. if (loadedFiles._internalCount === 6) {
  14836. onfinish(loadedFiles);
  14837. }
  14838. };
  14839. var onerror = function (request, exception) {
  14840. if (onErrorCallBack && request) {
  14841. onErrorCallBack(request.status + " " + request.statusText, exception);
  14842. }
  14843. };
  14844. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14845. };
  14846. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14847. if (onError === void 0) { onError = null; }
  14848. var loadedFiles = [];
  14849. loadedFiles._internalCount = 0;
  14850. for (var index = 0; index < 6; index++) {
  14851. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14852. }
  14853. };
  14854. // Statics
  14855. Engine.isSupported = function () {
  14856. try {
  14857. var tempcanvas = document.createElement("canvas");
  14858. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14859. return gl != null && !!window.WebGLRenderingContext;
  14860. }
  14861. catch (e) {
  14862. return false;
  14863. }
  14864. };
  14865. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14866. Engine.ExceptionList = [
  14867. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14868. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14869. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14870. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14871. ];
  14872. Engine.Instances = new Array();
  14873. // Const statics
  14874. Engine._ALPHA_DISABLE = 0;
  14875. Engine._ALPHA_ADD = 1;
  14876. Engine._ALPHA_COMBINE = 2;
  14877. Engine._ALPHA_SUBTRACT = 3;
  14878. Engine._ALPHA_MULTIPLY = 4;
  14879. Engine._ALPHA_MAXIMIZED = 5;
  14880. Engine._ALPHA_ONEONE = 6;
  14881. Engine._ALPHA_PREMULTIPLIED = 7;
  14882. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14883. Engine._ALPHA_INTERPOLATE = 9;
  14884. Engine._ALPHA_SCREENMODE = 10;
  14885. Engine._DELAYLOADSTATE_NONE = 0;
  14886. Engine._DELAYLOADSTATE_LOADED = 1;
  14887. Engine._DELAYLOADSTATE_LOADING = 2;
  14888. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14889. Engine._TEXTUREFORMAT_ALPHA = 0;
  14890. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14891. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14892. Engine._TEXTUREFORMAT_RGB = 4;
  14893. Engine._TEXTUREFORMAT_RGBA = 5;
  14894. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14895. Engine._TEXTURETYPE_FLOAT = 1;
  14896. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14897. // Depht or Stencil test Constants.
  14898. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14899. 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.
  14900. 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.
  14901. 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.
  14902. 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.
  14903. 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.
  14904. 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.
  14905. 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.
  14906. // Stencil Actions Constants.
  14907. Engine._KEEP = 0x1E00;
  14908. Engine._REPLACE = 0x1E01;
  14909. Engine._INCR = 0x1E02;
  14910. Engine._DECR = 0x1E03;
  14911. Engine._INVERT = 0x150A;
  14912. Engine._INCR_WRAP = 0x8507;
  14913. Engine._DECR_WRAP = 0x8508;
  14914. // Texture rescaling mode
  14915. Engine._SCALEMODE_FLOOR = 1;
  14916. Engine._SCALEMODE_NEAREST = 2;
  14917. Engine._SCALEMODE_CEILING = 3;
  14918. // Updatable statics so stick with vars here
  14919. Engine.CollisionsEpsilon = 0.001;
  14920. Engine.CodeRepository = "src/";
  14921. Engine.ShadersRepository = "src/Shaders/";
  14922. return Engine;
  14923. }());
  14924. BABYLON.Engine = Engine;
  14925. })(BABYLON || (BABYLON = {}));
  14926. //# sourceMappingURL=babylon.engine.js.map
  14927. var BABYLON;
  14928. (function (BABYLON) {
  14929. /**
  14930. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14931. */
  14932. var Node = /** @class */ (function () {
  14933. /**
  14934. * Creates a new Node
  14935. * @param {string} name - the name and id to be given to this node
  14936. * @param {BABYLON.Scene} the scene this node will be added to
  14937. */
  14938. function Node(name, scene) {
  14939. if (scene === void 0) { scene = null; }
  14940. /**
  14941. * Gets or sets a string used to store user defined state for the node
  14942. */
  14943. this.state = "";
  14944. /**
  14945. * Gets or sets an object used to store user defined information for the node
  14946. */
  14947. this.metadata = null;
  14948. /**
  14949. * Gets or sets a boolean used to define if the node must be serialized
  14950. */
  14951. this.doNotSerialize = false;
  14952. /** @ignore */
  14953. this._isDisposed = false;
  14954. /**
  14955. * Gets a list of {BABYLON.Animation} associated with the node
  14956. */
  14957. this.animations = new Array();
  14958. this._ranges = {};
  14959. this._isEnabled = true;
  14960. this._isReady = true;
  14961. /** @ignore */
  14962. this._currentRenderId = -1;
  14963. this._parentRenderId = -1;
  14964. /**
  14965. * An event triggered when the mesh is disposed
  14966. * @type {BABYLON.Observable}
  14967. */
  14968. this.onDisposeObservable = new BABYLON.Observable();
  14969. // Behaviors
  14970. this._behaviors = new Array();
  14971. this.name = name;
  14972. this.id = name;
  14973. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14974. this.uniqueId = this._scene.getUniqueId();
  14975. this._initCache();
  14976. }
  14977. /**
  14978. * Gets a boolean indicating if the node has been disposed
  14979. * @returns true if the node was disposed
  14980. */
  14981. Node.prototype.isDisposed = function () {
  14982. return this._isDisposed;
  14983. };
  14984. Object.defineProperty(Node.prototype, "parent", {
  14985. get: function () {
  14986. return this._parentNode;
  14987. },
  14988. /**
  14989. * Gets or sets the parent of the node
  14990. */
  14991. set: function (parent) {
  14992. if (this._parentNode === parent) {
  14993. return;
  14994. }
  14995. // Remove self from list of children of parent
  14996. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14997. var index = this._parentNode._children.indexOf(this);
  14998. if (index !== -1) {
  14999. this._parentNode._children.splice(index, 1);
  15000. }
  15001. }
  15002. // Store new parent
  15003. this._parentNode = parent;
  15004. // Add as child to new parent
  15005. if (this._parentNode) {
  15006. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15007. this._parentNode._children = new Array();
  15008. }
  15009. this._parentNode._children.push(this);
  15010. }
  15011. },
  15012. enumerable: true,
  15013. configurable: true
  15014. });
  15015. /**
  15016. * Gets a string idenfifying the name of the class
  15017. * @returns "Node" string
  15018. */
  15019. Node.prototype.getClassName = function () {
  15020. return "Node";
  15021. };
  15022. Object.defineProperty(Node.prototype, "onDispose", {
  15023. /**
  15024. * Sets a callback that will be raised when the node will be disposed
  15025. */
  15026. set: function (callback) {
  15027. if (this._onDisposeObserver) {
  15028. this.onDisposeObservable.remove(this._onDisposeObserver);
  15029. }
  15030. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. /**
  15036. * Gets the scene of the node
  15037. * @returns a {BABYLON.Scene}
  15038. */
  15039. Node.prototype.getScene = function () {
  15040. return this._scene;
  15041. };
  15042. /**
  15043. * Gets the engine of the node
  15044. * @returns a {BABYLON.Engine}
  15045. */
  15046. Node.prototype.getEngine = function () {
  15047. return this._scene.getEngine();
  15048. };
  15049. /**
  15050. * Attach a behavior to the node
  15051. * @see http://doc.babylonjs.com/features/behaviour
  15052. * @param behavior defines the behavior to attach
  15053. * @returns the current Node
  15054. */
  15055. Node.prototype.addBehavior = function (behavior) {
  15056. var _this = this;
  15057. var index = this._behaviors.indexOf(behavior);
  15058. if (index !== -1) {
  15059. return this;
  15060. }
  15061. behavior.init();
  15062. if (this._scene.isLoading) {
  15063. // We defer the attach when the scene will be loaded
  15064. var observer = this._scene.onDataLoadedObservable.add(function () {
  15065. behavior.attach(_this);
  15066. setTimeout(function () {
  15067. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15068. _this._scene.onDataLoadedObservable.remove(observer);
  15069. }, 0);
  15070. });
  15071. }
  15072. else {
  15073. behavior.attach(this);
  15074. }
  15075. this._behaviors.push(behavior);
  15076. return this;
  15077. };
  15078. /**
  15079. * Remove an attached behavior
  15080. * @see http://doc.babylonjs.com/features/behaviour
  15081. * @param behavior defines the behavior to attach
  15082. * @returns the current Node
  15083. */
  15084. Node.prototype.removeBehavior = function (behavior) {
  15085. var index = this._behaviors.indexOf(behavior);
  15086. if (index === -1) {
  15087. return this;
  15088. }
  15089. this._behaviors[index].detach();
  15090. this._behaviors.splice(index, 1);
  15091. return this;
  15092. };
  15093. Object.defineProperty(Node.prototype, "behaviors", {
  15094. /**
  15095. * Gets the list of attached behaviors
  15096. * @see http://doc.babylonjs.com/features/behaviour
  15097. */
  15098. get: function () {
  15099. return this._behaviors;
  15100. },
  15101. enumerable: true,
  15102. configurable: true
  15103. });
  15104. /**
  15105. * Gets an attached behavior by name
  15106. * @param name defines the name of the behavior to look for
  15107. * @see http://doc.babylonjs.com/features/behaviour
  15108. * @returns null if behavior was not found else the requested behavior
  15109. */
  15110. Node.prototype.getBehaviorByName = function (name) {
  15111. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15112. var behavior = _a[_i];
  15113. if (behavior.name === name) {
  15114. return behavior;
  15115. }
  15116. }
  15117. return null;
  15118. };
  15119. /**
  15120. * Returns the world matrix of the node
  15121. * @returns a matrix containing the node's world matrix
  15122. */
  15123. Node.prototype.getWorldMatrix = function () {
  15124. return BABYLON.Matrix.Identity();
  15125. };
  15126. // override it in derived class if you add new variables to the cache
  15127. // and call the parent class method
  15128. /** @ignore */
  15129. Node.prototype._initCache = function () {
  15130. this._cache = {};
  15131. this._cache.parent = undefined;
  15132. };
  15133. /** @ignore */
  15134. Node.prototype.updateCache = function (force) {
  15135. if (!force && this.isSynchronized())
  15136. return;
  15137. this._cache.parent = this.parent;
  15138. this._updateCache();
  15139. };
  15140. // override it in derived class if you add new variables to the cache
  15141. // and call the parent class method if !ignoreParentClass
  15142. /** @ignore */
  15143. Node.prototype._updateCache = function (ignoreParentClass) {
  15144. };
  15145. // override it in derived class if you add new variables to the cache
  15146. /** @ignore */
  15147. Node.prototype._isSynchronized = function () {
  15148. return true;
  15149. };
  15150. /** @ignore */
  15151. Node.prototype._markSyncedWithParent = function () {
  15152. if (this.parent) {
  15153. this._parentRenderId = this.parent._currentRenderId;
  15154. }
  15155. };
  15156. /** @ignore */
  15157. Node.prototype.isSynchronizedWithParent = function () {
  15158. if (!this.parent) {
  15159. return true;
  15160. }
  15161. if (this._parentRenderId !== this.parent._currentRenderId) {
  15162. return false;
  15163. }
  15164. return this.parent.isSynchronized();
  15165. };
  15166. /** @ignore */
  15167. Node.prototype.isSynchronized = function (updateCache) {
  15168. var check = this.hasNewParent();
  15169. check = check || !this.isSynchronizedWithParent();
  15170. check = check || !this._isSynchronized();
  15171. if (updateCache)
  15172. this.updateCache(true);
  15173. return !check;
  15174. };
  15175. /** @ignore */
  15176. Node.prototype.hasNewParent = function (update) {
  15177. if (this._cache.parent === this.parent)
  15178. return false;
  15179. if (update)
  15180. this._cache.parent = this.parent;
  15181. return true;
  15182. };
  15183. /**
  15184. * Is this node ready to be used/rendered
  15185. * @return true if the node is ready
  15186. */
  15187. Node.prototype.isReady = function () {
  15188. return this._isReady;
  15189. };
  15190. /**
  15191. * Is this node enabled?
  15192. * 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
  15193. * @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
  15194. * @return whether this node (and its parent) is enabled
  15195. * @see setEnabled
  15196. */
  15197. Node.prototype.isEnabled = function (checkAncestors) {
  15198. if (checkAncestors === void 0) { checkAncestors = true; }
  15199. if (checkAncestors === false) {
  15200. return this._isEnabled;
  15201. }
  15202. if (this._isEnabled === false) {
  15203. return false;
  15204. }
  15205. if (this.parent !== undefined && this.parent !== null) {
  15206. return this.parent.isEnabled(checkAncestors);
  15207. }
  15208. return true;
  15209. };
  15210. /**
  15211. * Set the enabled state of this node
  15212. * @param value defines the new enabled state
  15213. * @see isEnabled
  15214. */
  15215. Node.prototype.setEnabled = function (value) {
  15216. this._isEnabled = value;
  15217. };
  15218. /**
  15219. * Is this node a descendant of the given node?
  15220. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15221. * @param ancestor defines the parent node to inspect
  15222. * @see parent
  15223. * @returns a boolean indicating if this node is a descendant of the given node
  15224. */
  15225. Node.prototype.isDescendantOf = function (ancestor) {
  15226. if (this.parent) {
  15227. if (this.parent === ancestor) {
  15228. return true;
  15229. }
  15230. return this.parent.isDescendantOf(ancestor);
  15231. }
  15232. return false;
  15233. };
  15234. /** @ignore */
  15235. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15236. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15237. if (!this._children) {
  15238. return;
  15239. }
  15240. for (var index = 0; index < this._children.length; index++) {
  15241. var item = this._children[index];
  15242. if (!predicate || predicate(item)) {
  15243. results.push(item);
  15244. }
  15245. if (!directDescendantsOnly) {
  15246. item._getDescendants(results, false, predicate);
  15247. }
  15248. }
  15249. };
  15250. /**
  15251. * Will return all nodes that have this node as ascendant
  15252. * @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
  15253. * @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
  15254. * @return all children nodes of all types
  15255. */
  15256. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15257. var results = new Array();
  15258. this._getDescendants(results, directDescendantsOnly, predicate);
  15259. return results;
  15260. };
  15261. /**
  15262. * Get all child-meshes of this node
  15263. * @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
  15264. * @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
  15265. * @returns an array of {BABYLON.AbstractMesh}
  15266. */
  15267. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15268. var results = [];
  15269. this._getDescendants(results, directDescendantsOnly, function (node) {
  15270. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15271. });
  15272. return results;
  15273. };
  15274. /**
  15275. * Get all child-transformNodes of this node
  15276. * @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
  15277. * @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
  15278. * @returns an array of {BABYLON.TransformNode}
  15279. */
  15280. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15281. var results = [];
  15282. this._getDescendants(results, directDescendantsOnly, function (node) {
  15283. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15284. });
  15285. return results;
  15286. };
  15287. /**
  15288. * Get all direct children of this node
  15289. * @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
  15290. * @returns an array of {BABYLON.Node}
  15291. */
  15292. Node.prototype.getChildren = function (predicate) {
  15293. return this.getDescendants(true, predicate);
  15294. };
  15295. /** @ignore */
  15296. Node.prototype._setReady = function (state) {
  15297. if (state === this._isReady) {
  15298. return;
  15299. }
  15300. if (!state) {
  15301. this._isReady = false;
  15302. return;
  15303. }
  15304. this._isReady = true;
  15305. if (this.onReady) {
  15306. this.onReady(this);
  15307. }
  15308. };
  15309. /**
  15310. * Get an animation by name
  15311. * @param name defines the name of the animation to look for
  15312. * @returns null if not found else the requested animation
  15313. */
  15314. Node.prototype.getAnimationByName = function (name) {
  15315. for (var i = 0; i < this.animations.length; i++) {
  15316. var animation = this.animations[i];
  15317. if (animation.name === name) {
  15318. return animation;
  15319. }
  15320. }
  15321. return null;
  15322. };
  15323. /**
  15324. * Creates an animation range for this node
  15325. * @param name defines the name of the range
  15326. * @param from defines the starting key
  15327. * @param to defines the end key
  15328. */
  15329. Node.prototype.createAnimationRange = function (name, from, to) {
  15330. // check name not already in use
  15331. if (!this._ranges[name]) {
  15332. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15333. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15334. if (this.animations[i]) {
  15335. this.animations[i].createRange(name, from, to);
  15336. }
  15337. }
  15338. }
  15339. };
  15340. /**
  15341. * Delete a specific animation range
  15342. * @param name defines the name of the range to delete
  15343. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15344. */
  15345. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15346. if (deleteFrames === void 0) { deleteFrames = true; }
  15347. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15348. if (this.animations[i]) {
  15349. this.animations[i].deleteRange(name, deleteFrames);
  15350. }
  15351. }
  15352. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15353. };
  15354. /**
  15355. * Get an animation range by name
  15356. * @param name defines the name of the animation range to look for
  15357. * @returns null if not found else the requested animation range
  15358. */
  15359. Node.prototype.getAnimationRange = function (name) {
  15360. return this._ranges[name];
  15361. };
  15362. /**
  15363. * Will start the animation sequence
  15364. * @param name defines the range frames for animation sequence
  15365. * @param loop defines if the animation should loop (false by default)
  15366. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15367. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15368. * @returns the object created for this animation. If range does not exist, it will return null
  15369. */
  15370. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15371. var range = this.getAnimationRange(name);
  15372. if (!range) {
  15373. return null;
  15374. }
  15375. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15376. };
  15377. /**
  15378. * Serialize animation ranges into a JSON compatible object
  15379. * @returns serialization object
  15380. */
  15381. Node.prototype.serializeAnimationRanges = function () {
  15382. var serializationRanges = [];
  15383. for (var name in this._ranges) {
  15384. var localRange = this._ranges[name];
  15385. if (!localRange) {
  15386. continue;
  15387. }
  15388. var range = {};
  15389. range.name = name;
  15390. range.from = localRange.from;
  15391. range.to = localRange.to;
  15392. serializationRanges.push(range);
  15393. }
  15394. return serializationRanges;
  15395. };
  15396. /**
  15397. * Computes the world matrix of the node
  15398. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15399. * @returns the world matrix
  15400. */
  15401. Node.prototype.computeWorldMatrix = function (force) {
  15402. return BABYLON.Matrix.Identity();
  15403. };
  15404. /**
  15405. * Releases all associated resources
  15406. */
  15407. Node.prototype.dispose = function () {
  15408. this.parent = null;
  15409. // Callback
  15410. this.onDisposeObservable.notifyObservers(this);
  15411. this.onDisposeObservable.clear();
  15412. // Behaviors
  15413. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15414. var behavior = _a[_i];
  15415. behavior.detach();
  15416. }
  15417. this._behaviors = [];
  15418. this._isDisposed = true;
  15419. };
  15420. /**
  15421. * Parse animation range data from a serialization object and store them into a given node
  15422. * @param node defines where to store the animation ranges
  15423. * @param parsedNode defines the serialization object to read data from
  15424. * @param scene defines the hosting scene
  15425. */
  15426. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15427. if (parsedNode.ranges) {
  15428. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15429. var data = parsedNode.ranges[index];
  15430. node.createAnimationRange(data.name, data.from, data.to);
  15431. }
  15432. }
  15433. };
  15434. __decorate([
  15435. BABYLON.serialize()
  15436. ], Node.prototype, "name", void 0);
  15437. __decorate([
  15438. BABYLON.serialize()
  15439. ], Node.prototype, "id", void 0);
  15440. __decorate([
  15441. BABYLON.serialize()
  15442. ], Node.prototype, "uniqueId", void 0);
  15443. __decorate([
  15444. BABYLON.serialize()
  15445. ], Node.prototype, "state", void 0);
  15446. __decorate([
  15447. BABYLON.serialize()
  15448. ], Node.prototype, "metadata", void 0);
  15449. return Node;
  15450. }());
  15451. BABYLON.Node = Node;
  15452. })(BABYLON || (BABYLON = {}));
  15453. //# sourceMappingURL=babylon.node.js.map
  15454. var BABYLON;
  15455. (function (BABYLON) {
  15456. var BoundingSphere = /** @class */ (function () {
  15457. function BoundingSphere(minimum, maximum) {
  15458. this.minimum = minimum;
  15459. this.maximum = maximum;
  15460. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15461. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15462. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15463. this.radius = distance * 0.5;
  15464. this.centerWorld = BABYLON.Vector3.Zero();
  15465. this._update(BABYLON.Matrix.Identity());
  15466. }
  15467. // Methods
  15468. BoundingSphere.prototype._update = function (world) {
  15469. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15470. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15471. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15472. };
  15473. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15474. for (var i = 0; i < 6; i++) {
  15475. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15476. return false;
  15477. }
  15478. return true;
  15479. };
  15480. BoundingSphere.prototype.intersectsPoint = function (point) {
  15481. var x = this.centerWorld.x - point.x;
  15482. var y = this.centerWorld.y - point.y;
  15483. var z = this.centerWorld.z - point.z;
  15484. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15485. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15486. return false;
  15487. return true;
  15488. };
  15489. // Statics
  15490. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15491. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15492. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15493. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15494. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15495. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15496. return false;
  15497. return true;
  15498. };
  15499. return BoundingSphere;
  15500. }());
  15501. BABYLON.BoundingSphere = BoundingSphere;
  15502. })(BABYLON || (BABYLON = {}));
  15503. //# sourceMappingURL=babylon.boundingSphere.js.map
  15504. var BABYLON;
  15505. (function (BABYLON) {
  15506. var BoundingBox = /** @class */ (function () {
  15507. function BoundingBox(minimum, maximum) {
  15508. this.minimum = minimum;
  15509. this.maximum = maximum;
  15510. this.vectors = new Array();
  15511. this.vectorsWorld = new Array();
  15512. // Bounding vectors
  15513. this.vectors.push(this.minimum.clone());
  15514. this.vectors.push(this.maximum.clone());
  15515. this.vectors.push(this.minimum.clone());
  15516. this.vectors[2].x = this.maximum.x;
  15517. this.vectors.push(this.minimum.clone());
  15518. this.vectors[3].y = this.maximum.y;
  15519. this.vectors.push(this.minimum.clone());
  15520. this.vectors[4].z = this.maximum.z;
  15521. this.vectors.push(this.maximum.clone());
  15522. this.vectors[5].z = this.minimum.z;
  15523. this.vectors.push(this.maximum.clone());
  15524. this.vectors[6].x = this.minimum.x;
  15525. this.vectors.push(this.maximum.clone());
  15526. this.vectors[7].y = this.minimum.y;
  15527. // OBB
  15528. this.center = this.maximum.add(this.minimum).scale(0.5);
  15529. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15530. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15531. // World
  15532. for (var index = 0; index < this.vectors.length; index++) {
  15533. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15534. }
  15535. this.minimumWorld = BABYLON.Vector3.Zero();
  15536. this.maximumWorld = BABYLON.Vector3.Zero();
  15537. this.centerWorld = BABYLON.Vector3.Zero();
  15538. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15539. this._update(BABYLON.Matrix.Identity());
  15540. }
  15541. // Methods
  15542. BoundingBox.prototype.getWorldMatrix = function () {
  15543. return this._worldMatrix;
  15544. };
  15545. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15546. this._worldMatrix.copyFrom(matrix);
  15547. return this;
  15548. };
  15549. BoundingBox.prototype._update = function (world) {
  15550. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15551. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15552. for (var index = 0; index < this.vectors.length; index++) {
  15553. var v = this.vectorsWorld[index];
  15554. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15555. if (v.x < this.minimumWorld.x)
  15556. this.minimumWorld.x = v.x;
  15557. if (v.y < this.minimumWorld.y)
  15558. this.minimumWorld.y = v.y;
  15559. if (v.z < this.minimumWorld.z)
  15560. this.minimumWorld.z = v.z;
  15561. if (v.x > this.maximumWorld.x)
  15562. this.maximumWorld.x = v.x;
  15563. if (v.y > this.maximumWorld.y)
  15564. this.maximumWorld.y = v.y;
  15565. if (v.z > this.maximumWorld.z)
  15566. this.maximumWorld.z = v.z;
  15567. }
  15568. // Extend
  15569. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15570. this.extendSizeWorld.scaleInPlace(0.5);
  15571. // OBB
  15572. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15573. this.centerWorld.scaleInPlace(0.5);
  15574. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15575. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15576. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15577. this._worldMatrix = world;
  15578. };
  15579. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15580. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15581. };
  15582. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15583. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15584. };
  15585. BoundingBox.prototype.intersectsPoint = function (point) {
  15586. var delta = -BABYLON.Epsilon;
  15587. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15588. return false;
  15589. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15590. return false;
  15591. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15592. return false;
  15593. return true;
  15594. };
  15595. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15596. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15597. };
  15598. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15599. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15600. return false;
  15601. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15602. return false;
  15603. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15604. return false;
  15605. return true;
  15606. };
  15607. // Statics
  15608. BoundingBox.Intersects = function (box0, box1) {
  15609. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15610. return false;
  15611. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15612. return false;
  15613. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15614. return false;
  15615. return true;
  15616. };
  15617. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15618. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15619. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15620. return (num <= (sphereRadius * sphereRadius));
  15621. };
  15622. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15623. for (var p = 0; p < 6; p++) {
  15624. for (var i = 0; i < 8; i++) {
  15625. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15626. return false;
  15627. }
  15628. }
  15629. }
  15630. return true;
  15631. };
  15632. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15633. for (var p = 0; p < 6; p++) {
  15634. var inCount = 8;
  15635. for (var i = 0; i < 8; i++) {
  15636. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15637. --inCount;
  15638. }
  15639. else {
  15640. break;
  15641. }
  15642. }
  15643. if (inCount === 0)
  15644. return false;
  15645. }
  15646. return true;
  15647. };
  15648. return BoundingBox;
  15649. }());
  15650. BABYLON.BoundingBox = BoundingBox;
  15651. })(BABYLON || (BABYLON = {}));
  15652. //# sourceMappingURL=babylon.boundingBox.js.map
  15653. var BABYLON;
  15654. (function (BABYLON) {
  15655. var computeBoxExtents = function (axis, box) {
  15656. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15657. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15658. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15659. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15660. var r = r0 + r1 + r2;
  15661. return {
  15662. min: p - r,
  15663. max: p + r
  15664. };
  15665. };
  15666. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15667. var axisOverlap = function (axis, box0, box1) {
  15668. var result0 = computeBoxExtents(axis, box0);
  15669. var result1 = computeBoxExtents(axis, box1);
  15670. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15671. };
  15672. var BoundingInfo = /** @class */ (function () {
  15673. function BoundingInfo(minimum, maximum) {
  15674. this.minimum = minimum;
  15675. this.maximum = maximum;
  15676. this._isLocked = false;
  15677. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15678. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15679. }
  15680. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15681. get: function () {
  15682. return this._isLocked;
  15683. },
  15684. set: function (value) {
  15685. this._isLocked = value;
  15686. },
  15687. enumerable: true,
  15688. configurable: true
  15689. });
  15690. // Methods
  15691. BoundingInfo.prototype.update = function (world) {
  15692. if (this._isLocked) {
  15693. return;
  15694. }
  15695. this.boundingBox._update(world);
  15696. this.boundingSphere._update(world);
  15697. };
  15698. /**
  15699. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15700. * @param center New center of the bounding info
  15701. * @param extend New extend of the bounding info
  15702. */
  15703. BoundingInfo.prototype.centerOn = function (center, extend) {
  15704. this.minimum = center.subtract(extend);
  15705. this.maximum = center.add(extend);
  15706. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15707. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15708. return this;
  15709. };
  15710. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15711. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15712. return false;
  15713. return this.boundingBox.isInFrustum(frustumPlanes);
  15714. };
  15715. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15716. /**
  15717. * Gets the world distance between the min and max points of the bounding box
  15718. */
  15719. get: function () {
  15720. var boundingBox = this.boundingBox;
  15721. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15722. return size.length();
  15723. },
  15724. enumerable: true,
  15725. configurable: true
  15726. });
  15727. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15728. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15729. };
  15730. BoundingInfo.prototype._checkCollision = function (collider) {
  15731. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15732. };
  15733. BoundingInfo.prototype.intersectsPoint = function (point) {
  15734. if (!this.boundingSphere.centerWorld) {
  15735. return false;
  15736. }
  15737. if (!this.boundingSphere.intersectsPoint(point)) {
  15738. return false;
  15739. }
  15740. if (!this.boundingBox.intersectsPoint(point)) {
  15741. return false;
  15742. }
  15743. return true;
  15744. };
  15745. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15746. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15747. return false;
  15748. }
  15749. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15750. return false;
  15751. }
  15752. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15753. return false;
  15754. }
  15755. if (!precise) {
  15756. return true;
  15757. }
  15758. var box0 = this.boundingBox;
  15759. var box1 = boundingInfo.boundingBox;
  15760. if (!axisOverlap(box0.directions[0], box0, box1))
  15761. return false;
  15762. if (!axisOverlap(box0.directions[1], box0, box1))
  15763. return false;
  15764. if (!axisOverlap(box0.directions[2], box0, box1))
  15765. return false;
  15766. if (!axisOverlap(box1.directions[0], box0, box1))
  15767. return false;
  15768. if (!axisOverlap(box1.directions[1], box0, box1))
  15769. return false;
  15770. if (!axisOverlap(box1.directions[2], box0, box1))
  15771. return false;
  15772. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15773. return false;
  15774. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15775. return false;
  15776. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15777. return false;
  15778. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15779. return false;
  15780. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15781. return false;
  15782. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15783. return false;
  15784. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15785. return false;
  15786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15787. return false;
  15788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15789. return false;
  15790. return true;
  15791. };
  15792. return BoundingInfo;
  15793. }());
  15794. BABYLON.BoundingInfo = BoundingInfo;
  15795. })(BABYLON || (BABYLON = {}));
  15796. //# sourceMappingURL=babylon.boundingInfo.js.map
  15797. var BABYLON;
  15798. (function (BABYLON) {
  15799. var TransformNode = /** @class */ (function (_super) {
  15800. __extends(TransformNode, _super);
  15801. function TransformNode(name, scene, isPure) {
  15802. if (scene === void 0) { scene = null; }
  15803. if (isPure === void 0) { isPure = true; }
  15804. var _this = _super.call(this, name, scene) || this;
  15805. // Properties
  15806. _this._rotation = BABYLON.Vector3.Zero();
  15807. _this._scaling = BABYLON.Vector3.One();
  15808. _this._isDirty = false;
  15809. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15810. _this.scalingDeterminant = 1;
  15811. _this.infiniteDistance = false;
  15812. _this.position = BABYLON.Vector3.Zero();
  15813. _this._localWorld = BABYLON.Matrix.Zero();
  15814. _this._worldMatrix = BABYLON.Matrix.Zero();
  15815. _this._worldMatrixDeterminant = 0;
  15816. _this._absolutePosition = BABYLON.Vector3.Zero();
  15817. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15818. _this._postMultiplyPivotMatrix = false;
  15819. _this._isWorldMatrixFrozen = false;
  15820. /**
  15821. * An event triggered after the world matrix is updated
  15822. * @type {BABYLON.Observable}
  15823. */
  15824. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15825. _this._nonUniformScaling = false;
  15826. if (isPure) {
  15827. _this.getScene().addTransformNode(_this);
  15828. }
  15829. return _this;
  15830. }
  15831. Object.defineProperty(TransformNode.prototype, "rotation", {
  15832. /**
  15833. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15834. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15835. * Default : (0.0, 0.0, 0.0)
  15836. */
  15837. get: function () {
  15838. return this._rotation;
  15839. },
  15840. set: function (newRotation) {
  15841. this._rotation = newRotation;
  15842. },
  15843. enumerable: true,
  15844. configurable: true
  15845. });
  15846. Object.defineProperty(TransformNode.prototype, "scaling", {
  15847. /**
  15848. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15849. * Default : (1.0, 1.0, 1.0)
  15850. */
  15851. get: function () {
  15852. return this._scaling;
  15853. },
  15854. /**
  15855. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15856. * Default : (1.0, 1.0, 1.0)
  15857. */
  15858. set: function (newScaling) {
  15859. this._scaling = newScaling;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15865. /**
  15866. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15867. * It's null by default.
  15868. * 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)
  15869. */
  15870. get: function () {
  15871. return this._rotationQuaternion;
  15872. },
  15873. set: function (quaternion) {
  15874. this._rotationQuaternion = quaternion;
  15875. //reset the rotation vector.
  15876. if (quaternion && this.rotation.length()) {
  15877. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15878. }
  15879. },
  15880. enumerable: true,
  15881. configurable: true
  15882. });
  15883. /**
  15884. * Returns the latest update of the World matrix
  15885. * Returns a Matrix.
  15886. */
  15887. TransformNode.prototype.getWorldMatrix = function () {
  15888. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15889. this.computeWorldMatrix();
  15890. }
  15891. return this._worldMatrix;
  15892. };
  15893. /**
  15894. * Returns the latest update of the World matrix determinant.
  15895. */
  15896. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15897. return this._worldMatrixDeterminant;
  15898. };
  15899. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15900. /**
  15901. * Returns directly the latest state of the mesh World matrix.
  15902. * A Matrix is returned.
  15903. */
  15904. get: function () {
  15905. return this._worldMatrix;
  15906. },
  15907. enumerable: true,
  15908. configurable: true
  15909. });
  15910. /**
  15911. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15912. * Returns the AbstractMesh.
  15913. */
  15914. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15915. this._poseMatrix.copyFrom(matrix);
  15916. return this;
  15917. };
  15918. /**
  15919. * Returns the mesh Pose matrix.
  15920. * Returned object : Matrix
  15921. */
  15922. TransformNode.prototype.getPoseMatrix = function () {
  15923. return this._poseMatrix;
  15924. };
  15925. TransformNode.prototype._isSynchronized = function () {
  15926. if (this._isDirty) {
  15927. return false;
  15928. }
  15929. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15930. return false;
  15931. if (this._cache.pivotMatrixUpdated) {
  15932. return false;
  15933. }
  15934. if (this.infiniteDistance) {
  15935. return false;
  15936. }
  15937. if (!this._cache.position.equals(this.position))
  15938. return false;
  15939. if (this.rotationQuaternion) {
  15940. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15941. return false;
  15942. }
  15943. if (!this._cache.rotation.equals(this.rotation))
  15944. return false;
  15945. if (!this._cache.scaling.equals(this.scaling))
  15946. return false;
  15947. return true;
  15948. };
  15949. TransformNode.prototype._initCache = function () {
  15950. _super.prototype._initCache.call(this);
  15951. this._cache.localMatrixUpdated = false;
  15952. this._cache.position = BABYLON.Vector3.Zero();
  15953. this._cache.scaling = BABYLON.Vector3.Zero();
  15954. this._cache.rotation = BABYLON.Vector3.Zero();
  15955. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15956. this._cache.billboardMode = -1;
  15957. };
  15958. TransformNode.prototype.markAsDirty = function (property) {
  15959. if (property === "rotation") {
  15960. this.rotationQuaternion = null;
  15961. }
  15962. this._currentRenderId = Number.MAX_VALUE;
  15963. this._isDirty = true;
  15964. return this;
  15965. };
  15966. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15967. /**
  15968. * Returns the current mesh absolute position.
  15969. * Retuns a Vector3.
  15970. */
  15971. get: function () {
  15972. return this._absolutePosition;
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. /**
  15978. * Sets a new matrix to apply before all other transformation
  15979. * @param matrix defines the transform matrix
  15980. * @returns the current TransformNode
  15981. */
  15982. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15983. return this.setPivotMatrix(matrix, false);
  15984. };
  15985. /**
  15986. * Sets a new pivot matrix to the current node
  15987. * @param matrix defines the new pivot matrix to use
  15988. * @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
  15989. * @returns the current TransformNode
  15990. */
  15991. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15992. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15993. this._pivotMatrix = matrix.clone();
  15994. this._cache.pivotMatrixUpdated = true;
  15995. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15996. if (this._postMultiplyPivotMatrix) {
  15997. if (!this._pivotMatrixInverse) {
  15998. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15999. }
  16000. else {
  16001. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16002. }
  16003. }
  16004. return this;
  16005. };
  16006. /**
  16007. * Returns the mesh pivot matrix.
  16008. * Default : Identity.
  16009. * A Matrix is returned.
  16010. */
  16011. TransformNode.prototype.getPivotMatrix = function () {
  16012. return this._pivotMatrix;
  16013. };
  16014. /**
  16015. * Prevents the World matrix to be computed any longer.
  16016. * Returns the AbstractMesh.
  16017. */
  16018. TransformNode.prototype.freezeWorldMatrix = function () {
  16019. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16020. this.computeWorldMatrix(true);
  16021. this._isWorldMatrixFrozen = true;
  16022. return this;
  16023. };
  16024. /**
  16025. * Allows back the World matrix computation.
  16026. * Returns the AbstractMesh.
  16027. */
  16028. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16029. this._isWorldMatrixFrozen = false;
  16030. this.computeWorldMatrix(true);
  16031. return this;
  16032. };
  16033. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16034. /**
  16035. * True if the World matrix has been frozen.
  16036. * Returns a boolean.
  16037. */
  16038. get: function () {
  16039. return this._isWorldMatrixFrozen;
  16040. },
  16041. enumerable: true,
  16042. configurable: true
  16043. });
  16044. /**
  16045. * Retuns the mesh absolute position in the World.
  16046. * Returns a Vector3.
  16047. */
  16048. TransformNode.prototype.getAbsolutePosition = function () {
  16049. this.computeWorldMatrix();
  16050. return this._absolutePosition;
  16051. };
  16052. /**
  16053. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16054. * Returns the AbstractMesh.
  16055. */
  16056. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16057. if (!absolutePosition) {
  16058. return this;
  16059. }
  16060. var absolutePositionX;
  16061. var absolutePositionY;
  16062. var absolutePositionZ;
  16063. if (absolutePosition.x === undefined) {
  16064. if (arguments.length < 3) {
  16065. return this;
  16066. }
  16067. absolutePositionX = arguments[0];
  16068. absolutePositionY = arguments[1];
  16069. absolutePositionZ = arguments[2];
  16070. }
  16071. else {
  16072. absolutePositionX = absolutePosition.x;
  16073. absolutePositionY = absolutePosition.y;
  16074. absolutePositionZ = absolutePosition.z;
  16075. }
  16076. if (this.parent) {
  16077. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16078. invertParentWorldMatrix.invert();
  16079. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16080. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16081. }
  16082. else {
  16083. this.position.x = absolutePositionX;
  16084. this.position.y = absolutePositionY;
  16085. this.position.z = absolutePositionZ;
  16086. }
  16087. return this;
  16088. };
  16089. /**
  16090. * Sets the mesh position in its local space.
  16091. * Returns the AbstractMesh.
  16092. */
  16093. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16094. this.computeWorldMatrix();
  16095. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16096. return this;
  16097. };
  16098. /**
  16099. * Returns the mesh position in the local space from the current World matrix values.
  16100. * Returns a new Vector3.
  16101. */
  16102. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16103. this.computeWorldMatrix();
  16104. var invLocalWorldMatrix = this._localWorld.clone();
  16105. invLocalWorldMatrix.invert();
  16106. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16107. };
  16108. /**
  16109. * Translates the mesh along the passed Vector3 in its local space.
  16110. * Returns the AbstractMesh.
  16111. */
  16112. TransformNode.prototype.locallyTranslate = function (vector3) {
  16113. this.computeWorldMatrix(true);
  16114. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16115. return this;
  16116. };
  16117. /**
  16118. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16119. * @param targetPoint the position (must be in same space as current mesh) to look at
  16120. * @param yawCor optional yaw (y-axis) correction in radians
  16121. * @param pitchCor optional pitch (x-axis) correction in radians
  16122. * @param rollCor optional roll (z-axis) correction in radians
  16123. * @param space the choosen space of the target
  16124. * @returns the TransformNode.
  16125. */
  16126. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16127. if (yawCor === void 0) { yawCor = 0; }
  16128. if (pitchCor === void 0) { pitchCor = 0; }
  16129. if (rollCor === void 0) { rollCor = 0; }
  16130. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16131. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16132. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16133. targetPoint.subtractToRef(pos, dv);
  16134. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16135. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16136. var pitch = Math.atan2(dv.y, len);
  16137. if (this.rotationQuaternion) {
  16138. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16139. }
  16140. else {
  16141. this.rotation.x = pitch + pitchCor;
  16142. this.rotation.y = yaw + yawCor;
  16143. this.rotation.z = rollCor;
  16144. }
  16145. return this;
  16146. };
  16147. /**
  16148. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16149. * This Vector3 is expressed in the World space.
  16150. */
  16151. TransformNode.prototype.getDirection = function (localAxis) {
  16152. var result = BABYLON.Vector3.Zero();
  16153. this.getDirectionToRef(localAxis, result);
  16154. return result;
  16155. };
  16156. /**
  16157. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16158. * localAxis is expressed in the mesh local space.
  16159. * result is computed in the Wordl space from the mesh World matrix.
  16160. * Returns the AbstractMesh.
  16161. */
  16162. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16163. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16164. return this;
  16165. };
  16166. /**
  16167. * Sets a new pivot point to the current node
  16168. * @param point defines the new pivot point to use
  16169. * @param space defines if the point is in world or local space (local by default)
  16170. * @returns the current TransformNode
  16171. */
  16172. TransformNode.prototype.setPivotPoint = function (point, space) {
  16173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16174. if (this.getScene().getRenderId() == 0) {
  16175. this.computeWorldMatrix(true);
  16176. }
  16177. var wm = this.getWorldMatrix();
  16178. if (space == BABYLON.Space.WORLD) {
  16179. var tmat = BABYLON.Tmp.Matrix[0];
  16180. wm.invertToRef(tmat);
  16181. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16182. }
  16183. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16184. };
  16185. /**
  16186. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16187. */
  16188. TransformNode.prototype.getPivotPoint = function () {
  16189. var point = BABYLON.Vector3.Zero();
  16190. this.getPivotPointToRef(point);
  16191. return point;
  16192. };
  16193. /**
  16194. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16195. * Returns the AbstractMesh.
  16196. */
  16197. TransformNode.prototype.getPivotPointToRef = function (result) {
  16198. result.x = -this._pivotMatrix.m[12];
  16199. result.y = -this._pivotMatrix.m[13];
  16200. result.z = -this._pivotMatrix.m[14];
  16201. return this;
  16202. };
  16203. /**
  16204. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16205. */
  16206. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16207. var point = BABYLON.Vector3.Zero();
  16208. this.getAbsolutePivotPointToRef(point);
  16209. return point;
  16210. };
  16211. /**
  16212. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16213. * Returns the AbstractMesh.
  16214. */
  16215. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16216. result.x = this._pivotMatrix.m[12];
  16217. result.y = this._pivotMatrix.m[13];
  16218. result.z = this._pivotMatrix.m[14];
  16219. this.getPivotPointToRef(result);
  16220. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16221. return this;
  16222. };
  16223. /**
  16224. * Defines the passed node as the parent of the current node.
  16225. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16226. * Returns the TransformNode.
  16227. */
  16228. TransformNode.prototype.setParent = function (node) {
  16229. if (node === null) {
  16230. var rotation = BABYLON.Tmp.Quaternion[0];
  16231. var position = BABYLON.Tmp.Vector3[0];
  16232. var scale = BABYLON.Tmp.Vector3[1];
  16233. if (this.parent && this.parent.computeWorldMatrix) {
  16234. this.parent.computeWorldMatrix(true);
  16235. }
  16236. this.computeWorldMatrix(true);
  16237. this.getWorldMatrix().decompose(scale, rotation, position);
  16238. if (this.rotationQuaternion) {
  16239. this.rotationQuaternion.copyFrom(rotation);
  16240. }
  16241. else {
  16242. rotation.toEulerAnglesToRef(this.rotation);
  16243. }
  16244. this.scaling.x = scale.x;
  16245. this.scaling.y = scale.y;
  16246. this.scaling.z = scale.z;
  16247. this.position.x = position.x;
  16248. this.position.y = position.y;
  16249. this.position.z = position.z;
  16250. }
  16251. else {
  16252. var rotation = BABYLON.Tmp.Quaternion[0];
  16253. var position = BABYLON.Tmp.Vector3[0];
  16254. var scale = BABYLON.Tmp.Vector3[1];
  16255. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16256. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16257. this.computeWorldMatrix(true);
  16258. node.computeWorldMatrix(true);
  16259. node.getWorldMatrix().invertToRef(invParentMatrix);
  16260. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16261. diffMatrix.decompose(scale, rotation, position);
  16262. if (this.rotationQuaternion) {
  16263. this.rotationQuaternion.copyFrom(rotation);
  16264. }
  16265. else {
  16266. rotation.toEulerAnglesToRef(this.rotation);
  16267. }
  16268. this.position.x = position.x;
  16269. this.position.y = position.y;
  16270. this.position.z = position.z;
  16271. this.scaling.x = scale.x;
  16272. this.scaling.y = scale.y;
  16273. this.scaling.z = scale.z;
  16274. }
  16275. this.parent = node;
  16276. return this;
  16277. };
  16278. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16279. get: function () {
  16280. return this._nonUniformScaling;
  16281. },
  16282. enumerable: true,
  16283. configurable: true
  16284. });
  16285. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16286. if (this._nonUniformScaling === value) {
  16287. return false;
  16288. }
  16289. this._nonUniformScaling = true;
  16290. return true;
  16291. };
  16292. /**
  16293. * Attach the current TransformNode to another TransformNode associated with a bone
  16294. * @param bone Bone affecting the TransformNode
  16295. * @param affectedTransformNode TransformNode associated with the bone
  16296. */
  16297. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16298. this._transformToBoneReferal = affectedTransformNode;
  16299. this.parent = bone;
  16300. if (bone.getWorldMatrix().determinant() < 0) {
  16301. this.scalingDeterminant *= -1;
  16302. }
  16303. return this;
  16304. };
  16305. TransformNode.prototype.detachFromBone = function () {
  16306. if (!this.parent) {
  16307. return this;
  16308. }
  16309. if (this.parent.getWorldMatrix().determinant() < 0) {
  16310. this.scalingDeterminant *= -1;
  16311. }
  16312. this._transformToBoneReferal = null;
  16313. this.parent = null;
  16314. return this;
  16315. };
  16316. /**
  16317. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16318. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16319. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16320. * The passed axis is also normalized.
  16321. * Returns the AbstractMesh.
  16322. */
  16323. TransformNode.prototype.rotate = function (axis, amount, space) {
  16324. axis.normalize();
  16325. if (!this.rotationQuaternion) {
  16326. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16327. this.rotation = BABYLON.Vector3.Zero();
  16328. }
  16329. var rotationQuaternion;
  16330. if (!space || space === BABYLON.Space.LOCAL) {
  16331. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16332. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16333. }
  16334. else {
  16335. if (this.parent) {
  16336. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16337. invertParentWorldMatrix.invert();
  16338. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16339. }
  16340. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16341. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16342. }
  16343. return this;
  16344. };
  16345. /**
  16346. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16347. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16348. * The passed axis is also normalized.
  16349. * Returns the AbstractMesh.
  16350. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16351. */
  16352. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16353. axis.normalize();
  16354. if (!this.rotationQuaternion) {
  16355. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16356. this.rotation.copyFromFloats(0, 0, 0);
  16357. }
  16358. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16359. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16360. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16361. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16362. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16363. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16364. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16365. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16366. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16367. return this;
  16368. };
  16369. /**
  16370. * Translates the mesh along the axis vector for the passed distance in the given space.
  16371. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16372. * Returns the AbstractMesh.
  16373. */
  16374. TransformNode.prototype.translate = function (axis, distance, space) {
  16375. var displacementVector = axis.scale(distance);
  16376. if (!space || space === BABYLON.Space.LOCAL) {
  16377. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16378. this.setPositionWithLocalVector(tempV3);
  16379. }
  16380. else {
  16381. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16382. }
  16383. return this;
  16384. };
  16385. /**
  16386. * Adds a rotation step to the mesh current rotation.
  16387. * x, y, z are Euler angles expressed in radians.
  16388. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16389. * This means this rotation is made in the mesh local space only.
  16390. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16391. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16392. * ```javascript
  16393. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16394. * ```
  16395. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16396. * 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.
  16397. * Returns the AbstractMesh.
  16398. */
  16399. TransformNode.prototype.addRotation = function (x, y, z) {
  16400. var rotationQuaternion;
  16401. if (this.rotationQuaternion) {
  16402. rotationQuaternion = this.rotationQuaternion;
  16403. }
  16404. else {
  16405. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16406. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16407. }
  16408. var accumulation = BABYLON.Tmp.Quaternion[0];
  16409. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16410. rotationQuaternion.multiplyInPlace(accumulation);
  16411. if (!this.rotationQuaternion) {
  16412. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16413. }
  16414. return this;
  16415. };
  16416. /**
  16417. * Computes the mesh World matrix and returns it.
  16418. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16419. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16420. * If the parameter `force`is set to `true`, the actual computation is done.
  16421. * Returns the mesh World Matrix.
  16422. */
  16423. TransformNode.prototype.computeWorldMatrix = function (force) {
  16424. if (this._isWorldMatrixFrozen) {
  16425. return this._worldMatrix;
  16426. }
  16427. if (!force && this.isSynchronized(true)) {
  16428. return this._worldMatrix;
  16429. }
  16430. this._cache.position.copyFrom(this.position);
  16431. this._cache.scaling.copyFrom(this.scaling);
  16432. this._cache.pivotMatrixUpdated = false;
  16433. this._cache.billboardMode = this.billboardMode;
  16434. this._currentRenderId = this.getScene().getRenderId();
  16435. this._isDirty = false;
  16436. // Scaling
  16437. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16438. // Rotation
  16439. //rotate, if quaternion is set and rotation was used
  16440. if (this.rotationQuaternion) {
  16441. var len = this.rotation.length();
  16442. if (len) {
  16443. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16444. this.rotation.copyFromFloats(0, 0, 0);
  16445. }
  16446. }
  16447. if (this.rotationQuaternion) {
  16448. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16449. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16450. }
  16451. else {
  16452. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16453. this._cache.rotation.copyFrom(this.rotation);
  16454. }
  16455. // Translation
  16456. var camera = this.getScene().activeCamera;
  16457. if (this.infiniteDistance && !this.parent && camera) {
  16458. var cameraWorldMatrix = camera.getWorldMatrix();
  16459. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16460. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16461. }
  16462. else {
  16463. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16464. }
  16465. // Composing transformations
  16466. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16467. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16468. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16469. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16470. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16471. // Need to decompose each rotation here
  16472. var currentPosition = BABYLON.Tmp.Vector3[3];
  16473. if (this.parent && this.parent.getWorldMatrix) {
  16474. if (this._transformToBoneReferal) {
  16475. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16476. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16477. }
  16478. else {
  16479. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16480. }
  16481. }
  16482. else {
  16483. currentPosition.copyFrom(this.position);
  16484. }
  16485. currentPosition.subtractInPlace(camera.globalPosition);
  16486. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16487. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16488. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16489. }
  16490. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16491. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16492. }
  16493. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16494. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16495. }
  16496. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16497. }
  16498. else {
  16499. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16500. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16501. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16502. }
  16503. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16504. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16505. }
  16506. // Local world
  16507. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16508. // Parent
  16509. if (this.parent && this.parent.getWorldMatrix) {
  16510. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16511. if (this._transformToBoneReferal) {
  16512. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16513. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16514. }
  16515. else {
  16516. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16517. }
  16518. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16519. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16520. this._worldMatrix.copyFrom(this._localWorld);
  16521. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16522. }
  16523. else {
  16524. if (this._transformToBoneReferal) {
  16525. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16526. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16527. }
  16528. else {
  16529. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16530. }
  16531. }
  16532. this._markSyncedWithParent();
  16533. }
  16534. else {
  16535. this._worldMatrix.copyFrom(this._localWorld);
  16536. }
  16537. // Post multiply inverse of pivotMatrix
  16538. if (this._postMultiplyPivotMatrix) {
  16539. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16540. }
  16541. // Normal matrix
  16542. if (this.scaling.isNonUniform) {
  16543. this._updateNonUniformScalingState(true);
  16544. }
  16545. else if (this.parent && this.parent._nonUniformScaling) {
  16546. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16547. }
  16548. else {
  16549. this._updateNonUniformScalingState(false);
  16550. }
  16551. this._afterComputeWorldMatrix();
  16552. // Absolute position
  16553. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16554. // Callbacks
  16555. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16556. if (!this._poseMatrix) {
  16557. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16558. }
  16559. // Cache the determinant
  16560. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16561. return this._worldMatrix;
  16562. };
  16563. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16564. };
  16565. /**
  16566. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16567. * @param func: callback function to add
  16568. *
  16569. * Returns the TransformNode.
  16570. */
  16571. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16572. this.onAfterWorldMatrixUpdateObservable.add(func);
  16573. return this;
  16574. };
  16575. /**
  16576. * Removes a registered callback function.
  16577. * Returns the TransformNode.
  16578. */
  16579. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16580. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16581. return this;
  16582. };
  16583. /**
  16584. * Clone the current transform node
  16585. * Returns the new transform node
  16586. * @param name Name of the new clone
  16587. * @param newParent New parent for the clone
  16588. * @param doNotCloneChildren Do not clone children hierarchy
  16589. */
  16590. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16591. var _this = this;
  16592. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16593. result.name = name;
  16594. result.id = name;
  16595. if (newParent) {
  16596. result.parent = newParent;
  16597. }
  16598. if (!doNotCloneChildren) {
  16599. // Children
  16600. var directDescendants = this.getDescendants(true);
  16601. for (var index = 0; index < directDescendants.length; index++) {
  16602. var child = directDescendants[index];
  16603. if (child.clone) {
  16604. child.clone(name + "." + child.name, result);
  16605. }
  16606. }
  16607. }
  16608. return result;
  16609. };
  16610. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16611. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16612. serializationObject.type = this.getClassName();
  16613. // Parent
  16614. if (this.parent) {
  16615. serializationObject.parentId = this.parent.id;
  16616. }
  16617. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16618. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16619. }
  16620. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16621. serializationObject.isEnabled = this.isEnabled();
  16622. // Parent
  16623. if (this.parent) {
  16624. serializationObject.parentId = this.parent.id;
  16625. }
  16626. return serializationObject;
  16627. };
  16628. // Statics
  16629. /**
  16630. * Returns a new TransformNode object parsed from the source provided.
  16631. * The parameter `parsedMesh` is the source.
  16632. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16633. */
  16634. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16635. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16636. if (BABYLON.Tags) {
  16637. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16638. }
  16639. if (parsedTransformNode.localMatrix) {
  16640. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16641. }
  16642. else if (parsedTransformNode.pivotMatrix) {
  16643. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16644. }
  16645. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16646. // Parent
  16647. if (parsedTransformNode.parentId) {
  16648. transformNode._waitingParentId = parsedTransformNode.parentId;
  16649. }
  16650. return transformNode;
  16651. };
  16652. /**
  16653. * Disposes the TransformNode.
  16654. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16655. * Returns nothing.
  16656. */
  16657. TransformNode.prototype.dispose = function (doNotRecurse) {
  16658. // Animations
  16659. this.getScene().stopAnimation(this);
  16660. // Remove from scene
  16661. this.getScene().removeTransformNode(this);
  16662. if (!doNotRecurse) {
  16663. // Children
  16664. var objects = this.getDescendants(true);
  16665. for (var index = 0; index < objects.length; index++) {
  16666. objects[index].dispose();
  16667. }
  16668. }
  16669. else {
  16670. var childMeshes = this.getChildMeshes(true);
  16671. for (index = 0; index < childMeshes.length; index++) {
  16672. var child = childMeshes[index];
  16673. child.parent = null;
  16674. child.computeWorldMatrix(true);
  16675. }
  16676. }
  16677. this.onAfterWorldMatrixUpdateObservable.clear();
  16678. _super.prototype.dispose.call(this);
  16679. };
  16680. // Statics
  16681. TransformNode.BILLBOARDMODE_NONE = 0;
  16682. TransformNode.BILLBOARDMODE_X = 1;
  16683. TransformNode.BILLBOARDMODE_Y = 2;
  16684. TransformNode.BILLBOARDMODE_Z = 4;
  16685. TransformNode.BILLBOARDMODE_ALL = 7;
  16686. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16687. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16688. __decorate([
  16689. BABYLON.serializeAsVector3()
  16690. ], TransformNode.prototype, "_rotation", void 0);
  16691. __decorate([
  16692. BABYLON.serializeAsQuaternion()
  16693. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16694. __decorate([
  16695. BABYLON.serializeAsVector3()
  16696. ], TransformNode.prototype, "_scaling", void 0);
  16697. __decorate([
  16698. BABYLON.serialize()
  16699. ], TransformNode.prototype, "billboardMode", void 0);
  16700. __decorate([
  16701. BABYLON.serialize()
  16702. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16703. __decorate([
  16704. BABYLON.serialize()
  16705. ], TransformNode.prototype, "infiniteDistance", void 0);
  16706. __decorate([
  16707. BABYLON.serializeAsVector3()
  16708. ], TransformNode.prototype, "position", void 0);
  16709. return TransformNode;
  16710. }(BABYLON.Node));
  16711. BABYLON.TransformNode = TransformNode;
  16712. })(BABYLON || (BABYLON = {}));
  16713. //# sourceMappingURL=babylon.transformNode.js.map
  16714. var BABYLON;
  16715. (function (BABYLON) {
  16716. var AbstractMesh = /** @class */ (function (_super) {
  16717. __extends(AbstractMesh, _super);
  16718. // Constructor
  16719. function AbstractMesh(name, scene) {
  16720. if (scene === void 0) { scene = null; }
  16721. var _this = _super.call(this, name, scene, false) || this;
  16722. _this._facetNb = 0; // facet number
  16723. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16724. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16725. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16726. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16727. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16728. _this._subDiv = {
  16729. max: 1,
  16730. X: 1,
  16731. Y: 1,
  16732. Z: 1
  16733. };
  16734. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16735. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16736. // Events
  16737. /**
  16738. * An event triggered when this mesh collides with another one
  16739. * @type {BABYLON.Observable}
  16740. */
  16741. _this.onCollideObservable = new BABYLON.Observable();
  16742. /**
  16743. * An event triggered when the collision's position changes
  16744. * @type {BABYLON.Observable}
  16745. */
  16746. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16747. /**
  16748. * An event triggered when material is changed
  16749. * @type {BABYLON.Observable}
  16750. */
  16751. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16752. // Properties
  16753. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16754. /**
  16755. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16756. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16757. * or
  16758. * 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.
  16759. * for more info check WebGl documentations
  16760. */
  16761. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16762. /**
  16763. * 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:
  16764. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16765. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16766. * 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.
  16767. */
  16768. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16769. /**
  16770. * 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.
  16771. * The default value is -1 which means don't break the query and wait till the result.
  16772. */
  16773. _this.occlusionRetryCount = -1;
  16774. _this._occlusionInternalRetryCounter = 0;
  16775. _this._isOccluded = false;
  16776. _this._isOcclusionQueryInProgress = false;
  16777. _this._visibility = 1.0;
  16778. _this.alphaIndex = Number.MAX_VALUE;
  16779. _this.isVisible = true;
  16780. _this.isPickable = true;
  16781. _this.showBoundingBox = false;
  16782. _this.showSubMeshesBoundingBox = false;
  16783. _this.isBlocker = false;
  16784. _this.enablePointerMoveEvents = false;
  16785. _this.renderingGroupId = 0;
  16786. _this._receiveShadows = false;
  16787. _this.renderOutline = false;
  16788. _this.outlineColor = BABYLON.Color3.Red();
  16789. _this.outlineWidth = 0.02;
  16790. _this.renderOverlay = false;
  16791. _this.overlayColor = BABYLON.Color3.Red();
  16792. _this.overlayAlpha = 0.5;
  16793. _this._hasVertexAlpha = false;
  16794. _this._useVertexColors = true;
  16795. _this._computeBonesUsingShaders = true;
  16796. _this._numBoneInfluencers = 4;
  16797. _this._applyFog = true;
  16798. _this.useOctreeForRenderingSelection = true;
  16799. _this.useOctreeForPicking = true;
  16800. _this.useOctreeForCollisions = true;
  16801. _this._layerMask = 0x0FFFFFFF;
  16802. /**
  16803. * True if the mesh must be rendered in any case.
  16804. */
  16805. _this.alwaysSelectAsActiveMesh = false;
  16806. /**
  16807. * This scene's action manager
  16808. * @type {BABYLON.ActionManager}
  16809. */
  16810. _this.actionManager = null;
  16811. // Physics
  16812. _this.physicsImpostor = null;
  16813. // Collisions
  16814. _this._checkCollisions = false;
  16815. _this._collisionMask = -1;
  16816. _this._collisionGroup = -1;
  16817. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16818. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16819. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16820. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16821. // Edges
  16822. _this.edgesWidth = 1;
  16823. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16824. // Cache
  16825. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16826. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16827. _this._renderId = 0;
  16828. _this._intersectionsInProgress = new Array();
  16829. _this._unIndexed = false;
  16830. _this._lightSources = new Array();
  16831. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16832. if (collidedMesh === void 0) { collidedMesh = null; }
  16833. //TODO move this to the collision coordinator!
  16834. if (_this.getScene().workerCollisions)
  16835. newPosition.multiplyInPlace(_this._collider._radius);
  16836. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16837. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16838. _this.position.addInPlace(_this._diffPositionForCollisions);
  16839. }
  16840. if (collidedMesh) {
  16841. _this.onCollideObservable.notifyObservers(collidedMesh);
  16842. }
  16843. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16844. };
  16845. _this.getScene().addMesh(_this);
  16846. _this._resyncLightSources();
  16847. return _this;
  16848. }
  16849. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16850. get: function () {
  16851. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16852. },
  16853. enumerable: true,
  16854. configurable: true
  16855. });
  16856. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16857. get: function () {
  16858. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16859. },
  16860. enumerable: true,
  16861. configurable: true
  16862. });
  16863. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16864. get: function () {
  16865. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16866. },
  16867. enumerable: true,
  16868. configurable: true
  16869. });
  16870. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16871. get: function () {
  16872. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16873. },
  16874. enumerable: true,
  16875. configurable: true
  16876. });
  16877. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16878. get: function () {
  16879. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16880. },
  16881. enumerable: true,
  16882. configurable: true
  16883. });
  16884. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16885. /**
  16886. * Read-only : the number of facets in the mesh
  16887. */
  16888. get: function () {
  16889. return this._facetNb;
  16890. },
  16891. enumerable: true,
  16892. configurable: true
  16893. });
  16894. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16895. /**
  16896. * The number (integer) of subdivisions per axis in the partioning space
  16897. */
  16898. get: function () {
  16899. return this._partitioningSubdivisions;
  16900. },
  16901. set: function (nb) {
  16902. this._partitioningSubdivisions = nb;
  16903. },
  16904. enumerable: true,
  16905. configurable: true
  16906. });
  16907. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16908. /**
  16909. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16910. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16911. */
  16912. get: function () {
  16913. return this._partitioningBBoxRatio;
  16914. },
  16915. set: function (ratio) {
  16916. this._partitioningBBoxRatio = ratio;
  16917. },
  16918. enumerable: true,
  16919. configurable: true
  16920. });
  16921. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16922. /**
  16923. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16924. * Works only for updatable meshes.
  16925. * Doesn't work with multi-materials.
  16926. */
  16927. get: function () {
  16928. return this._facetDepthSort;
  16929. },
  16930. set: function (sort) {
  16931. this._facetDepthSort = sort;
  16932. },
  16933. enumerable: true,
  16934. configurable: true
  16935. });
  16936. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16937. /**
  16938. * The location (Vector3) where the facet depth sort must be computed from.
  16939. * By default, the active camera position.
  16940. * Used only when facet depth sort is enabled.
  16941. */
  16942. get: function () {
  16943. return this._facetDepthSortFrom;
  16944. },
  16945. set: function (location) {
  16946. this._facetDepthSortFrom = location;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16952. /**
  16953. * Read-only boolean : is the feature facetData enabled ?
  16954. */
  16955. get: function () {
  16956. return this._facetDataEnabled;
  16957. },
  16958. enumerable: true,
  16959. configurable: true
  16960. });
  16961. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16962. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16963. return false;
  16964. }
  16965. this._markSubMeshesAsMiscDirty();
  16966. return true;
  16967. };
  16968. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16969. set: function (callback) {
  16970. if (this._onCollideObserver) {
  16971. this.onCollideObservable.remove(this._onCollideObserver);
  16972. }
  16973. this._onCollideObserver = this.onCollideObservable.add(callback);
  16974. },
  16975. enumerable: true,
  16976. configurable: true
  16977. });
  16978. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16979. set: function (callback) {
  16980. if (this._onCollisionPositionChangeObserver) {
  16981. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16982. }
  16983. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16984. },
  16985. enumerable: true,
  16986. configurable: true
  16987. });
  16988. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16989. /**
  16990. * 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.
  16991. */
  16992. get: function () {
  16993. return this._isOccluded;
  16994. },
  16995. set: function (value) {
  16996. this._isOccluded = value;
  16997. },
  16998. enumerable: true,
  16999. configurable: true
  17000. });
  17001. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17002. /**
  17003. * Flag to check the progress status of the query
  17004. */
  17005. get: function () {
  17006. return this._isOcclusionQueryInProgress;
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17012. /**
  17013. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17014. */
  17015. get: function () {
  17016. return this._visibility;
  17017. },
  17018. /**
  17019. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17020. */
  17021. set: function (value) {
  17022. if (this._visibility === value) {
  17023. return;
  17024. }
  17025. this._visibility = value;
  17026. this._markSubMeshesAsMiscDirty();
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. Object.defineProperty(AbstractMesh.prototype, "material", {
  17032. get: function () {
  17033. return this._material;
  17034. },
  17035. set: function (value) {
  17036. if (this._material === value) {
  17037. return;
  17038. }
  17039. this._material = value;
  17040. if (this.onMaterialChangedObservable.hasObservers) {
  17041. this.onMaterialChangedObservable.notifyObservers(this);
  17042. }
  17043. if (!this.subMeshes) {
  17044. return;
  17045. }
  17046. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17047. var subMesh = _a[_i];
  17048. subMesh.setEffect(null);
  17049. }
  17050. },
  17051. enumerable: true,
  17052. configurable: true
  17053. });
  17054. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17055. get: function () {
  17056. return this._receiveShadows;
  17057. },
  17058. set: function (value) {
  17059. if (this._receiveShadows === value) {
  17060. return;
  17061. }
  17062. this._receiveShadows = value;
  17063. this._markSubMeshesAsLightDirty();
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17069. get: function () {
  17070. return this._hasVertexAlpha;
  17071. },
  17072. set: function (value) {
  17073. if (this._hasVertexAlpha === value) {
  17074. return;
  17075. }
  17076. this._hasVertexAlpha = value;
  17077. this._markSubMeshesAsAttributesDirty();
  17078. this._markSubMeshesAsMiscDirty();
  17079. },
  17080. enumerable: true,
  17081. configurable: true
  17082. });
  17083. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17084. get: function () {
  17085. return this._useVertexColors;
  17086. },
  17087. set: function (value) {
  17088. if (this._useVertexColors === value) {
  17089. return;
  17090. }
  17091. this._useVertexColors = value;
  17092. this._markSubMeshesAsAttributesDirty();
  17093. },
  17094. enumerable: true,
  17095. configurable: true
  17096. });
  17097. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17098. get: function () {
  17099. return this._computeBonesUsingShaders;
  17100. },
  17101. set: function (value) {
  17102. if (this._computeBonesUsingShaders === value) {
  17103. return;
  17104. }
  17105. this._computeBonesUsingShaders = value;
  17106. this._markSubMeshesAsAttributesDirty();
  17107. },
  17108. enumerable: true,
  17109. configurable: true
  17110. });
  17111. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17112. get: function () {
  17113. return this._numBoneInfluencers;
  17114. },
  17115. set: function (value) {
  17116. if (this._numBoneInfluencers === value) {
  17117. return;
  17118. }
  17119. this._numBoneInfluencers = value;
  17120. this._markSubMeshesAsAttributesDirty();
  17121. },
  17122. enumerable: true,
  17123. configurable: true
  17124. });
  17125. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17126. get: function () {
  17127. return this._applyFog;
  17128. },
  17129. set: function (value) {
  17130. if (this._applyFog === value) {
  17131. return;
  17132. }
  17133. this._applyFog = value;
  17134. this._markSubMeshesAsMiscDirty();
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17140. get: function () {
  17141. return this._layerMask;
  17142. },
  17143. set: function (value) {
  17144. if (value === this._layerMask) {
  17145. return;
  17146. }
  17147. this._layerMask = value;
  17148. this._resyncLightSources();
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17154. get: function () {
  17155. return this._collisionMask;
  17156. },
  17157. set: function (mask) {
  17158. this._collisionMask = !isNaN(mask) ? mask : -1;
  17159. },
  17160. enumerable: true,
  17161. configurable: true
  17162. });
  17163. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17164. get: function () {
  17165. return this._collisionGroup;
  17166. },
  17167. set: function (mask) {
  17168. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17169. },
  17170. enumerable: true,
  17171. configurable: true
  17172. });
  17173. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17174. get: function () {
  17175. return null;
  17176. },
  17177. enumerable: true,
  17178. configurable: true
  17179. });
  17180. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17181. get: function () {
  17182. return this._skeleton;
  17183. },
  17184. set: function (value) {
  17185. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17186. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17187. }
  17188. if (value && value.needInitialSkinMatrix) {
  17189. value._registerMeshWithPoseMatrix(this);
  17190. }
  17191. this._skeleton = value;
  17192. if (!this._skeleton) {
  17193. this._bonesTransformMatrices = null;
  17194. }
  17195. this._markSubMeshesAsAttributesDirty();
  17196. },
  17197. enumerable: true,
  17198. configurable: true
  17199. });
  17200. /**
  17201. * Returns the string "AbstractMesh"
  17202. */
  17203. AbstractMesh.prototype.getClassName = function () {
  17204. return "AbstractMesh";
  17205. };
  17206. /**
  17207. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17208. */
  17209. AbstractMesh.prototype.toString = function (fullDetails) {
  17210. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17211. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17212. if (this._skeleton) {
  17213. ret += ", skeleton: " + this._skeleton.name;
  17214. }
  17215. if (fullDetails) {
  17216. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17217. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17218. }
  17219. return ret;
  17220. };
  17221. AbstractMesh.prototype._rebuild = function () {
  17222. if (this._occlusionQuery) {
  17223. this._occlusionQuery = null;
  17224. }
  17225. if (this._edgesRenderer) {
  17226. this._edgesRenderer._rebuild();
  17227. }
  17228. if (!this.subMeshes) {
  17229. return;
  17230. }
  17231. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17232. var subMesh = _a[_i];
  17233. subMesh._rebuild();
  17234. }
  17235. };
  17236. AbstractMesh.prototype._resyncLightSources = function () {
  17237. this._lightSources.length = 0;
  17238. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17239. var light = _a[_i];
  17240. if (!light.isEnabled()) {
  17241. continue;
  17242. }
  17243. if (light.canAffectMesh(this)) {
  17244. this._lightSources.push(light);
  17245. }
  17246. }
  17247. this._markSubMeshesAsLightDirty();
  17248. };
  17249. AbstractMesh.prototype._resyncLighSource = function (light) {
  17250. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17251. var index = this._lightSources.indexOf(light);
  17252. if (index === -1) {
  17253. if (!isIn) {
  17254. return;
  17255. }
  17256. this._lightSources.push(light);
  17257. }
  17258. else {
  17259. if (isIn) {
  17260. return;
  17261. }
  17262. this._lightSources.splice(index, 1);
  17263. }
  17264. this._markSubMeshesAsLightDirty();
  17265. };
  17266. AbstractMesh.prototype._removeLightSource = function (light) {
  17267. var index = this._lightSources.indexOf(light);
  17268. if (index === -1) {
  17269. return;
  17270. }
  17271. this._lightSources.splice(index, 1);
  17272. this._markSubMeshesAsLightDirty();
  17273. };
  17274. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17275. if (!this.subMeshes) {
  17276. return;
  17277. }
  17278. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17279. var subMesh = _a[_i];
  17280. if (subMesh._materialDefines) {
  17281. func(subMesh._materialDefines);
  17282. }
  17283. }
  17284. };
  17285. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17286. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17287. };
  17288. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17289. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17290. };
  17291. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17292. if (!this.subMeshes) {
  17293. return;
  17294. }
  17295. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17296. var subMesh = _a[_i];
  17297. var material = subMesh.getMaterial();
  17298. if (material) {
  17299. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17300. }
  17301. }
  17302. };
  17303. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17304. /**
  17305. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17306. * Default : (1.0, 1.0, 1.0)
  17307. */
  17308. get: function () {
  17309. return this._scaling;
  17310. },
  17311. /**
  17312. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17313. * Default : (1.0, 1.0, 1.0)
  17314. */
  17315. set: function (newScaling) {
  17316. this._scaling = newScaling;
  17317. if (this.physicsImpostor) {
  17318. this.physicsImpostor.forceUpdate();
  17319. }
  17320. },
  17321. enumerable: true,
  17322. configurable: true
  17323. });
  17324. // Methods
  17325. /**
  17326. * Disables the mesh edger rendering mode.
  17327. * Returns the AbstractMesh.
  17328. */
  17329. AbstractMesh.prototype.disableEdgesRendering = function () {
  17330. if (this._edgesRenderer) {
  17331. this._edgesRenderer.dispose();
  17332. this._edgesRenderer = null;
  17333. }
  17334. return this;
  17335. };
  17336. /**
  17337. * Enables the edge rendering mode on the mesh.
  17338. * This mode makes the mesh edges visible.
  17339. * Returns the AbstractMesh.
  17340. */
  17341. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17342. if (epsilon === void 0) { epsilon = 0.95; }
  17343. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17344. this.disableEdgesRendering();
  17345. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17346. return this;
  17347. };
  17348. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17349. /**
  17350. * Returns true if the mesh is blocked. Used by the class Mesh.
  17351. * Returns the boolean `false` by default.
  17352. */
  17353. get: function () {
  17354. return false;
  17355. },
  17356. enumerable: true,
  17357. configurable: true
  17358. });
  17359. /**
  17360. * Returns the mesh itself by default, used by the class Mesh.
  17361. * Returned type : AbstractMesh
  17362. */
  17363. AbstractMesh.prototype.getLOD = function (camera) {
  17364. return this;
  17365. };
  17366. /**
  17367. * Returns 0 by default, used by the class Mesh.
  17368. * Returns an integer.
  17369. */
  17370. AbstractMesh.prototype.getTotalVertices = function () {
  17371. return 0;
  17372. };
  17373. /**
  17374. * Returns null by default, used by the class Mesh.
  17375. * Returned type : integer array
  17376. */
  17377. AbstractMesh.prototype.getIndices = function () {
  17378. return null;
  17379. };
  17380. /**
  17381. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17382. * Returned type : float array or Float32Array
  17383. */
  17384. AbstractMesh.prototype.getVerticesData = function (kind) {
  17385. return null;
  17386. };
  17387. /**
  17388. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17389. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17390. * The `data` are either a numeric array either a Float32Array.
  17391. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17392. * 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).
  17393. * Note that a new underlying VertexBuffer object is created each call.
  17394. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17395. *
  17396. * Possible `kind` values :
  17397. * - BABYLON.VertexBuffer.PositionKind
  17398. * - BABYLON.VertexBuffer.UVKind
  17399. * - BABYLON.VertexBuffer.UV2Kind
  17400. * - BABYLON.VertexBuffer.UV3Kind
  17401. * - BABYLON.VertexBuffer.UV4Kind
  17402. * - BABYLON.VertexBuffer.UV5Kind
  17403. * - BABYLON.VertexBuffer.UV6Kind
  17404. * - BABYLON.VertexBuffer.ColorKind
  17405. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17406. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17407. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17408. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17409. *
  17410. * Returns the Mesh.
  17411. */
  17412. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17413. return this;
  17414. };
  17415. /**
  17416. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17417. * If the mesh has no geometry, it is simply returned as it is.
  17418. * The `data` are either a numeric array either a Float32Array.
  17419. * No new underlying VertexBuffer object is created.
  17420. * 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.
  17421. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17422. *
  17423. * Possible `kind` values :
  17424. * - BABYLON.VertexBuffer.PositionKind
  17425. * - BABYLON.VertexBuffer.UVKind
  17426. * - BABYLON.VertexBuffer.UV2Kind
  17427. * - BABYLON.VertexBuffer.UV3Kind
  17428. * - BABYLON.VertexBuffer.UV4Kind
  17429. * - BABYLON.VertexBuffer.UV5Kind
  17430. * - BABYLON.VertexBuffer.UV6Kind
  17431. * - BABYLON.VertexBuffer.ColorKind
  17432. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17433. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17434. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17435. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17436. *
  17437. * Returns the Mesh.
  17438. */
  17439. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17440. return this;
  17441. };
  17442. /**
  17443. * Sets the mesh indices.
  17444. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17445. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17446. * This method creates a new index buffer each call.
  17447. * Returns the Mesh.
  17448. */
  17449. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17450. return this;
  17451. };
  17452. /** Returns false by default, used by the class Mesh.
  17453. * Returns a boolean
  17454. */
  17455. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17456. return false;
  17457. };
  17458. /**
  17459. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17460. * Returns a BoundingInfo
  17461. */
  17462. AbstractMesh.prototype.getBoundingInfo = function () {
  17463. if (this._masterMesh) {
  17464. return this._masterMesh.getBoundingInfo();
  17465. }
  17466. if (!this._boundingInfo) {
  17467. // this._boundingInfo is being created here
  17468. this._updateBoundingInfo();
  17469. }
  17470. // cannot be null.
  17471. return this._boundingInfo;
  17472. };
  17473. /**
  17474. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17475. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17476. */
  17477. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17478. if (includeDescendants === void 0) { includeDescendants = true; }
  17479. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17480. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17481. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17482. if (maxDimension === 0) {
  17483. return this;
  17484. }
  17485. var scale = 1 / maxDimension;
  17486. this.scaling.scaleInPlace(scale);
  17487. return this;
  17488. };
  17489. /**
  17490. * Sets a mesh new object BoundingInfo.
  17491. * Returns the AbstractMesh.
  17492. */
  17493. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17494. this._boundingInfo = boundingInfo;
  17495. return this;
  17496. };
  17497. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17498. get: function () {
  17499. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17500. },
  17501. enumerable: true,
  17502. configurable: true
  17503. });
  17504. AbstractMesh.prototype._preActivate = function () {
  17505. };
  17506. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17507. };
  17508. AbstractMesh.prototype._activate = function (renderId) {
  17509. this._renderId = renderId;
  17510. };
  17511. /**
  17512. * Returns the latest update of the World matrix
  17513. * Returns a Matrix.
  17514. */
  17515. AbstractMesh.prototype.getWorldMatrix = function () {
  17516. if (this._masterMesh) {
  17517. return this._masterMesh.getWorldMatrix();
  17518. }
  17519. return _super.prototype.getWorldMatrix.call(this);
  17520. };
  17521. /**
  17522. * Returns the latest update of the World matrix determinant.
  17523. */
  17524. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17525. if (this._masterMesh) {
  17526. return this._masterMesh._getWorldMatrixDeterminant();
  17527. }
  17528. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17529. };
  17530. // ================================== Point of View Movement =================================
  17531. /**
  17532. * Perform relative position change from the point of view of behind the front of the mesh.
  17533. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17534. * Supports definition of mesh facing forward or backward.
  17535. * @param {number} amountRight
  17536. * @param {number} amountUp
  17537. * @param {number} amountForward
  17538. *
  17539. * Returns the AbstractMesh.
  17540. */
  17541. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17542. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17543. return this;
  17544. };
  17545. /**
  17546. * Calculate relative position change from the point of view of behind the front of the mesh.
  17547. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17548. * Supports definition of mesh facing forward or backward.
  17549. * @param {number} amountRight
  17550. * @param {number} amountUp
  17551. * @param {number} amountForward
  17552. *
  17553. * Returns a new Vector3.
  17554. */
  17555. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17556. var rotMatrix = new BABYLON.Matrix();
  17557. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17558. rotQuaternion.toRotationMatrix(rotMatrix);
  17559. var translationDelta = BABYLON.Vector3.Zero();
  17560. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17561. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17562. return translationDelta;
  17563. };
  17564. // ================================== Point of View Rotation =================================
  17565. /**
  17566. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17567. * Supports definition of mesh facing forward or backward.
  17568. * @param {number} flipBack
  17569. * @param {number} twirlClockwise
  17570. * @param {number} tiltRight
  17571. *
  17572. * Returns the AbstractMesh.
  17573. */
  17574. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17575. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17576. return this;
  17577. };
  17578. /**
  17579. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17580. * Supports definition of mesh facing forward or backward.
  17581. * @param {number} flipBack
  17582. * @param {number} twirlClockwise
  17583. * @param {number} tiltRight
  17584. *
  17585. * Returns a new Vector3.
  17586. */
  17587. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17588. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17589. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17590. };
  17591. /**
  17592. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17593. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17594. */
  17595. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17596. if (includeDescendants === void 0) { includeDescendants = true; }
  17597. this.computeWorldMatrix(true);
  17598. var min;
  17599. var max;
  17600. var boundingInfo = this.getBoundingInfo();
  17601. if (!this.subMeshes) {
  17602. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17603. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17604. }
  17605. else {
  17606. min = boundingInfo.boundingBox.minimumWorld;
  17607. max = boundingInfo.boundingBox.maximumWorld;
  17608. }
  17609. if (includeDescendants) {
  17610. var descendants = this.getDescendants(false);
  17611. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17612. var descendant = descendants_1[_i];
  17613. var childMesh = descendant;
  17614. childMesh.computeWorldMatrix(true);
  17615. //make sure we have the needed params to get mix and max
  17616. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17617. continue;
  17618. }
  17619. var childBoundingInfo = childMesh.getBoundingInfo();
  17620. var boundingBox = childBoundingInfo.boundingBox;
  17621. var minBox = boundingBox.minimumWorld;
  17622. var maxBox = boundingBox.maximumWorld;
  17623. BABYLON.Tools.CheckExtends(minBox, min, max);
  17624. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17625. }
  17626. }
  17627. return {
  17628. min: min,
  17629. max: max
  17630. };
  17631. };
  17632. /**
  17633. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17634. * Returns the AbstractMesh.
  17635. */
  17636. AbstractMesh.prototype._updateBoundingInfo = function () {
  17637. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17638. this._boundingInfo.update(this.worldMatrixFromCache);
  17639. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17640. return this;
  17641. };
  17642. /**
  17643. * Update a mesh's children BoundingInfo objects only.
  17644. * Returns the AbstractMesh.
  17645. */
  17646. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17647. if (!this.subMeshes) {
  17648. return this;
  17649. }
  17650. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17651. var subMesh = this.subMeshes[subIndex];
  17652. if (!subMesh.IsGlobal) {
  17653. subMesh.updateBoundingInfo(matrix);
  17654. }
  17655. }
  17656. return this;
  17657. };
  17658. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17659. // Bounding info
  17660. this._updateBoundingInfo();
  17661. };
  17662. /**
  17663. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17664. * A mesh is in the frustum if its bounding box intersects the frustum.
  17665. * Boolean returned.
  17666. */
  17667. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17668. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17669. };
  17670. /**
  17671. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17672. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17673. * Boolean returned.
  17674. */
  17675. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17676. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17677. ;
  17678. };
  17679. /**
  17680. * True if the mesh intersects another mesh or a SolidParticle object.
  17681. * 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)
  17682. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17683. * Returns a boolean.
  17684. */
  17685. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17686. if (precise === void 0) { precise = false; }
  17687. if (!this._boundingInfo || !mesh._boundingInfo) {
  17688. return false;
  17689. }
  17690. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17691. return true;
  17692. }
  17693. if (includeDescendants) {
  17694. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17695. var child = _a[_i];
  17696. if (child.intersectsMesh(mesh, precise, true)) {
  17697. return true;
  17698. }
  17699. }
  17700. }
  17701. return false;
  17702. };
  17703. /**
  17704. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17705. * Returns a boolean.
  17706. */
  17707. AbstractMesh.prototype.intersectsPoint = function (point) {
  17708. if (!this._boundingInfo) {
  17709. return false;
  17710. }
  17711. return this._boundingInfo.intersectsPoint(point);
  17712. };
  17713. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17714. return this.physicsImpostor;
  17715. };
  17716. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17717. if (camera === void 0) { camera = null; }
  17718. if (!camera) {
  17719. camera = this.getScene().activeCamera;
  17720. }
  17721. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17722. };
  17723. /**
  17724. * Returns the distance from the mesh to the active camera.
  17725. * Returns a float.
  17726. */
  17727. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17728. if (camera === void 0) { camera = null; }
  17729. if (!camera) {
  17730. camera = this.getScene().activeCamera;
  17731. }
  17732. return this.absolutePosition.subtract(camera.position).length();
  17733. };
  17734. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17735. if (!this.physicsImpostor) {
  17736. return this;
  17737. }
  17738. this.physicsImpostor.applyImpulse(force, contactPoint);
  17739. return this;
  17740. };
  17741. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17742. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17743. return this;
  17744. }
  17745. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17746. mainPivot: pivot1,
  17747. connectedPivot: pivot2,
  17748. nativeParams: options
  17749. });
  17750. return this;
  17751. };
  17752. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17753. // Collisions
  17754. /**
  17755. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17756. * Default `false`.
  17757. */
  17758. get: function () {
  17759. return this._checkCollisions;
  17760. },
  17761. set: function (collisionEnabled) {
  17762. this._checkCollisions = collisionEnabled;
  17763. if (this.getScene().workerCollisions) {
  17764. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17765. }
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17771. /**
  17772. * Gets Collider object used to compute collisions (not physics)
  17773. */
  17774. get: function () {
  17775. return this._collider;
  17776. },
  17777. enumerable: true,
  17778. configurable: true
  17779. });
  17780. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17781. var globalPosition = this.getAbsolutePosition();
  17782. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17783. if (!this._collider) {
  17784. this._collider = new BABYLON.Collider();
  17785. }
  17786. this._collider._radius = this.ellipsoid;
  17787. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17788. return this;
  17789. };
  17790. // Submeshes octree
  17791. /**
  17792. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17793. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17794. * Returns an Octree of submeshes.
  17795. */
  17796. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17797. if (maxCapacity === void 0) { maxCapacity = 64; }
  17798. if (maxDepth === void 0) { maxDepth = 2; }
  17799. if (!this._submeshesOctree) {
  17800. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17801. }
  17802. this.computeWorldMatrix(true);
  17803. var boundingInfo = this.getBoundingInfo();
  17804. // Update octree
  17805. var bbox = boundingInfo.boundingBox;
  17806. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17807. return this._submeshesOctree;
  17808. };
  17809. // Collisions
  17810. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17811. this._generatePointsArray();
  17812. if (!this._positions) {
  17813. return this;
  17814. }
  17815. // Transformation
  17816. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17817. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17818. subMesh._lastColliderWorldVertices = [];
  17819. subMesh._trianglePlanes = [];
  17820. var start = subMesh.verticesStart;
  17821. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17822. for (var i = start; i < end; i++) {
  17823. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17824. }
  17825. }
  17826. // Collide
  17827. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17828. if (collider.collisionFound) {
  17829. collider.collidedMesh = this;
  17830. }
  17831. return this;
  17832. };
  17833. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17834. var subMeshes;
  17835. var len;
  17836. // Octrees
  17837. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17838. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17839. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17840. len = intersections.length;
  17841. subMeshes = intersections.data;
  17842. }
  17843. else {
  17844. subMeshes = this.subMeshes;
  17845. len = subMeshes.length;
  17846. }
  17847. for (var index = 0; index < len; index++) {
  17848. var subMesh = subMeshes[index];
  17849. // Bounding test
  17850. if (len > 1 && !subMesh._checkCollision(collider))
  17851. continue;
  17852. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17853. }
  17854. return this;
  17855. };
  17856. AbstractMesh.prototype._checkCollision = function (collider) {
  17857. // Bounding box test
  17858. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17859. return this;
  17860. // Transformation matrix
  17861. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17862. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17863. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17864. return this;
  17865. };
  17866. // Picking
  17867. AbstractMesh.prototype._generatePointsArray = function () {
  17868. return false;
  17869. };
  17870. /**
  17871. * Checks if the passed Ray intersects with the mesh.
  17872. * Returns an object PickingInfo.
  17873. */
  17874. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17875. var pickingInfo = new BABYLON.PickingInfo();
  17876. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17877. return pickingInfo;
  17878. }
  17879. if (!this._generatePointsArray()) {
  17880. return pickingInfo;
  17881. }
  17882. var intersectInfo = null;
  17883. // Octrees
  17884. var subMeshes;
  17885. var len;
  17886. if (this._submeshesOctree && this.useOctreeForPicking) {
  17887. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17888. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17889. len = intersections.length;
  17890. subMeshes = intersections.data;
  17891. }
  17892. else {
  17893. subMeshes = this.subMeshes;
  17894. len = subMeshes.length;
  17895. }
  17896. for (var index = 0; index < len; index++) {
  17897. var subMesh = subMeshes[index];
  17898. // Bounding test
  17899. if (len > 1 && !subMesh.canIntersects(ray))
  17900. continue;
  17901. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17902. if (currentIntersectInfo) {
  17903. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17904. intersectInfo = currentIntersectInfo;
  17905. intersectInfo.subMeshId = index;
  17906. if (fastCheck) {
  17907. break;
  17908. }
  17909. }
  17910. }
  17911. }
  17912. if (intersectInfo) {
  17913. // Get picked point
  17914. var world = this.getWorldMatrix();
  17915. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17916. var direction = ray.direction.clone();
  17917. direction = direction.scale(intersectInfo.distance);
  17918. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17919. var pickedPoint = worldOrigin.add(worldDirection);
  17920. // Return result
  17921. pickingInfo.hit = true;
  17922. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17923. pickingInfo.pickedPoint = pickedPoint;
  17924. pickingInfo.pickedMesh = this;
  17925. pickingInfo.bu = intersectInfo.bu || 0;
  17926. pickingInfo.bv = intersectInfo.bv || 0;
  17927. pickingInfo.faceId = intersectInfo.faceId;
  17928. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17929. return pickingInfo;
  17930. }
  17931. return pickingInfo;
  17932. };
  17933. /**
  17934. * Clones the mesh, used by the class Mesh.
  17935. * Just returns `null` for an AbstractMesh.
  17936. */
  17937. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17938. return null;
  17939. };
  17940. /**
  17941. * Disposes all the mesh submeshes.
  17942. * Returns the AbstractMesh.
  17943. */
  17944. AbstractMesh.prototype.releaseSubMeshes = function () {
  17945. if (this.subMeshes) {
  17946. while (this.subMeshes.length) {
  17947. this.subMeshes[0].dispose();
  17948. }
  17949. }
  17950. else {
  17951. this.subMeshes = new Array();
  17952. }
  17953. return this;
  17954. };
  17955. /**
  17956. * Disposes the AbstractMesh.
  17957. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17958. * Returns nothing.
  17959. */
  17960. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17961. var _this = this;
  17962. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17963. var index;
  17964. // Action manager
  17965. if (this.actionManager !== undefined && this.actionManager !== null) {
  17966. this.actionManager.dispose();
  17967. this.actionManager = null;
  17968. }
  17969. // Skeleton
  17970. this.skeleton = null;
  17971. // Physics
  17972. if (this.physicsImpostor) {
  17973. this.physicsImpostor.dispose();
  17974. }
  17975. // Intersections in progress
  17976. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17977. var other = this._intersectionsInProgress[index];
  17978. var pos = other._intersectionsInProgress.indexOf(this);
  17979. other._intersectionsInProgress.splice(pos, 1);
  17980. }
  17981. this._intersectionsInProgress = [];
  17982. // Lights
  17983. var lights = this.getScene().lights;
  17984. lights.forEach(function (light) {
  17985. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17986. if (meshIndex !== -1) {
  17987. light.includedOnlyMeshes.splice(meshIndex, 1);
  17988. }
  17989. meshIndex = light.excludedMeshes.indexOf(_this);
  17990. if (meshIndex !== -1) {
  17991. light.excludedMeshes.splice(meshIndex, 1);
  17992. }
  17993. // Shadow generators
  17994. var generator = light.getShadowGenerator();
  17995. if (generator) {
  17996. var shadowMap = generator.getShadowMap();
  17997. if (shadowMap && shadowMap.renderList) {
  17998. meshIndex = shadowMap.renderList.indexOf(_this);
  17999. if (meshIndex !== -1) {
  18000. shadowMap.renderList.splice(meshIndex, 1);
  18001. }
  18002. }
  18003. }
  18004. });
  18005. // Edges
  18006. if (this._edgesRenderer) {
  18007. this._edgesRenderer.dispose();
  18008. this._edgesRenderer = null;
  18009. }
  18010. // SubMeshes
  18011. if (this.getClassName() !== "InstancedMesh") {
  18012. this.releaseSubMeshes();
  18013. }
  18014. // Octree
  18015. var sceneOctree = this.getScene().selectionOctree;
  18016. if (sceneOctree !== undefined && sceneOctree !== null) {
  18017. var index = sceneOctree.dynamicContent.indexOf(this);
  18018. if (index !== -1) {
  18019. sceneOctree.dynamicContent.splice(index, 1);
  18020. }
  18021. }
  18022. // Query
  18023. var engine = this.getScene().getEngine();
  18024. if (this._occlusionQuery) {
  18025. this._isOcclusionQueryInProgress = false;
  18026. engine.deleteQuery(this._occlusionQuery);
  18027. this._occlusionQuery = null;
  18028. }
  18029. // Engine
  18030. engine.wipeCaches();
  18031. // Remove from scene
  18032. this.getScene().removeMesh(this);
  18033. if (disposeMaterialAndTextures) {
  18034. if (this.material) {
  18035. this.material.dispose(false, true);
  18036. }
  18037. }
  18038. if (!doNotRecurse) {
  18039. // Particles
  18040. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18041. if (this.getScene().particleSystems[index].emitter === this) {
  18042. this.getScene().particleSystems[index].dispose();
  18043. index--;
  18044. }
  18045. }
  18046. }
  18047. // facet data
  18048. if (this._facetDataEnabled) {
  18049. this.disableFacetData();
  18050. }
  18051. this.onAfterWorldMatrixUpdateObservable.clear();
  18052. this.onCollideObservable.clear();
  18053. this.onCollisionPositionChangeObservable.clear();
  18054. _super.prototype.dispose.call(this, doNotRecurse);
  18055. };
  18056. /**
  18057. * Adds the passed mesh as a child to the current mesh.
  18058. * Returns the AbstractMesh.
  18059. */
  18060. AbstractMesh.prototype.addChild = function (mesh) {
  18061. mesh.setParent(this);
  18062. return this;
  18063. };
  18064. /**
  18065. * Removes the passed mesh from the current mesh children list.
  18066. * Returns the AbstractMesh.
  18067. */
  18068. AbstractMesh.prototype.removeChild = function (mesh) {
  18069. mesh.setParent(null);
  18070. return this;
  18071. };
  18072. // Facet data
  18073. /**
  18074. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18075. * Returns the AbstractMesh.
  18076. */
  18077. AbstractMesh.prototype._initFacetData = function () {
  18078. if (!this._facetNormals) {
  18079. this._facetNormals = new Array();
  18080. }
  18081. if (!this._facetPositions) {
  18082. this._facetPositions = new Array();
  18083. }
  18084. if (!this._facetPartitioning) {
  18085. this._facetPartitioning = new Array();
  18086. }
  18087. this._facetNb = (this.getIndices().length / 3) | 0;
  18088. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18089. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18090. for (var f = 0; f < this._facetNb; f++) {
  18091. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18092. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18093. }
  18094. this._facetDataEnabled = true;
  18095. return this;
  18096. };
  18097. /**
  18098. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18099. * This method can be called within the render loop.
  18100. * 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.
  18101. * Returns the AbstractMesh.
  18102. */
  18103. AbstractMesh.prototype.updateFacetData = function () {
  18104. if (!this._facetDataEnabled) {
  18105. this._initFacetData();
  18106. }
  18107. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18108. var indices = this.getIndices();
  18109. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18110. var bInfo = this.getBoundingInfo();
  18111. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18112. // init arrays, matrix and sort function on first call
  18113. this._facetDepthSortEnabled = true;
  18114. if (indices instanceof Uint16Array) {
  18115. this._depthSortedIndices = new Uint16Array(indices);
  18116. }
  18117. else if (indices instanceof Uint32Array) {
  18118. this._depthSortedIndices = new Uint32Array(indices);
  18119. }
  18120. else {
  18121. var needs32bits = false;
  18122. for (var i = 0; i < indices.length; i++) {
  18123. if (indices[i] > 65535) {
  18124. needs32bits = true;
  18125. break;
  18126. }
  18127. }
  18128. if (needs32bits) {
  18129. this._depthSortedIndices = new Uint32Array(indices);
  18130. }
  18131. else {
  18132. this._depthSortedIndices = new Uint16Array(indices);
  18133. }
  18134. }
  18135. this._facetDepthSortFunction = function (f1, f2) {
  18136. return (f2.sqDistance - f1.sqDistance);
  18137. };
  18138. if (!this._facetDepthSortFrom) {
  18139. var camera = this.getScene().activeCamera;
  18140. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18141. }
  18142. this._depthSortedFacets = [];
  18143. for (var f = 0; f < this._facetNb; f++) {
  18144. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18145. this._depthSortedFacets.push(depthSortedFacet);
  18146. }
  18147. this._invertedMatrix = BABYLON.Matrix.Identity();
  18148. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18149. }
  18150. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18151. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18152. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18153. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18154. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18155. this._subDiv.max = this._partitioningSubdivisions;
  18156. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18157. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18158. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18159. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18160. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18161. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18162. // set the parameters for ComputeNormals()
  18163. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18164. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18165. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18166. this._facetParameters.bInfo = bInfo;
  18167. this._facetParameters.bbSize = this._bbSize;
  18168. this._facetParameters.subDiv = this._subDiv;
  18169. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18170. this._facetParameters.depthSort = this._facetDepthSort;
  18171. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18172. this.computeWorldMatrix(true);
  18173. this._worldMatrix.invertToRef(this._invertedMatrix);
  18174. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18175. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18176. }
  18177. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18178. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18179. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18180. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18181. var l = (this._depthSortedIndices.length / 3) | 0;
  18182. for (var f = 0; f < l; f++) {
  18183. var sind = this._depthSortedFacets[f].ind;
  18184. this._depthSortedIndices[f * 3] = indices[sind];
  18185. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18186. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18187. }
  18188. this.updateIndices(this._depthSortedIndices);
  18189. }
  18190. return this;
  18191. };
  18192. /**
  18193. * Returns the facetLocalNormals array.
  18194. * The normals are expressed in the mesh local space.
  18195. */
  18196. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18197. if (!this._facetNormals) {
  18198. this.updateFacetData();
  18199. }
  18200. return this._facetNormals;
  18201. };
  18202. /**
  18203. * Returns the facetLocalPositions array.
  18204. * The facet positions are expressed in the mesh local space.
  18205. */
  18206. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18207. if (!this._facetPositions) {
  18208. this.updateFacetData();
  18209. }
  18210. return this._facetPositions;
  18211. };
  18212. /**
  18213. * Returns the facetLocalPartioning array.
  18214. */
  18215. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18216. if (!this._facetPartitioning) {
  18217. this.updateFacetData();
  18218. }
  18219. return this._facetPartitioning;
  18220. };
  18221. /**
  18222. * Returns the i-th facet position in the world system.
  18223. * This method allocates a new Vector3 per call.
  18224. */
  18225. AbstractMesh.prototype.getFacetPosition = function (i) {
  18226. var pos = BABYLON.Vector3.Zero();
  18227. this.getFacetPositionToRef(i, pos);
  18228. return pos;
  18229. };
  18230. /**
  18231. * Sets the reference Vector3 with the i-th facet position in the world system.
  18232. * Returns the AbstractMesh.
  18233. */
  18234. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18235. var localPos = (this.getFacetLocalPositions())[i];
  18236. var world = this.getWorldMatrix();
  18237. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18238. return this;
  18239. };
  18240. /**
  18241. * Returns the i-th facet normal in the world system.
  18242. * This method allocates a new Vector3 per call.
  18243. */
  18244. AbstractMesh.prototype.getFacetNormal = function (i) {
  18245. var norm = BABYLON.Vector3.Zero();
  18246. this.getFacetNormalToRef(i, norm);
  18247. return norm;
  18248. };
  18249. /**
  18250. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18251. * Returns the AbstractMesh.
  18252. */
  18253. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18254. var localNorm = (this.getFacetLocalNormals())[i];
  18255. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18256. return this;
  18257. };
  18258. /**
  18259. * 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).
  18260. */
  18261. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18262. var bInfo = this.getBoundingInfo();
  18263. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18264. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18265. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18266. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18267. return null;
  18268. }
  18269. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18270. };
  18271. /**
  18272. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18273. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18274. * 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.
  18275. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18276. * 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.
  18277. */
  18278. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18279. if (checkFace === void 0) { checkFace = false; }
  18280. if (facing === void 0) { facing = true; }
  18281. var world = this.getWorldMatrix();
  18282. var invMat = BABYLON.Tmp.Matrix[5];
  18283. world.invertToRef(invMat);
  18284. var invVect = BABYLON.Tmp.Vector3[8];
  18285. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18286. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18287. if (projected) {
  18288. // tranform the local computed projected vector to world coordinates
  18289. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18290. }
  18291. return closest;
  18292. };
  18293. /**
  18294. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18295. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18296. * 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.
  18297. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18298. * 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.
  18299. */
  18300. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18301. if (checkFace === void 0) { checkFace = false; }
  18302. if (facing === void 0) { facing = true; }
  18303. var closest = null;
  18304. var tmpx = 0.0;
  18305. var tmpy = 0.0;
  18306. var tmpz = 0.0;
  18307. var d = 0.0; // tmp dot facet normal * facet position
  18308. var t0 = 0.0;
  18309. var projx = 0.0;
  18310. var projy = 0.0;
  18311. var projz = 0.0;
  18312. // Get all the facets in the same partitioning block than (x, y, z)
  18313. var facetPositions = this.getFacetLocalPositions();
  18314. var facetNormals = this.getFacetLocalNormals();
  18315. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18316. if (!facetsInBlock) {
  18317. return null;
  18318. }
  18319. // Get the closest facet to (x, y, z)
  18320. var shortest = Number.MAX_VALUE; // init distance vars
  18321. var tmpDistance = shortest;
  18322. var fib; // current facet in the block
  18323. var norm; // current facet normal
  18324. var p0; // current facet barycenter position
  18325. // loop on all the facets in the current partitioning block
  18326. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18327. fib = facetsInBlock[idx];
  18328. norm = facetNormals[fib];
  18329. p0 = facetPositions[fib];
  18330. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18331. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18332. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18333. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18334. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18335. projx = x + norm.x * t0;
  18336. projy = y + norm.y * t0;
  18337. projz = z + norm.z * t0;
  18338. tmpx = projx - x;
  18339. tmpy = projy - y;
  18340. tmpz = projz - z;
  18341. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18342. if (tmpDistance < shortest) {
  18343. shortest = tmpDistance;
  18344. closest = fib;
  18345. if (projected) {
  18346. projected.x = projx;
  18347. projected.y = projy;
  18348. projected.z = projz;
  18349. }
  18350. }
  18351. }
  18352. }
  18353. return closest;
  18354. };
  18355. /**
  18356. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18357. */
  18358. AbstractMesh.prototype.getFacetDataParameters = function () {
  18359. return this._facetParameters;
  18360. };
  18361. /**
  18362. * Disables the feature FacetData and frees the related memory.
  18363. * Returns the AbstractMesh.
  18364. */
  18365. AbstractMesh.prototype.disableFacetData = function () {
  18366. if (this._facetDataEnabled) {
  18367. this._facetDataEnabled = false;
  18368. this._facetPositions = new Array();
  18369. this._facetNormals = new Array();
  18370. this._facetPartitioning = new Array();
  18371. this._facetParameters = null;
  18372. this._depthSortedIndices = new Uint32Array(0);
  18373. }
  18374. return this;
  18375. };
  18376. /**
  18377. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18378. * Returns the mesh.
  18379. */
  18380. AbstractMesh.prototype.updateIndices = function (indices) {
  18381. return this;
  18382. };
  18383. /**
  18384. * The mesh Geometry. Actually used by the Mesh object.
  18385. * Returns a blank geometry object.
  18386. */
  18387. /**
  18388. * Creates new normals data for the mesh.
  18389. * @param updatable.
  18390. */
  18391. AbstractMesh.prototype.createNormals = function (updatable) {
  18392. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18393. var indices = this.getIndices();
  18394. var normals;
  18395. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18396. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18397. }
  18398. else {
  18399. normals = [];
  18400. }
  18401. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18402. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18403. };
  18404. /**
  18405. * Align the mesh with a normal.
  18406. * Returns the mesh.
  18407. */
  18408. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18409. if (!upDirection) {
  18410. upDirection = BABYLON.Axis.Y;
  18411. }
  18412. var axisX = BABYLON.Tmp.Vector3[0];
  18413. var axisZ = BABYLON.Tmp.Vector3[1];
  18414. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18415. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18416. if (this.rotationQuaternion) {
  18417. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18418. }
  18419. else {
  18420. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18421. }
  18422. return this;
  18423. };
  18424. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18425. var engine = this.getEngine();
  18426. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18427. this._isOccluded = false;
  18428. return;
  18429. }
  18430. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18431. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18432. if (isOcclusionQueryAvailable) {
  18433. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18434. this._isOcclusionQueryInProgress = false;
  18435. this._occlusionInternalRetryCounter = 0;
  18436. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18437. }
  18438. else {
  18439. this._occlusionInternalRetryCounter++;
  18440. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18441. this._isOcclusionQueryInProgress = false;
  18442. this._occlusionInternalRetryCounter = 0;
  18443. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18444. // if strict continue the last state of the object.
  18445. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18446. }
  18447. else {
  18448. return;
  18449. }
  18450. }
  18451. }
  18452. var scene = this.getScene();
  18453. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18454. if (!this._occlusionQuery) {
  18455. this._occlusionQuery = engine.createQuery();
  18456. }
  18457. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18458. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18459. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18460. this._isOcclusionQueryInProgress = true;
  18461. };
  18462. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18463. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18464. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18465. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18466. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18467. return AbstractMesh;
  18468. }(BABYLON.TransformNode));
  18469. BABYLON.AbstractMesh = AbstractMesh;
  18470. })(BABYLON || (BABYLON = {}));
  18471. //# sourceMappingURL=babylon.abstractMesh.js.map
  18472. var BABYLON;
  18473. (function (BABYLON) {
  18474. /**
  18475. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18476. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18477. * 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.
  18478. */
  18479. var Light = /** @class */ (function (_super) {
  18480. __extends(Light, _super);
  18481. /**
  18482. * Creates a Light object in the scene.
  18483. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18484. * @param name The firendly name of the light
  18485. * @param scene The scene the light belongs too
  18486. */
  18487. function Light(name, scene) {
  18488. var _this = _super.call(this, name, scene) || this;
  18489. /**
  18490. * Diffuse gives the basic color to an object.
  18491. */
  18492. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18493. /**
  18494. * Specular produces a highlight color on an object.
  18495. * Note: This is note affecting PBR materials.
  18496. */
  18497. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18498. /**
  18499. * Strength of the light.
  18500. * Note: By default it is define in the framework own unit.
  18501. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18502. */
  18503. _this.intensity = 1.0;
  18504. /**
  18505. * Defines how far from the source the light is impacting in scene units.
  18506. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18507. */
  18508. _this.range = Number.MAX_VALUE;
  18509. /**
  18510. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18511. * of light.
  18512. */
  18513. _this._photometricScale = 1.0;
  18514. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18515. _this._radius = 0.00001;
  18516. /**
  18517. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18518. * exceeding the number allowed of the materials.
  18519. */
  18520. _this.renderPriority = 0;
  18521. /**
  18522. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18523. * the current shadow generator.
  18524. */
  18525. _this.shadowEnabled = true;
  18526. _this._excludeWithLayerMask = 0;
  18527. _this._includeOnlyWithLayerMask = 0;
  18528. _this._lightmapMode = 0;
  18529. /**
  18530. * @ignore Internal use only.
  18531. */
  18532. _this._excludedMeshesIds = new Array();
  18533. /**
  18534. * @ignore Internal use only.
  18535. */
  18536. _this._includedOnlyMeshesIds = new Array();
  18537. _this.getScene().addLight(_this);
  18538. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18539. _this._buildUniformLayout();
  18540. _this.includedOnlyMeshes = new Array();
  18541. _this.excludedMeshes = new Array();
  18542. _this._resyncMeshes();
  18543. return _this;
  18544. }
  18545. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18546. /**
  18547. * If every light affecting the material is in this lightmapMode,
  18548. * material.lightmapTexture adds or multiplies
  18549. * (depends on material.useLightmapAsShadowmap)
  18550. * after every other light calculations.
  18551. */
  18552. get: function () {
  18553. return Light._LIGHTMAP_DEFAULT;
  18554. },
  18555. enumerable: true,
  18556. configurable: true
  18557. });
  18558. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18559. /**
  18560. * material.lightmapTexture as only diffuse lighting from this light
  18561. * adds only specular lighting from this light
  18562. * adds dynamic shadows
  18563. */
  18564. get: function () {
  18565. return Light._LIGHTMAP_SPECULAR;
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18571. /**
  18572. * material.lightmapTexture as only lighting
  18573. * no light calculation from this light
  18574. * only adds dynamic shadows from this light
  18575. */
  18576. get: function () {
  18577. return Light._LIGHTMAP_SHADOWSONLY;
  18578. },
  18579. enumerable: true,
  18580. configurable: true
  18581. });
  18582. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18583. /**
  18584. * Each light type uses the default quantity according to its type:
  18585. * point/spot lights use luminous intensity
  18586. * directional lights use illuminance
  18587. */
  18588. get: function () {
  18589. return Light._INTENSITYMODE_AUTOMATIC;
  18590. },
  18591. enumerable: true,
  18592. configurable: true
  18593. });
  18594. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18595. /**
  18596. * lumen (lm)
  18597. */
  18598. get: function () {
  18599. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18605. /**
  18606. * candela (lm/sr)
  18607. */
  18608. get: function () {
  18609. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18610. },
  18611. enumerable: true,
  18612. configurable: true
  18613. });
  18614. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18615. /**
  18616. * lux (lm/m^2)
  18617. */
  18618. get: function () {
  18619. return Light._INTENSITYMODE_ILLUMINANCE;
  18620. },
  18621. enumerable: true,
  18622. configurable: true
  18623. });
  18624. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18625. /**
  18626. * nit (cd/m^2)
  18627. */
  18628. get: function () {
  18629. return Light._INTENSITYMODE_LUMINANCE;
  18630. },
  18631. enumerable: true,
  18632. configurable: true
  18633. });
  18634. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18635. /**
  18636. * Light type const id of the point light.
  18637. */
  18638. get: function () {
  18639. return Light._LIGHTTYPEID_POINTLIGHT;
  18640. },
  18641. enumerable: true,
  18642. configurable: true
  18643. });
  18644. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18645. /**
  18646. * Light type const id of the directional light.
  18647. */
  18648. get: function () {
  18649. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18650. },
  18651. enumerable: true,
  18652. configurable: true
  18653. });
  18654. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18655. /**
  18656. * Light type const id of the spot light.
  18657. */
  18658. get: function () {
  18659. return Light._LIGHTTYPEID_SPOTLIGHT;
  18660. },
  18661. enumerable: true,
  18662. configurable: true
  18663. });
  18664. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18665. /**
  18666. * Light type const id of the hemispheric light.
  18667. */
  18668. get: function () {
  18669. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. Object.defineProperty(Light.prototype, "intensityMode", {
  18675. /**
  18676. * Gets the photometric scale used to interpret the intensity.
  18677. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18678. */
  18679. get: function () {
  18680. return this._intensityMode;
  18681. },
  18682. /**
  18683. * Sets the photometric scale used to interpret the intensity.
  18684. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18685. */
  18686. set: function (value) {
  18687. this._intensityMode = value;
  18688. this._computePhotometricScale();
  18689. },
  18690. enumerable: true,
  18691. configurable: true
  18692. });
  18693. ;
  18694. ;
  18695. Object.defineProperty(Light.prototype, "radius", {
  18696. /**
  18697. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18698. */
  18699. get: function () {
  18700. return this._radius;
  18701. },
  18702. /**
  18703. * sets the light radius used by PBR Materials to simulate soft area lights.
  18704. */
  18705. set: function (value) {
  18706. this._radius = value;
  18707. this._computePhotometricScale();
  18708. },
  18709. enumerable: true,
  18710. configurable: true
  18711. });
  18712. ;
  18713. ;
  18714. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18715. /**
  18716. * Gets the only meshes impacted by this light.
  18717. */
  18718. get: function () {
  18719. return this._includedOnlyMeshes;
  18720. },
  18721. /**
  18722. * Sets the only meshes impacted by this light.
  18723. */
  18724. set: function (value) {
  18725. this._includedOnlyMeshes = value;
  18726. this._hookArrayForIncludedOnly(value);
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18732. /**
  18733. * Gets the meshes not impacted by this light.
  18734. */
  18735. get: function () {
  18736. return this._excludedMeshes;
  18737. },
  18738. /**
  18739. * Sets the meshes not impacted by this light.
  18740. */
  18741. set: function (value) {
  18742. this._excludedMeshes = value;
  18743. this._hookArrayForExcluded(value);
  18744. },
  18745. enumerable: true,
  18746. configurable: true
  18747. });
  18748. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18749. /**
  18750. * Gets the layer id use to find what meshes are not impacted by the light.
  18751. * Inactive if 0
  18752. */
  18753. get: function () {
  18754. return this._excludeWithLayerMask;
  18755. },
  18756. /**
  18757. * Sets the layer id use to find what meshes are not impacted by the light.
  18758. * Inactive if 0
  18759. */
  18760. set: function (value) {
  18761. this._excludeWithLayerMask = value;
  18762. this._resyncMeshes();
  18763. },
  18764. enumerable: true,
  18765. configurable: true
  18766. });
  18767. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18768. /**
  18769. * Gets the layer id use to find what meshes are impacted by the light.
  18770. * Inactive if 0
  18771. */
  18772. get: function () {
  18773. return this._includeOnlyWithLayerMask;
  18774. },
  18775. /**
  18776. * Sets the layer id use to find what meshes are impacted by the light.
  18777. * Inactive if 0
  18778. */
  18779. set: function (value) {
  18780. this._includeOnlyWithLayerMask = value;
  18781. this._resyncMeshes();
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. Object.defineProperty(Light.prototype, "lightmapMode", {
  18787. /**
  18788. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18789. */
  18790. get: function () {
  18791. return this._lightmapMode;
  18792. },
  18793. /**
  18794. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18795. */
  18796. set: function (value) {
  18797. if (this._lightmapMode === value) {
  18798. return;
  18799. }
  18800. this._lightmapMode = value;
  18801. this._markMeshesAsLightDirty();
  18802. },
  18803. enumerable: true,
  18804. configurable: true
  18805. });
  18806. /**
  18807. * Returns the string "Light".
  18808. * @returns the class name
  18809. */
  18810. Light.prototype.getClassName = function () {
  18811. return "Light";
  18812. };
  18813. /**
  18814. * Converts the light information to a readable string for debug purpose.
  18815. * @param fullDetails Supports for multiple levels of logging within scene loading
  18816. * @returns the human readable light info
  18817. */
  18818. Light.prototype.toString = function (fullDetails) {
  18819. var ret = "Name: " + this.name;
  18820. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18821. if (this.animations) {
  18822. for (var i = 0; i < this.animations.length; i++) {
  18823. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18824. }
  18825. }
  18826. if (fullDetails) {
  18827. }
  18828. return ret;
  18829. };
  18830. /**
  18831. * Set the enabled state of this node.
  18832. * @param value - the new enabled state
  18833. * @see isEnabled
  18834. */
  18835. Light.prototype.setEnabled = function (value) {
  18836. _super.prototype.setEnabled.call(this, value);
  18837. this._resyncMeshes();
  18838. };
  18839. /**
  18840. * Returns the Light associated shadow generator if any.
  18841. * @return the associated shadow generator.
  18842. */
  18843. Light.prototype.getShadowGenerator = function () {
  18844. return this._shadowGenerator;
  18845. };
  18846. /**
  18847. * Returns a Vector3, the absolute light position in the World.
  18848. * @returns the world space position of the light
  18849. */
  18850. Light.prototype.getAbsolutePosition = function () {
  18851. return BABYLON.Vector3.Zero();
  18852. };
  18853. /**
  18854. * Specifies if the light will affect the passed mesh.
  18855. * @param mesh The mesh to test against the light
  18856. * @return true the mesh is affected otherwise, false.
  18857. */
  18858. Light.prototype.canAffectMesh = function (mesh) {
  18859. if (!mesh) {
  18860. return true;
  18861. }
  18862. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18863. return false;
  18864. }
  18865. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18866. return false;
  18867. }
  18868. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18869. return false;
  18870. }
  18871. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18872. return false;
  18873. }
  18874. return true;
  18875. };
  18876. /**
  18877. * Computes and Returns the light World matrix.
  18878. * @returns the world matrix
  18879. */
  18880. Light.prototype.getWorldMatrix = function () {
  18881. this._currentRenderId = this.getScene().getRenderId();
  18882. var worldMatrix = this._getWorldMatrix();
  18883. if (this.parent && this.parent.getWorldMatrix) {
  18884. if (!this._parentedWorldMatrix) {
  18885. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18886. }
  18887. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18888. this._markSyncedWithParent();
  18889. return this._parentedWorldMatrix;
  18890. }
  18891. return worldMatrix;
  18892. };
  18893. /**
  18894. * Sort function to order lights for rendering.
  18895. * @param a First Light object to compare to second.
  18896. * @param b Second Light object to compare first.
  18897. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18898. */
  18899. Light.CompareLightsPriority = function (a, b) {
  18900. //shadow-casting lights have priority over non-shadow-casting lights
  18901. //the renderPrioirty is a secondary sort criterion
  18902. if (a.shadowEnabled !== b.shadowEnabled) {
  18903. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18904. }
  18905. return b.renderPriority - a.renderPriority;
  18906. };
  18907. /**
  18908. * Disposes the light.
  18909. */
  18910. Light.prototype.dispose = function () {
  18911. if (this._shadowGenerator) {
  18912. this._shadowGenerator.dispose();
  18913. this._shadowGenerator = null;
  18914. }
  18915. // Animations
  18916. this.getScene().stopAnimation(this);
  18917. // Remove from meshes
  18918. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18919. var mesh = _a[_i];
  18920. mesh._removeLightSource(this);
  18921. }
  18922. this._uniformBuffer.dispose();
  18923. // Remove from scene
  18924. this.getScene().removeLight(this);
  18925. _super.prototype.dispose.call(this);
  18926. };
  18927. /**
  18928. * Returns the light type ID (integer).
  18929. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18930. */
  18931. Light.prototype.getTypeID = function () {
  18932. return 0;
  18933. };
  18934. /**
  18935. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18936. * @returns the scaled intensity in intensity mode unit
  18937. */
  18938. Light.prototype.getScaledIntensity = function () {
  18939. return this._photometricScale * this.intensity;
  18940. };
  18941. /**
  18942. * Returns a new Light object, named "name", from the current one.
  18943. * @param name The name of the cloned light
  18944. * @returns the new created light
  18945. */
  18946. Light.prototype.clone = function (name) {
  18947. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18948. if (!constructor) {
  18949. return null;
  18950. }
  18951. return BABYLON.SerializationHelper.Clone(constructor, this);
  18952. };
  18953. /**
  18954. * Serializes the current light into a Serialization object.
  18955. * @returns the serialized object.
  18956. */
  18957. Light.prototype.serialize = function () {
  18958. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18959. // Type
  18960. serializationObject.type = this.getTypeID();
  18961. // Parent
  18962. if (this.parent) {
  18963. serializationObject.parentId = this.parent.id;
  18964. }
  18965. // Inclusion / exclusions
  18966. if (this.excludedMeshes.length > 0) {
  18967. serializationObject.excludedMeshesIds = [];
  18968. this.excludedMeshes.forEach(function (mesh) {
  18969. serializationObject.excludedMeshesIds.push(mesh.id);
  18970. });
  18971. }
  18972. if (this.includedOnlyMeshes.length > 0) {
  18973. serializationObject.includedOnlyMeshesIds = [];
  18974. this.includedOnlyMeshes.forEach(function (mesh) {
  18975. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18976. });
  18977. }
  18978. // Animations
  18979. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18980. serializationObject.ranges = this.serializeAnimationRanges();
  18981. return serializationObject;
  18982. };
  18983. /**
  18984. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18985. * This new light is named "name" and added to the passed scene.
  18986. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18987. * @param name The friendly name of the light
  18988. * @param scene The scene the new light will belong to
  18989. * @returns the constructor function
  18990. */
  18991. Light.GetConstructorFromName = function (type, name, scene) {
  18992. switch (type) {
  18993. case 0:
  18994. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18995. case 1:
  18996. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18997. case 2:
  18998. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18999. case 3:
  19000. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19001. }
  19002. return null;
  19003. };
  19004. /**
  19005. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19006. * @param parsedLight The JSON representation of the light
  19007. * @param scene The scene to create the parsed light in
  19008. * @returns the created light after parsing
  19009. */
  19010. Light.Parse = function (parsedLight, scene) {
  19011. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19012. if (!constructor) {
  19013. return null;
  19014. }
  19015. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19016. // Inclusion / exclusions
  19017. if (parsedLight.excludedMeshesIds) {
  19018. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19019. }
  19020. if (parsedLight.includedOnlyMeshesIds) {
  19021. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19022. }
  19023. // Parent
  19024. if (parsedLight.parentId) {
  19025. light._waitingParentId = parsedLight.parentId;
  19026. }
  19027. // Animations
  19028. if (parsedLight.animations) {
  19029. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19030. var parsedAnimation = parsedLight.animations[animationIndex];
  19031. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19032. }
  19033. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19034. }
  19035. if (parsedLight.autoAnimate) {
  19036. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19037. }
  19038. return light;
  19039. };
  19040. Light.prototype._hookArrayForExcluded = function (array) {
  19041. var _this = this;
  19042. var oldPush = array.push;
  19043. array.push = function () {
  19044. var items = [];
  19045. for (var _i = 0; _i < arguments.length; _i++) {
  19046. items[_i] = arguments[_i];
  19047. }
  19048. var result = oldPush.apply(array, items);
  19049. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19050. var item = items_1[_a];
  19051. item._resyncLighSource(_this);
  19052. }
  19053. return result;
  19054. };
  19055. var oldSplice = array.splice;
  19056. array.splice = function (index, deleteCount) {
  19057. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19058. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19059. var item = deleted_1[_i];
  19060. item._resyncLighSource(_this);
  19061. }
  19062. return deleted;
  19063. };
  19064. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19065. var item = array_1[_i];
  19066. item._resyncLighSource(this);
  19067. }
  19068. };
  19069. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19070. var _this = this;
  19071. var oldPush = array.push;
  19072. array.push = function () {
  19073. var items = [];
  19074. for (var _i = 0; _i < arguments.length; _i++) {
  19075. items[_i] = arguments[_i];
  19076. }
  19077. var result = oldPush.apply(array, items);
  19078. _this._resyncMeshes();
  19079. return result;
  19080. };
  19081. var oldSplice = array.splice;
  19082. array.splice = function (index, deleteCount) {
  19083. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19084. _this._resyncMeshes();
  19085. return deleted;
  19086. };
  19087. this._resyncMeshes();
  19088. };
  19089. Light.prototype._resyncMeshes = function () {
  19090. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19091. var mesh = _a[_i];
  19092. mesh._resyncLighSource(this);
  19093. }
  19094. };
  19095. /**
  19096. * Forces the meshes to update their light related information in their rendering used effects
  19097. * @ignore Internal Use Only
  19098. */
  19099. Light.prototype._markMeshesAsLightDirty = function () {
  19100. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19101. var mesh = _a[_i];
  19102. if (mesh._lightSources.indexOf(this) !== -1) {
  19103. mesh._markSubMeshesAsLightDirty();
  19104. }
  19105. }
  19106. };
  19107. /**
  19108. * Recomputes the cached photometric scale if needed.
  19109. */
  19110. Light.prototype._computePhotometricScale = function () {
  19111. this._photometricScale = this._getPhotometricScale();
  19112. this.getScene().resetCachedMaterial();
  19113. };
  19114. /**
  19115. * Returns the Photometric Scale according to the light type and intensity mode.
  19116. */
  19117. Light.prototype._getPhotometricScale = function () {
  19118. var photometricScale = 0.0;
  19119. var lightTypeID = this.getTypeID();
  19120. //get photometric mode
  19121. var photometricMode = this.intensityMode;
  19122. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19123. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19124. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19125. }
  19126. else {
  19127. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19128. }
  19129. }
  19130. //compute photometric scale
  19131. switch (lightTypeID) {
  19132. case Light.LIGHTTYPEID_POINTLIGHT:
  19133. case Light.LIGHTTYPEID_SPOTLIGHT:
  19134. switch (photometricMode) {
  19135. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19136. photometricScale = 1.0 / (4.0 * Math.PI);
  19137. break;
  19138. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19139. photometricScale = 1.0;
  19140. break;
  19141. case Light.INTENSITYMODE_LUMINANCE:
  19142. photometricScale = this.radius * this.radius;
  19143. break;
  19144. }
  19145. break;
  19146. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19147. switch (photometricMode) {
  19148. case Light.INTENSITYMODE_ILLUMINANCE:
  19149. photometricScale = 1.0;
  19150. break;
  19151. case Light.INTENSITYMODE_LUMINANCE:
  19152. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19153. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19154. var apexAngleRadians = this.radius;
  19155. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19156. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19157. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19158. photometricScale = solidAngle;
  19159. break;
  19160. }
  19161. break;
  19162. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19163. // No fall off in hemisperic light.
  19164. photometricScale = 1.0;
  19165. break;
  19166. }
  19167. return photometricScale;
  19168. };
  19169. /**
  19170. * Reorder the light in the scene according to their defined priority.
  19171. * @ignore Internal Use Only
  19172. */
  19173. Light.prototype._reorderLightsInScene = function () {
  19174. var scene = this.getScene();
  19175. if (this._renderPriority != 0) {
  19176. scene.requireLightSorting = true;
  19177. }
  19178. this.getScene().sortLightsByPriority();
  19179. };
  19180. //lightmapMode Consts
  19181. Light._LIGHTMAP_DEFAULT = 0;
  19182. Light._LIGHTMAP_SPECULAR = 1;
  19183. Light._LIGHTMAP_SHADOWSONLY = 2;
  19184. // Intensity Mode Consts
  19185. Light._INTENSITYMODE_AUTOMATIC = 0;
  19186. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19187. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19188. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19189. Light._INTENSITYMODE_LUMINANCE = 4;
  19190. // Light types ids const.
  19191. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19192. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19193. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19194. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19195. __decorate([
  19196. BABYLON.serializeAsColor3()
  19197. ], Light.prototype, "diffuse", void 0);
  19198. __decorate([
  19199. BABYLON.serializeAsColor3()
  19200. ], Light.prototype, "specular", void 0);
  19201. __decorate([
  19202. BABYLON.serialize()
  19203. ], Light.prototype, "intensity", void 0);
  19204. __decorate([
  19205. BABYLON.serialize()
  19206. ], Light.prototype, "range", void 0);
  19207. __decorate([
  19208. BABYLON.serialize()
  19209. ], Light.prototype, "intensityMode", null);
  19210. __decorate([
  19211. BABYLON.serialize()
  19212. ], Light.prototype, "radius", null);
  19213. __decorate([
  19214. BABYLON.serialize()
  19215. ], Light.prototype, "_renderPriority", void 0);
  19216. __decorate([
  19217. BABYLON.expandToProperty("_reorderLightsInScene")
  19218. ], Light.prototype, "renderPriority", void 0);
  19219. __decorate([
  19220. BABYLON.serialize()
  19221. ], Light.prototype, "shadowEnabled", void 0);
  19222. __decorate([
  19223. BABYLON.serialize("excludeWithLayerMask")
  19224. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19225. __decorate([
  19226. BABYLON.serialize("includeOnlyWithLayerMask")
  19227. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19228. __decorate([
  19229. BABYLON.serialize("lightmapMode")
  19230. ], Light.prototype, "_lightmapMode", void 0);
  19231. return Light;
  19232. }(BABYLON.Node));
  19233. BABYLON.Light = Light;
  19234. })(BABYLON || (BABYLON = {}));
  19235. //# sourceMappingURL=babylon.light.js.map
  19236. var BABYLON;
  19237. (function (BABYLON) {
  19238. var Camera = /** @class */ (function (_super) {
  19239. __extends(Camera, _super);
  19240. function Camera(name, position, scene) {
  19241. var _this = _super.call(this, name, scene) || this;
  19242. /**
  19243. * The vector the camera should consider as up.
  19244. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19245. */
  19246. _this.upVector = BABYLON.Vector3.Up();
  19247. _this.orthoLeft = null;
  19248. _this.orthoRight = null;
  19249. _this.orthoBottom = null;
  19250. _this.orthoTop = null;
  19251. /**
  19252. * FOV is set in Radians. (default is 0.8)
  19253. */
  19254. _this.fov = 0.8;
  19255. _this.minZ = 1;
  19256. _this.maxZ = 10000.0;
  19257. _this.inertia = 0.9;
  19258. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19259. _this.isIntermediate = false;
  19260. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19261. /**
  19262. * Restricts the camera to viewing objects with the same layerMask.
  19263. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19264. */
  19265. _this.layerMask = 0x0FFFFFFF;
  19266. /**
  19267. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19268. */
  19269. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19270. // Camera rig members
  19271. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19272. _this._rigCameras = new Array();
  19273. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19274. _this._skipRendering = false;
  19275. _this.customRenderTargets = new Array();
  19276. // Observables
  19277. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19278. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19279. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19280. _this.onRestoreStateObservable = new BABYLON.Observable();
  19281. // Cache
  19282. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19283. _this._projectionMatrix = new BABYLON.Matrix();
  19284. _this._doNotComputeProjectionMatrix = false;
  19285. _this._postProcesses = new Array();
  19286. _this._transformMatrix = BABYLON.Matrix.Zero();
  19287. _this._activeMeshes = new BABYLON.SmartArray(256);
  19288. _this._globalPosition = BABYLON.Vector3.Zero();
  19289. _this._refreshFrustumPlanes = true;
  19290. _this.getScene().addCamera(_this);
  19291. if (!_this.getScene().activeCamera) {
  19292. _this.getScene().activeCamera = _this;
  19293. }
  19294. _this.position = position;
  19295. return _this;
  19296. }
  19297. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19298. get: function () {
  19299. return Camera._PERSPECTIVE_CAMERA;
  19300. },
  19301. enumerable: true,
  19302. configurable: true
  19303. });
  19304. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19305. get: function () {
  19306. return Camera._ORTHOGRAPHIC_CAMERA;
  19307. },
  19308. enumerable: true,
  19309. configurable: true
  19310. });
  19311. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19312. /**
  19313. * This is the default FOV mode for perspective cameras.
  19314. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19315. *
  19316. */
  19317. get: function () {
  19318. return Camera._FOVMODE_VERTICAL_FIXED;
  19319. },
  19320. enumerable: true,
  19321. configurable: true
  19322. });
  19323. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19324. /**
  19325. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19326. *
  19327. */
  19328. get: function () {
  19329. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19330. },
  19331. enumerable: true,
  19332. configurable: true
  19333. });
  19334. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19335. get: function () {
  19336. return Camera._RIG_MODE_NONE;
  19337. },
  19338. enumerable: true,
  19339. configurable: true
  19340. });
  19341. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19342. get: function () {
  19343. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19344. },
  19345. enumerable: true,
  19346. configurable: true
  19347. });
  19348. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19349. get: function () {
  19350. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19356. get: function () {
  19357. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19358. },
  19359. enumerable: true,
  19360. configurable: true
  19361. });
  19362. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19363. get: function () {
  19364. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19370. get: function () {
  19371. return Camera._RIG_MODE_VR;
  19372. },
  19373. enumerable: true,
  19374. configurable: true
  19375. });
  19376. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19377. get: function () {
  19378. return Camera._RIG_MODE_WEBVR;
  19379. },
  19380. enumerable: true,
  19381. configurable: true
  19382. });
  19383. /**
  19384. * Store current camera state (fov, position, etc..)
  19385. */
  19386. Camera.prototype.storeState = function () {
  19387. this._stateStored = true;
  19388. this._storedFov = this.fov;
  19389. return this;
  19390. };
  19391. /**
  19392. * Restores the camera state values if it has been stored. You must call storeState() first
  19393. */
  19394. Camera.prototype._restoreStateValues = function () {
  19395. if (!this._stateStored) {
  19396. return false;
  19397. }
  19398. this.fov = this._storedFov;
  19399. return true;
  19400. };
  19401. /**
  19402. * Restored camera state. You must call storeState() first
  19403. */
  19404. Camera.prototype.restoreState = function () {
  19405. if (this._restoreStateValues()) {
  19406. this.onRestoreStateObservable.notifyObservers(this);
  19407. return true;
  19408. }
  19409. return false;
  19410. };
  19411. Camera.prototype.getClassName = function () {
  19412. return "Camera";
  19413. };
  19414. /**
  19415. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19416. */
  19417. Camera.prototype.toString = function (fullDetails) {
  19418. var ret = "Name: " + this.name;
  19419. ret += ", type: " + this.getClassName();
  19420. if (this.animations) {
  19421. for (var i = 0; i < this.animations.length; i++) {
  19422. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19423. }
  19424. }
  19425. if (fullDetails) {
  19426. }
  19427. return ret;
  19428. };
  19429. Object.defineProperty(Camera.prototype, "globalPosition", {
  19430. get: function () {
  19431. return this._globalPosition;
  19432. },
  19433. enumerable: true,
  19434. configurable: true
  19435. });
  19436. Camera.prototype.getActiveMeshes = function () {
  19437. return this._activeMeshes;
  19438. };
  19439. Camera.prototype.isActiveMesh = function (mesh) {
  19440. return (this._activeMeshes.indexOf(mesh) !== -1);
  19441. };
  19442. //Cache
  19443. Camera.prototype._initCache = function () {
  19444. _super.prototype._initCache.call(this);
  19445. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19446. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19447. this._cache.mode = undefined;
  19448. this._cache.minZ = undefined;
  19449. this._cache.maxZ = undefined;
  19450. this._cache.fov = undefined;
  19451. this._cache.fovMode = undefined;
  19452. this._cache.aspectRatio = undefined;
  19453. this._cache.orthoLeft = undefined;
  19454. this._cache.orthoRight = undefined;
  19455. this._cache.orthoBottom = undefined;
  19456. this._cache.orthoTop = undefined;
  19457. this._cache.renderWidth = undefined;
  19458. this._cache.renderHeight = undefined;
  19459. };
  19460. Camera.prototype._updateCache = function (ignoreParentClass) {
  19461. if (!ignoreParentClass) {
  19462. _super.prototype._updateCache.call(this);
  19463. }
  19464. this._cache.position.copyFrom(this.position);
  19465. this._cache.upVector.copyFrom(this.upVector);
  19466. };
  19467. // Synchronized
  19468. Camera.prototype._isSynchronized = function () {
  19469. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19470. };
  19471. Camera.prototype._isSynchronizedViewMatrix = function () {
  19472. if (!_super.prototype._isSynchronized.call(this))
  19473. return false;
  19474. return this._cache.position.equals(this.position)
  19475. && this._cache.upVector.equals(this.upVector)
  19476. && this.isSynchronizedWithParent();
  19477. };
  19478. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19479. var check = this._cache.mode === this.mode
  19480. && this._cache.minZ === this.minZ
  19481. && this._cache.maxZ === this.maxZ;
  19482. if (!check) {
  19483. return false;
  19484. }
  19485. var engine = this.getEngine();
  19486. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19487. check = this._cache.fov === this.fov
  19488. && this._cache.fovMode === this.fovMode
  19489. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19490. }
  19491. else {
  19492. check = this._cache.orthoLeft === this.orthoLeft
  19493. && this._cache.orthoRight === this.orthoRight
  19494. && this._cache.orthoBottom === this.orthoBottom
  19495. && this._cache.orthoTop === this.orthoTop
  19496. && this._cache.renderWidth === engine.getRenderWidth()
  19497. && this._cache.renderHeight === engine.getRenderHeight();
  19498. }
  19499. return check;
  19500. };
  19501. // Controls
  19502. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19503. };
  19504. Camera.prototype.detachControl = function (element) {
  19505. };
  19506. Camera.prototype.update = function () {
  19507. this._checkInputs();
  19508. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19509. this._updateRigCameras();
  19510. }
  19511. };
  19512. Camera.prototype._checkInputs = function () {
  19513. this.onAfterCheckInputsObservable.notifyObservers(this);
  19514. };
  19515. Object.defineProperty(Camera.prototype, "rigCameras", {
  19516. get: function () {
  19517. return this._rigCameras;
  19518. },
  19519. enumerable: true,
  19520. configurable: true
  19521. });
  19522. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19523. get: function () {
  19524. return this._rigPostProcess;
  19525. },
  19526. enumerable: true,
  19527. configurable: true
  19528. });
  19529. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19530. // invalidate framebuffer
  19531. if (this._postProcesses.length > 0) {
  19532. this._postProcesses[0].markTextureDirty();
  19533. }
  19534. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19535. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19536. var cam = this._rigCameras[i];
  19537. var rigPostProcess = cam._rigPostProcess;
  19538. // for VR rig, there does not have to be a post process
  19539. if (rigPostProcess) {
  19540. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19541. if (isPass) {
  19542. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19543. cam.isIntermediate = this._postProcesses.length === 0;
  19544. }
  19545. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19546. rigPostProcess.markTextureDirty();
  19547. }
  19548. else {
  19549. cam._postProcesses = this._postProcesses.slice(0);
  19550. }
  19551. }
  19552. };
  19553. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19554. if (insertAt === void 0) { insertAt = null; }
  19555. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19556. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19557. return 0;
  19558. }
  19559. if (insertAt == null || insertAt < 0) {
  19560. this._postProcesses.push(postProcess);
  19561. }
  19562. else {
  19563. this._postProcesses.splice(insertAt, 0, postProcess);
  19564. }
  19565. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19566. return this._postProcesses.indexOf(postProcess);
  19567. };
  19568. Camera.prototype.detachPostProcess = function (postProcess) {
  19569. var idx = this._postProcesses.indexOf(postProcess);
  19570. if (idx !== -1) {
  19571. this._postProcesses.splice(idx, 1);
  19572. }
  19573. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19574. };
  19575. Camera.prototype.getWorldMatrix = function () {
  19576. if (!this._worldMatrix) {
  19577. this._worldMatrix = BABYLON.Matrix.Identity();
  19578. }
  19579. var viewMatrix = this.getViewMatrix();
  19580. viewMatrix.invertToRef(this._worldMatrix);
  19581. return this._worldMatrix;
  19582. };
  19583. Camera.prototype._getViewMatrix = function () {
  19584. return BABYLON.Matrix.Identity();
  19585. };
  19586. Camera.prototype.getViewMatrix = function (force) {
  19587. if (!force && this._isSynchronizedViewMatrix()) {
  19588. return this._computedViewMatrix;
  19589. }
  19590. this.updateCache();
  19591. this._computedViewMatrix = this._getViewMatrix();
  19592. this._currentRenderId = this.getScene().getRenderId();
  19593. this._refreshFrustumPlanes = true;
  19594. if (!this.parent || !this.parent.getWorldMatrix) {
  19595. this._globalPosition.copyFrom(this.position);
  19596. }
  19597. else {
  19598. if (!this._worldMatrix) {
  19599. this._worldMatrix = BABYLON.Matrix.Identity();
  19600. }
  19601. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19602. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19603. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19604. this._computedViewMatrix.invert();
  19605. this._markSyncedWithParent();
  19606. }
  19607. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19608. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19609. }
  19610. this.onViewMatrixChangedObservable.notifyObservers(this);
  19611. return this._computedViewMatrix;
  19612. };
  19613. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19614. this._doNotComputeProjectionMatrix = true;
  19615. if (projection !== undefined) {
  19616. this._projectionMatrix = projection;
  19617. }
  19618. };
  19619. ;
  19620. Camera.prototype.unfreezeProjectionMatrix = function () {
  19621. this._doNotComputeProjectionMatrix = false;
  19622. };
  19623. ;
  19624. Camera.prototype.getProjectionMatrix = function (force) {
  19625. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19626. return this._projectionMatrix;
  19627. }
  19628. // Cache
  19629. this._cache.mode = this.mode;
  19630. this._cache.minZ = this.minZ;
  19631. this._cache.maxZ = this.maxZ;
  19632. // Matrix
  19633. this._refreshFrustumPlanes = true;
  19634. var engine = this.getEngine();
  19635. var scene = this.getScene();
  19636. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19637. this._cache.fov = this.fov;
  19638. this._cache.fovMode = this.fovMode;
  19639. this._cache.aspectRatio = engine.getAspectRatio(this);
  19640. if (this.minZ <= 0) {
  19641. this.minZ = 0.1;
  19642. }
  19643. if (scene.useRightHandedSystem) {
  19644. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19645. }
  19646. else {
  19647. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19648. }
  19649. }
  19650. else {
  19651. var halfWidth = engine.getRenderWidth() / 2.0;
  19652. var halfHeight = engine.getRenderHeight() / 2.0;
  19653. if (scene.useRightHandedSystem) {
  19654. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19655. }
  19656. else {
  19657. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19658. }
  19659. this._cache.orthoLeft = this.orthoLeft;
  19660. this._cache.orthoRight = this.orthoRight;
  19661. this._cache.orthoBottom = this.orthoBottom;
  19662. this._cache.orthoTop = this.orthoTop;
  19663. this._cache.renderWidth = engine.getRenderWidth();
  19664. this._cache.renderHeight = engine.getRenderHeight();
  19665. }
  19666. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19667. return this._projectionMatrix;
  19668. };
  19669. Camera.prototype.getTranformationMatrix = function () {
  19670. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19671. return this._transformMatrix;
  19672. };
  19673. Camera.prototype.updateFrustumPlanes = function () {
  19674. if (!this._refreshFrustumPlanes) {
  19675. return;
  19676. }
  19677. this.getTranformationMatrix();
  19678. if (!this._frustumPlanes) {
  19679. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19680. }
  19681. else {
  19682. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19683. }
  19684. this._refreshFrustumPlanes = false;
  19685. };
  19686. Camera.prototype.isInFrustum = function (target) {
  19687. this.updateFrustumPlanes();
  19688. return target.isInFrustum(this._frustumPlanes);
  19689. };
  19690. Camera.prototype.isCompletelyInFrustum = function (target) {
  19691. this.updateFrustumPlanes();
  19692. return target.isCompletelyInFrustum(this._frustumPlanes);
  19693. };
  19694. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19695. if (length === void 0) { length = 100; }
  19696. if (!transform) {
  19697. transform = this.getWorldMatrix();
  19698. }
  19699. if (!origin) {
  19700. origin = this.position;
  19701. }
  19702. var forward = new BABYLON.Vector3(0, 0, 1);
  19703. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19704. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19705. return new BABYLON.Ray(origin, direction, length);
  19706. };
  19707. Camera.prototype.dispose = function () {
  19708. // Observables
  19709. this.onViewMatrixChangedObservable.clear();
  19710. this.onProjectionMatrixChangedObservable.clear();
  19711. this.onAfterCheckInputsObservable.clear();
  19712. this.onRestoreStateObservable.clear();
  19713. // Inputs
  19714. if (this.inputs) {
  19715. this.inputs.clear();
  19716. }
  19717. // Animations
  19718. this.getScene().stopAnimation(this);
  19719. // Remove from scene
  19720. this.getScene().removeCamera(this);
  19721. while (this._rigCameras.length > 0) {
  19722. var camera = this._rigCameras.pop();
  19723. if (camera) {
  19724. camera.dispose();
  19725. }
  19726. }
  19727. // Postprocesses
  19728. if (this._rigPostProcess) {
  19729. this._rigPostProcess.dispose(this);
  19730. this._rigPostProcess = null;
  19731. this._postProcesses = [];
  19732. }
  19733. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19734. this._rigPostProcess = null;
  19735. this._postProcesses = [];
  19736. }
  19737. else {
  19738. var i = this._postProcesses.length;
  19739. while (--i >= 0) {
  19740. this._postProcesses[i].dispose(this);
  19741. }
  19742. }
  19743. // Render targets
  19744. var i = this.customRenderTargets.length;
  19745. while (--i >= 0) {
  19746. this.customRenderTargets[i].dispose();
  19747. }
  19748. this.customRenderTargets = [];
  19749. // Active Meshes
  19750. this._activeMeshes.dispose();
  19751. _super.prototype.dispose.call(this);
  19752. };
  19753. Object.defineProperty(Camera.prototype, "leftCamera", {
  19754. // ---- Camera rigs section ----
  19755. get: function () {
  19756. if (this._rigCameras.length < 1) {
  19757. return null;
  19758. }
  19759. return this._rigCameras[0];
  19760. },
  19761. enumerable: true,
  19762. configurable: true
  19763. });
  19764. Object.defineProperty(Camera.prototype, "rightCamera", {
  19765. get: function () {
  19766. if (this._rigCameras.length < 2) {
  19767. return null;
  19768. }
  19769. return this._rigCameras[1];
  19770. },
  19771. enumerable: true,
  19772. configurable: true
  19773. });
  19774. Camera.prototype.getLeftTarget = function () {
  19775. if (this._rigCameras.length < 1) {
  19776. return null;
  19777. }
  19778. return this._rigCameras[0].getTarget();
  19779. };
  19780. Camera.prototype.getRightTarget = function () {
  19781. if (this._rigCameras.length < 2) {
  19782. return null;
  19783. }
  19784. return this._rigCameras[1].getTarget();
  19785. };
  19786. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19787. if (this.cameraRigMode === mode) {
  19788. return;
  19789. }
  19790. while (this._rigCameras.length > 0) {
  19791. var camera = this._rigCameras.pop();
  19792. if (camera) {
  19793. camera.dispose();
  19794. }
  19795. }
  19796. this.cameraRigMode = mode;
  19797. this._cameraRigParams = {};
  19798. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19799. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19800. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19801. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19802. // create the rig cameras, unless none
  19803. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19804. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19805. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19806. if (leftCamera && rightCamera) {
  19807. this._rigCameras.push(leftCamera);
  19808. this._rigCameras.push(rightCamera);
  19809. }
  19810. }
  19811. switch (this.cameraRigMode) {
  19812. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19813. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19814. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19815. break;
  19816. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19817. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19818. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19819. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19820. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19821. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19822. break;
  19823. case Camera.RIG_MODE_VR:
  19824. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19825. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19826. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19827. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19828. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19829. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19830. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19831. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19832. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19833. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19834. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19835. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19836. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19837. if (metrics.compensateDistortion) {
  19838. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19839. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19840. }
  19841. break;
  19842. case Camera.RIG_MODE_WEBVR:
  19843. if (rigParams.vrDisplay) {
  19844. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19845. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19846. //Left eye
  19847. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19848. this._rigCameras[0].setCameraRigParameter("left", true);
  19849. //leaving this for future reference
  19850. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19851. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19852. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19853. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19854. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19855. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19856. this._rigCameras[0].parent = this;
  19857. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19858. //Right eye
  19859. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19860. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19861. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19862. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19863. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19864. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19865. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19866. this._rigCameras[1].parent = this;
  19867. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19868. if (Camera.UseAlternateWebVRRendering) {
  19869. this._rigCameras[1]._skipRendering = true;
  19870. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19871. }
  19872. }
  19873. break;
  19874. }
  19875. this._cascadePostProcessesToRigCams();
  19876. this.update();
  19877. };
  19878. Camera.prototype._getVRProjectionMatrix = function () {
  19879. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19880. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19881. return this._projectionMatrix;
  19882. };
  19883. Camera.prototype._updateCameraRotationMatrix = function () {
  19884. //Here for WebVR
  19885. };
  19886. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19887. //Here for WebVR
  19888. };
  19889. /**
  19890. * This function MUST be overwritten by the different WebVR cameras available.
  19891. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19892. */
  19893. Camera.prototype._getWebVRProjectionMatrix = function () {
  19894. return BABYLON.Matrix.Identity();
  19895. };
  19896. /**
  19897. * This function MUST be overwritten by the different WebVR cameras available.
  19898. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19899. */
  19900. Camera.prototype._getWebVRViewMatrix = function () {
  19901. return BABYLON.Matrix.Identity();
  19902. };
  19903. Camera.prototype.setCameraRigParameter = function (name, value) {
  19904. if (!this._cameraRigParams) {
  19905. this._cameraRigParams = {};
  19906. }
  19907. this._cameraRigParams[name] = value;
  19908. //provisionnally:
  19909. if (name === "interaxialDistance") {
  19910. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19911. }
  19912. };
  19913. /**
  19914. * needs to be overridden by children so sub has required properties to be copied
  19915. */
  19916. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19917. return null;
  19918. };
  19919. /**
  19920. * May need to be overridden by children
  19921. */
  19922. Camera.prototype._updateRigCameras = function () {
  19923. for (var i = 0; i < this._rigCameras.length; i++) {
  19924. this._rigCameras[i].minZ = this.minZ;
  19925. this._rigCameras[i].maxZ = this.maxZ;
  19926. this._rigCameras[i].fov = this.fov;
  19927. }
  19928. // only update viewport when ANAGLYPH
  19929. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19930. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19931. }
  19932. };
  19933. Camera.prototype._setupInputs = function () {
  19934. };
  19935. Camera.prototype.serialize = function () {
  19936. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19937. // Type
  19938. serializationObject.type = this.getClassName();
  19939. // Parent
  19940. if (this.parent) {
  19941. serializationObject.parentId = this.parent.id;
  19942. }
  19943. if (this.inputs) {
  19944. this.inputs.serialize(serializationObject);
  19945. }
  19946. // Animations
  19947. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19948. serializationObject.ranges = this.serializeAnimationRanges();
  19949. return serializationObject;
  19950. };
  19951. Camera.prototype.clone = function (name) {
  19952. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19953. };
  19954. Camera.prototype.getDirection = function (localAxis) {
  19955. var result = BABYLON.Vector3.Zero();
  19956. this.getDirectionToRef(localAxis, result);
  19957. return result;
  19958. };
  19959. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19960. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19961. };
  19962. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19963. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19964. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19965. switch (type) {
  19966. case "ArcRotateCamera":
  19967. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19968. case "DeviceOrientationCamera":
  19969. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19970. case "FollowCamera":
  19971. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19972. case "ArcFollowCamera":
  19973. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19974. case "GamepadCamera":
  19975. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19976. case "TouchCamera":
  19977. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19978. case "VirtualJoysticksCamera":
  19979. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19980. case "WebVRFreeCamera":
  19981. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19982. case "WebVRGamepadCamera":
  19983. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19984. case "VRDeviceOrientationFreeCamera":
  19985. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19986. case "VRDeviceOrientationGamepadCamera":
  19987. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19988. case "AnaglyphArcRotateCamera":
  19989. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19990. case "AnaglyphFreeCamera":
  19991. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19992. case "AnaglyphGamepadCamera":
  19993. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19994. case "AnaglyphUniversalCamera":
  19995. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19996. case "StereoscopicArcRotateCamera":
  19997. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19998. case "StereoscopicFreeCamera":
  19999. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20000. case "StereoscopicGamepadCamera":
  20001. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20002. case "StereoscopicUniversalCamera":
  20003. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20004. case "FreeCamera":// Forcing Universal here
  20005. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20006. default:// Universal Camera is the default value
  20007. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20008. }
  20009. };
  20010. Camera.prototype.computeWorldMatrix = function () {
  20011. return this.getWorldMatrix();
  20012. };
  20013. Camera.Parse = function (parsedCamera, scene) {
  20014. var type = parsedCamera.type;
  20015. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20016. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20017. // Parent
  20018. if (parsedCamera.parentId) {
  20019. camera._waitingParentId = parsedCamera.parentId;
  20020. }
  20021. //If camera has an input manager, let it parse inputs settings
  20022. if (camera.inputs) {
  20023. camera.inputs.parse(parsedCamera);
  20024. camera._setupInputs();
  20025. }
  20026. if (camera.setPosition) {
  20027. camera.position.copyFromFloats(0, 0, 0);
  20028. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20029. }
  20030. // Target
  20031. if (parsedCamera.target) {
  20032. if (camera.setTarget) {
  20033. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20034. }
  20035. }
  20036. // Apply 3d rig, when found
  20037. if (parsedCamera.cameraRigMode) {
  20038. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20039. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20040. }
  20041. // Animations
  20042. if (parsedCamera.animations) {
  20043. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20044. var parsedAnimation = parsedCamera.animations[animationIndex];
  20045. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20046. }
  20047. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20048. }
  20049. if (parsedCamera.autoAnimate) {
  20050. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20051. }
  20052. return camera;
  20053. };
  20054. // Statics
  20055. Camera._PERSPECTIVE_CAMERA = 0;
  20056. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20057. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20058. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20059. Camera._RIG_MODE_NONE = 0;
  20060. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20061. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20062. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20063. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20064. Camera._RIG_MODE_VR = 20;
  20065. Camera._RIG_MODE_WEBVR = 21;
  20066. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20067. Camera.UseAlternateWebVRRendering = false;
  20068. __decorate([
  20069. BABYLON.serializeAsVector3()
  20070. ], Camera.prototype, "position", void 0);
  20071. __decorate([
  20072. BABYLON.serializeAsVector3()
  20073. ], Camera.prototype, "upVector", void 0);
  20074. __decorate([
  20075. BABYLON.serialize()
  20076. ], Camera.prototype, "orthoLeft", void 0);
  20077. __decorate([
  20078. BABYLON.serialize()
  20079. ], Camera.prototype, "orthoRight", void 0);
  20080. __decorate([
  20081. BABYLON.serialize()
  20082. ], Camera.prototype, "orthoBottom", void 0);
  20083. __decorate([
  20084. BABYLON.serialize()
  20085. ], Camera.prototype, "orthoTop", void 0);
  20086. __decorate([
  20087. BABYLON.serialize()
  20088. ], Camera.prototype, "fov", void 0);
  20089. __decorate([
  20090. BABYLON.serialize()
  20091. ], Camera.prototype, "minZ", void 0);
  20092. __decorate([
  20093. BABYLON.serialize()
  20094. ], Camera.prototype, "maxZ", void 0);
  20095. __decorate([
  20096. BABYLON.serialize()
  20097. ], Camera.prototype, "inertia", void 0);
  20098. __decorate([
  20099. BABYLON.serialize()
  20100. ], Camera.prototype, "mode", void 0);
  20101. __decorate([
  20102. BABYLON.serialize()
  20103. ], Camera.prototype, "layerMask", void 0);
  20104. __decorate([
  20105. BABYLON.serialize()
  20106. ], Camera.prototype, "fovMode", void 0);
  20107. __decorate([
  20108. BABYLON.serialize()
  20109. ], Camera.prototype, "cameraRigMode", void 0);
  20110. __decorate([
  20111. BABYLON.serialize()
  20112. ], Camera.prototype, "interaxialDistance", void 0);
  20113. __decorate([
  20114. BABYLON.serialize()
  20115. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20116. return Camera;
  20117. }(BABYLON.Node));
  20118. BABYLON.Camera = Camera;
  20119. })(BABYLON || (BABYLON = {}));
  20120. //# sourceMappingURL=babylon.camera.js.map
  20121. var BABYLON;
  20122. (function (BABYLON) {
  20123. var RenderingManager = /** @class */ (function () {
  20124. function RenderingManager(scene) {
  20125. this._renderingGroups = new Array();
  20126. this._autoClearDepthStencil = {};
  20127. this._customOpaqueSortCompareFn = {};
  20128. this._customAlphaTestSortCompareFn = {};
  20129. this._customTransparentSortCompareFn = {};
  20130. this._renderinGroupInfo = null;
  20131. this._scene = scene;
  20132. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20133. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20134. }
  20135. }
  20136. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20137. if (depth === void 0) { depth = true; }
  20138. if (stencil === void 0) { stencil = true; }
  20139. if (this._depthStencilBufferAlreadyCleaned) {
  20140. return;
  20141. }
  20142. this._scene.getEngine().clear(null, false, depth, stencil);
  20143. this._depthStencilBufferAlreadyCleaned = true;
  20144. };
  20145. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20146. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20147. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20148. var info = null;
  20149. if (observable) {
  20150. if (!this._renderinGroupInfo) {
  20151. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20152. }
  20153. info = this._renderinGroupInfo;
  20154. info.scene = this._scene;
  20155. info.camera = this._scene.activeCamera;
  20156. }
  20157. // Dispatch sprites
  20158. if (renderSprites) {
  20159. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20160. var manager = this._scene.spriteManagers[index];
  20161. this.dispatchSprites(manager);
  20162. }
  20163. }
  20164. // Render
  20165. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20166. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20167. var renderingGroup = this._renderingGroups[index];
  20168. if (!renderingGroup && !observable)
  20169. continue;
  20170. var renderingGroupMask = 0;
  20171. // Fire PRECLEAR stage
  20172. if (observable && info) {
  20173. renderingGroupMask = Math.pow(2, index);
  20174. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20175. info.renderingGroupId = index;
  20176. observable.notifyObservers(info, renderingGroupMask);
  20177. }
  20178. // Clear depth/stencil if needed
  20179. if (RenderingManager.AUTOCLEAR) {
  20180. var autoClear = this._autoClearDepthStencil[index];
  20181. if (autoClear && autoClear.autoClear) {
  20182. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20183. }
  20184. }
  20185. if (observable && info) {
  20186. // Fire PREOPAQUE stage
  20187. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20188. observable.notifyObservers(info, renderingGroupMask);
  20189. // Fire PRETRANSPARENT stage
  20190. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20191. observable.notifyObservers(info, renderingGroupMask);
  20192. }
  20193. if (renderingGroup)
  20194. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20195. // Fire POSTTRANSPARENT stage
  20196. if (observable && info) {
  20197. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20198. observable.notifyObservers(info, renderingGroupMask);
  20199. }
  20200. }
  20201. };
  20202. RenderingManager.prototype.reset = function () {
  20203. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20204. var renderingGroup = this._renderingGroups[index];
  20205. if (renderingGroup) {
  20206. renderingGroup.prepare();
  20207. }
  20208. }
  20209. };
  20210. RenderingManager.prototype.dispose = function () {
  20211. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20212. var renderingGroup = this._renderingGroups[index];
  20213. if (renderingGroup) {
  20214. renderingGroup.dispose();
  20215. }
  20216. }
  20217. this._renderingGroups.length = 0;
  20218. };
  20219. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20220. if (this._renderingGroups[renderingGroupId] === undefined) {
  20221. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20222. }
  20223. };
  20224. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20225. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20226. this._prepareRenderingGroup(renderingGroupId);
  20227. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20228. };
  20229. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20230. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20231. this._prepareRenderingGroup(renderingGroupId);
  20232. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20233. };
  20234. /**
  20235. * @param subMesh The submesh to dispatch
  20236. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20237. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20238. */
  20239. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20240. if (mesh === undefined) {
  20241. mesh = subMesh.getMesh();
  20242. }
  20243. var renderingGroupId = mesh.renderingGroupId || 0;
  20244. this._prepareRenderingGroup(renderingGroupId);
  20245. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20246. };
  20247. /**
  20248. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20249. * This allowed control for front to back rendering or reversly depending of the special needs.
  20250. *
  20251. * @param renderingGroupId The rendering group id corresponding to its index
  20252. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20253. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20254. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20255. */
  20256. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20257. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20258. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20259. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20260. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20261. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20262. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20263. if (this._renderingGroups[renderingGroupId]) {
  20264. var group = this._renderingGroups[renderingGroupId];
  20265. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20266. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20267. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20268. }
  20269. };
  20270. /**
  20271. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20272. *
  20273. * @param renderingGroupId The rendering group id corresponding to its index
  20274. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20275. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20276. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20277. */
  20278. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20279. if (depth === void 0) { depth = true; }
  20280. if (stencil === void 0) { stencil = true; }
  20281. this._autoClearDepthStencil[renderingGroupId] = {
  20282. autoClear: autoClearDepthStencil,
  20283. depth: depth,
  20284. stencil: stencil
  20285. };
  20286. };
  20287. /**
  20288. * The max id used for rendering groups (not included)
  20289. */
  20290. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20291. /**
  20292. * The min id used for rendering groups (included)
  20293. */
  20294. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20295. /**
  20296. * Used to globally prevent autoclearing scenes.
  20297. */
  20298. RenderingManager.AUTOCLEAR = true;
  20299. return RenderingManager;
  20300. }());
  20301. BABYLON.RenderingManager = RenderingManager;
  20302. })(BABYLON || (BABYLON = {}));
  20303. //# sourceMappingURL=babylon.renderingManager.js.map
  20304. var BABYLON;
  20305. (function (BABYLON) {
  20306. var RenderingGroup = /** @class */ (function () {
  20307. /**
  20308. * Creates a new rendering group.
  20309. * @param index The rendering group index
  20310. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20311. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20312. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20313. */
  20314. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20315. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20316. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20317. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20318. this.index = index;
  20319. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20320. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20321. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20322. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20323. this._particleSystems = new BABYLON.SmartArray(256);
  20324. this._spriteManagers = new BABYLON.SmartArray(256);
  20325. this._edgesRenderers = new BABYLON.SmartArray(16);
  20326. this._scene = scene;
  20327. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20328. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20329. this.transparentSortCompareFn = transparentSortCompareFn;
  20330. }
  20331. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20332. /**
  20333. * Set the opaque sort comparison function.
  20334. * If null the sub meshes will be render in the order they were created
  20335. */
  20336. set: function (value) {
  20337. this._opaqueSortCompareFn = value;
  20338. if (value) {
  20339. this._renderOpaque = this.renderOpaqueSorted;
  20340. }
  20341. else {
  20342. this._renderOpaque = RenderingGroup.renderUnsorted;
  20343. }
  20344. },
  20345. enumerable: true,
  20346. configurable: true
  20347. });
  20348. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20349. /**
  20350. * Set the alpha test sort comparison function.
  20351. * If null the sub meshes will be render in the order they were created
  20352. */
  20353. set: function (value) {
  20354. this._alphaTestSortCompareFn = value;
  20355. if (value) {
  20356. this._renderAlphaTest = this.renderAlphaTestSorted;
  20357. }
  20358. else {
  20359. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20360. }
  20361. },
  20362. enumerable: true,
  20363. configurable: true
  20364. });
  20365. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20366. /**
  20367. * Set the transparent sort comparison function.
  20368. * If null the sub meshes will be render in the order they were created
  20369. */
  20370. set: function (value) {
  20371. if (value) {
  20372. this._transparentSortCompareFn = value;
  20373. }
  20374. else {
  20375. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20376. }
  20377. this._renderTransparent = this.renderTransparentSorted;
  20378. },
  20379. enumerable: true,
  20380. configurable: true
  20381. });
  20382. /**
  20383. * Render all the sub meshes contained in the group.
  20384. * @param customRenderFunction Used to override the default render behaviour of the group.
  20385. * @returns true if rendered some submeshes.
  20386. */
  20387. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20388. if (customRenderFunction) {
  20389. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20390. return;
  20391. }
  20392. var engine = this._scene.getEngine();
  20393. // Depth only
  20394. if (this._depthOnlySubMeshes.length !== 0) {
  20395. engine.setColorWrite(false);
  20396. this._renderAlphaTest(this._depthOnlySubMeshes);
  20397. engine.setColorWrite(true);
  20398. }
  20399. // Opaque
  20400. if (this._opaqueSubMeshes.length !== 0) {
  20401. this._renderOpaque(this._opaqueSubMeshes);
  20402. }
  20403. // Alpha test
  20404. if (this._alphaTestSubMeshes.length !== 0) {
  20405. this._renderAlphaTest(this._alphaTestSubMeshes);
  20406. }
  20407. var stencilState = engine.getStencilBuffer();
  20408. engine.setStencilBuffer(false);
  20409. // Sprites
  20410. if (renderSprites) {
  20411. this._renderSprites();
  20412. }
  20413. // Particles
  20414. if (renderParticles) {
  20415. this._renderParticles(activeMeshes);
  20416. }
  20417. if (this.onBeforeTransparentRendering) {
  20418. this.onBeforeTransparentRendering();
  20419. }
  20420. // Transparent
  20421. if (this._transparentSubMeshes.length !== 0) {
  20422. this._renderTransparent(this._transparentSubMeshes);
  20423. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20424. }
  20425. // Set back stencil to false in case it changes before the edge renderer.
  20426. engine.setStencilBuffer(false);
  20427. // Edges
  20428. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20429. this._edgesRenderers.data[edgesRendererIndex].render();
  20430. }
  20431. // Restore Stencil state.
  20432. engine.setStencilBuffer(stencilState);
  20433. };
  20434. /**
  20435. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20436. * @param subMeshes The submeshes to render
  20437. */
  20438. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20439. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20440. };
  20441. /**
  20442. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20443. * @param subMeshes The submeshes to render
  20444. */
  20445. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20446. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20447. };
  20448. /**
  20449. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20450. * @param subMeshes The submeshes to render
  20451. */
  20452. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20453. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20454. };
  20455. /**
  20456. * Renders the submeshes in a specified order.
  20457. * @param subMeshes The submeshes to sort before render
  20458. * @param sortCompareFn The comparison function use to sort
  20459. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20460. * @param transparent Specifies to activate blending if true
  20461. */
  20462. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20463. var subIndex = 0;
  20464. var subMesh;
  20465. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20466. for (; subIndex < subMeshes.length; subIndex++) {
  20467. subMesh = subMeshes.data[subIndex];
  20468. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20469. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20470. }
  20471. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20472. if (sortCompareFn) {
  20473. sortedArray.sort(sortCompareFn);
  20474. }
  20475. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20476. subMesh = sortedArray[subIndex];
  20477. if (transparent) {
  20478. var material = subMesh.getMaterial();
  20479. if (material && material.needDepthPrePass) {
  20480. var engine = material.getScene().getEngine();
  20481. engine.setColorWrite(false);
  20482. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20483. subMesh.render(false);
  20484. engine.setColorWrite(true);
  20485. }
  20486. }
  20487. subMesh.render(transparent);
  20488. }
  20489. };
  20490. /**
  20491. * Renders the submeshes in the order they were dispatched (no sort applied).
  20492. * @param subMeshes The submeshes to render
  20493. */
  20494. RenderingGroup.renderUnsorted = function (subMeshes) {
  20495. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20496. var submesh = subMeshes.data[subIndex];
  20497. submesh.render(false);
  20498. }
  20499. };
  20500. /**
  20501. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20502. * are rendered back to front if in the same alpha index.
  20503. *
  20504. * @param a The first submesh
  20505. * @param b The second submesh
  20506. * @returns The result of the comparison
  20507. */
  20508. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20509. // Alpha index first
  20510. if (a._alphaIndex > b._alphaIndex) {
  20511. return 1;
  20512. }
  20513. if (a._alphaIndex < b._alphaIndex) {
  20514. return -1;
  20515. }
  20516. // Then distance to camera
  20517. return RenderingGroup.backToFrontSortCompare(a, b);
  20518. };
  20519. /**
  20520. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20521. * are rendered back to front.
  20522. *
  20523. * @param a The first submesh
  20524. * @param b The second submesh
  20525. * @returns The result of the comparison
  20526. */
  20527. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20528. // Then distance to camera
  20529. if (a._distanceToCamera < b._distanceToCamera) {
  20530. return 1;
  20531. }
  20532. if (a._distanceToCamera > b._distanceToCamera) {
  20533. return -1;
  20534. }
  20535. return 0;
  20536. };
  20537. /**
  20538. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20539. * are rendered front to back (prevent overdraw).
  20540. *
  20541. * @param a The first submesh
  20542. * @param b The second submesh
  20543. * @returns The result of the comparison
  20544. */
  20545. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20546. // Then distance to camera
  20547. if (a._distanceToCamera < b._distanceToCamera) {
  20548. return -1;
  20549. }
  20550. if (a._distanceToCamera > b._distanceToCamera) {
  20551. return 1;
  20552. }
  20553. return 0;
  20554. };
  20555. /**
  20556. * Resets the different lists of submeshes to prepare a new frame.
  20557. */
  20558. RenderingGroup.prototype.prepare = function () {
  20559. this._opaqueSubMeshes.reset();
  20560. this._transparentSubMeshes.reset();
  20561. this._alphaTestSubMeshes.reset();
  20562. this._depthOnlySubMeshes.reset();
  20563. this._particleSystems.reset();
  20564. this._spriteManagers.reset();
  20565. this._edgesRenderers.reset();
  20566. };
  20567. RenderingGroup.prototype.dispose = function () {
  20568. this._opaqueSubMeshes.dispose();
  20569. this._transparentSubMeshes.dispose();
  20570. this._alphaTestSubMeshes.dispose();
  20571. this._depthOnlySubMeshes.dispose();
  20572. this._particleSystems.dispose();
  20573. this._spriteManagers.dispose();
  20574. this._edgesRenderers.dispose();
  20575. };
  20576. /**
  20577. * Inserts the submesh in its correct queue depending on its material.
  20578. * @param subMesh The submesh to dispatch
  20579. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20580. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20581. */
  20582. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20583. // Get mesh and materials if not provided
  20584. if (mesh === undefined) {
  20585. mesh = subMesh.getMesh();
  20586. }
  20587. if (material === undefined) {
  20588. material = subMesh.getMaterial();
  20589. }
  20590. if (material === null || material === undefined) {
  20591. return;
  20592. }
  20593. if (material.needAlphaBlendingForMesh(mesh)) {
  20594. this._transparentSubMeshes.push(subMesh);
  20595. }
  20596. else if (material.needAlphaTesting()) {
  20597. if (material.needDepthPrePass) {
  20598. this._depthOnlySubMeshes.push(subMesh);
  20599. }
  20600. this._alphaTestSubMeshes.push(subMesh);
  20601. }
  20602. else {
  20603. if (material.needDepthPrePass) {
  20604. this._depthOnlySubMeshes.push(subMesh);
  20605. }
  20606. this._opaqueSubMeshes.push(subMesh); // Opaque
  20607. }
  20608. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20609. this._edgesRenderers.push(mesh._edgesRenderer);
  20610. }
  20611. };
  20612. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20613. this._spriteManagers.push(spriteManager);
  20614. };
  20615. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20616. this._particleSystems.push(particleSystem);
  20617. };
  20618. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20619. if (this._particleSystems.length === 0) {
  20620. return;
  20621. }
  20622. // Particles
  20623. var activeCamera = this._scene.activeCamera;
  20624. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20625. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20626. var particleSystem = this._particleSystems.data[particleIndex];
  20627. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20628. continue;
  20629. }
  20630. var emitter = particleSystem.emitter;
  20631. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20632. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20633. }
  20634. }
  20635. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20636. };
  20637. RenderingGroup.prototype._renderSprites = function () {
  20638. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20639. return;
  20640. }
  20641. // Sprites
  20642. var activeCamera = this._scene.activeCamera;
  20643. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20644. for (var id = 0; id < this._spriteManagers.length; id++) {
  20645. var spriteManager = this._spriteManagers.data[id];
  20646. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20647. spriteManager.render();
  20648. }
  20649. }
  20650. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20651. };
  20652. return RenderingGroup;
  20653. }());
  20654. BABYLON.RenderingGroup = RenderingGroup;
  20655. })(BABYLON || (BABYLON = {}));
  20656. //# sourceMappingURL=babylon.renderingGroup.js.map
  20657. var BABYLON;
  20658. (function (BABYLON) {
  20659. var ClickInfo = /** @class */ (function () {
  20660. function ClickInfo() {
  20661. this._singleClick = false;
  20662. this._doubleClick = false;
  20663. this._hasSwiped = false;
  20664. this._ignore = false;
  20665. }
  20666. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20667. get: function () {
  20668. return this._singleClick;
  20669. },
  20670. set: function (b) {
  20671. this._singleClick = b;
  20672. },
  20673. enumerable: true,
  20674. configurable: true
  20675. });
  20676. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20677. get: function () {
  20678. return this._doubleClick;
  20679. },
  20680. set: function (b) {
  20681. this._doubleClick = b;
  20682. },
  20683. enumerable: true,
  20684. configurable: true
  20685. });
  20686. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20687. get: function () {
  20688. return this._hasSwiped;
  20689. },
  20690. set: function (b) {
  20691. this._hasSwiped = b;
  20692. },
  20693. enumerable: true,
  20694. configurable: true
  20695. });
  20696. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20697. get: function () {
  20698. return this._ignore;
  20699. },
  20700. set: function (b) {
  20701. this._ignore = b;
  20702. },
  20703. enumerable: true,
  20704. configurable: true
  20705. });
  20706. return ClickInfo;
  20707. }());
  20708. /**
  20709. * This class is used by the onRenderingGroupObservable
  20710. */
  20711. var RenderingGroupInfo = /** @class */ (function () {
  20712. function RenderingGroupInfo() {
  20713. }
  20714. /**
  20715. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20716. * This stage will be fired no matter what
  20717. */
  20718. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20719. /**
  20720. * Called before opaque object are rendered.
  20721. * This stage will be fired only if there's 3D Opaque content to render
  20722. */
  20723. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20724. /**
  20725. * Called after the opaque objects are rendered and before the transparent ones
  20726. * This stage will be fired only if there's 3D transparent content to render
  20727. */
  20728. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20729. /**
  20730. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20731. * This stage will be fired no matter what
  20732. */
  20733. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20734. return RenderingGroupInfo;
  20735. }());
  20736. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20737. /**
  20738. * Represents a scene to be rendered by the engine.
  20739. * @see http://doc.babylonjs.com/page.php?p=21911
  20740. */
  20741. var Scene = /** @class */ (function () {
  20742. /**
  20743. * @constructor
  20744. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20745. */
  20746. function Scene(engine) {
  20747. // Members
  20748. this.autoClear = true;
  20749. this.autoClearDepthAndStencil = true;
  20750. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20751. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20752. this.forceWireframe = false;
  20753. this._forcePointsCloud = false;
  20754. this.forceShowBoundingBoxes = false;
  20755. this.animationsEnabled = true;
  20756. this.useConstantAnimationDeltaTime = false;
  20757. this.constantlyUpdateMeshUnderPointer = false;
  20758. this.hoverCursor = "pointer";
  20759. this.defaultCursor = "";
  20760. /**
  20761. * This is used to call preventDefault() on pointer down
  20762. * in order to block unwanted artifacts like system double clicks
  20763. */
  20764. this.preventDefaultOnPointerDown = true;
  20765. // Metadata
  20766. this.metadata = null;
  20767. /**
  20768. * An event triggered when the scene is disposed.
  20769. * @type {BABYLON.Observable}
  20770. */
  20771. this.onDisposeObservable = new BABYLON.Observable();
  20772. /**
  20773. * An event triggered before rendering the scene (right after animations and physics)
  20774. * @type {BABYLON.Observable}
  20775. */
  20776. this.onBeforeRenderObservable = new BABYLON.Observable();
  20777. /**
  20778. * An event triggered after rendering the scene
  20779. * @type {BABYLON.Observable}
  20780. */
  20781. this.onAfterRenderObservable = new BABYLON.Observable();
  20782. /**
  20783. * An event triggered before animating the scene
  20784. * @type {BABYLON.Observable}
  20785. */
  20786. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20787. /**
  20788. * An event triggered after animations processing
  20789. * @type {BABYLON.Observable}
  20790. */
  20791. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20792. /**
  20793. * An event triggered before draw calls are ready to be sent
  20794. * @type {BABYLON.Observable}
  20795. */
  20796. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20797. /**
  20798. * An event triggered after draw calls have been sent
  20799. * @type {BABYLON.Observable}
  20800. */
  20801. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20802. /**
  20803. * An event triggered when physic simulation is about to be run
  20804. * @type {BABYLON.Observable}
  20805. */
  20806. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20807. /**
  20808. * An event triggered when physic simulation has been done
  20809. * @type {BABYLON.Observable}
  20810. */
  20811. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20812. /**
  20813. * An event triggered when the scene is ready
  20814. * @type {BABYLON.Observable}
  20815. */
  20816. this.onReadyObservable = new BABYLON.Observable();
  20817. /**
  20818. * An event triggered before rendering a camera
  20819. * @type {BABYLON.Observable}
  20820. */
  20821. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20822. /**
  20823. * An event triggered after rendering a camera
  20824. * @type {BABYLON.Observable}
  20825. */
  20826. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20827. /**
  20828. * An event triggered when active meshes evaluation is about to start
  20829. * @type {BABYLON.Observable}
  20830. */
  20831. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20832. /**
  20833. * An event triggered when active meshes evaluation is done
  20834. * @type {BABYLON.Observable}
  20835. */
  20836. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20837. /**
  20838. * An event triggered when particles rendering is about to start
  20839. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20840. * @type {BABYLON.Observable}
  20841. */
  20842. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20843. /**
  20844. * An event triggered when particles rendering is done
  20845. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20846. * @type {BABYLON.Observable}
  20847. */
  20848. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20849. /**
  20850. * An event triggered when sprites rendering is about to start
  20851. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20852. * @type {BABYLON.Observable}
  20853. */
  20854. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20855. /**
  20856. * An event triggered when sprites rendering is done
  20857. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20858. * @type {BABYLON.Observable}
  20859. */
  20860. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20861. /**
  20862. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20863. * @type {BABYLON.Observable}
  20864. */
  20865. this.onDataLoadedObservable = new BABYLON.Observable();
  20866. /**
  20867. * An event triggered when a camera is created
  20868. * @type {BABYLON.Observable}
  20869. */
  20870. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20871. /**
  20872. * An event triggered when a camera is removed
  20873. * @type {BABYLON.Observable}
  20874. */
  20875. this.onCameraRemovedObservable = new BABYLON.Observable();
  20876. /**
  20877. * An event triggered when a light is created
  20878. * @type {BABYLON.Observable}
  20879. */
  20880. this.onNewLightAddedObservable = new BABYLON.Observable();
  20881. /**
  20882. * An event triggered when a light is removed
  20883. * @type {BABYLON.Observable}
  20884. */
  20885. this.onLightRemovedObservable = new BABYLON.Observable();
  20886. /**
  20887. * An event triggered when a geometry is created
  20888. * @type {BABYLON.Observable}
  20889. */
  20890. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20891. /**
  20892. * An event triggered when a geometry is removed
  20893. * @type {BABYLON.Observable}
  20894. */
  20895. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20896. /**
  20897. * An event triggered when a transform node is created
  20898. * @type {BABYLON.Observable}
  20899. */
  20900. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20901. /**
  20902. * An event triggered when a transform node is removed
  20903. * @type {BABYLON.Observable}
  20904. */
  20905. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20906. /**
  20907. * An event triggered when a mesh is created
  20908. * @type {BABYLON.Observable}
  20909. */
  20910. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20911. /**
  20912. * An event triggered when a mesh is removed
  20913. * @type {BABYLON.Observable}
  20914. */
  20915. this.onMeshRemovedObservable = new BABYLON.Observable();
  20916. /**
  20917. * An event triggered when render targets are about to be rendered
  20918. * Can happen multiple times per frame.
  20919. * @type {BABYLON.Observable}
  20920. */
  20921. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20922. /**
  20923. * An event triggered when render targets were rendered.
  20924. * Can happen multiple times per frame.
  20925. * @type {BABYLON.Observable}
  20926. */
  20927. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20928. /**
  20929. * An event triggered before calculating deterministic simulation step
  20930. * @type {BABYLON.Observable}
  20931. */
  20932. this.onBeforeStepObservable = new BABYLON.Observable();
  20933. /**
  20934. * An event triggered after calculating deterministic simulation step
  20935. * @type {BABYLON.Observable}
  20936. */
  20937. this.onAfterStepObservable = new BABYLON.Observable();
  20938. /**
  20939. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20940. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20941. * 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)
  20942. */
  20943. this.onRenderingGroupObservable = new BABYLON.Observable();
  20944. // Animations
  20945. this.animations = [];
  20946. /**
  20947. * 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).
  20948. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20949. */
  20950. this.onPrePointerObservable = new BABYLON.Observable();
  20951. /**
  20952. * Observable event triggered each time an input event is received from the rendering canvas
  20953. */
  20954. this.onPointerObservable = new BABYLON.Observable();
  20955. this._meshPickProceed = false;
  20956. this._currentPickResult = null;
  20957. this._previousPickResult = null;
  20958. this._totalPointersPressed = 0;
  20959. this._doubleClickOccured = false;
  20960. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20961. this.cameraToUseForPointers = null;
  20962. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20963. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20964. this._startingPointerTime = 0;
  20965. this._previousStartingPointerTime = 0;
  20966. // Deterministic lockstep
  20967. this._timeAccumulator = 0;
  20968. this._currentStepId = 0;
  20969. this._currentInternalStep = 0;
  20970. // Keyboard
  20971. /**
  20972. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20973. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20974. */
  20975. this.onPreKeyboardObservable = new BABYLON.Observable();
  20976. /**
  20977. * Observable event triggered each time an keyboard event is received from the hosting window
  20978. */
  20979. this.onKeyboardObservable = new BABYLON.Observable();
  20980. // Coordinate system
  20981. /**
  20982. * use right-handed coordinate system on this scene.
  20983. * @type {boolean}
  20984. */
  20985. this._useRightHandedSystem = false;
  20986. // Fog
  20987. this._fogEnabled = true;
  20988. this._fogMode = Scene.FOGMODE_NONE;
  20989. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20990. this.fogDensity = 0.1;
  20991. this.fogStart = 0;
  20992. this.fogEnd = 1000.0;
  20993. // Lights
  20994. /**
  20995. * is shadow enabled on this scene.
  20996. * @type {boolean}
  20997. */
  20998. this._shadowsEnabled = true;
  20999. /**
  21000. * is light enabled on this scene.
  21001. * @type {boolean}
  21002. */
  21003. this._lightsEnabled = true;
  21004. /**
  21005. * All of the lights added to this scene.
  21006. * @see BABYLON.Light
  21007. * @type {BABYLON.Light[]}
  21008. */
  21009. this.lights = new Array();
  21010. // Cameras
  21011. /** All of the cameras added to this scene. */
  21012. this.cameras = new Array();
  21013. /** All of the active cameras added to this scene. */
  21014. this.activeCameras = new Array();
  21015. // Meshes
  21016. /**
  21017. * All of the tranform nodes added to this scene.
  21018. * @see BABYLON.TransformNode
  21019. * @type {BABYLON.TransformNode[]}
  21020. */
  21021. this.transformNodes = new Array();
  21022. /**
  21023. * All of the (abstract) meshes added to this scene.
  21024. * @see BABYLON.AbstractMesh
  21025. * @type {BABYLON.AbstractMesh[]}
  21026. */
  21027. this.meshes = new Array();
  21028. /**
  21029. * All of the animation groups added to this scene.
  21030. * @see BABYLON.AnimationGroup
  21031. * @type {BABYLON.AnimationGroup[]}
  21032. */
  21033. this.animationGroups = new Array();
  21034. // Geometries
  21035. this._geometries = new Array();
  21036. this.materials = new Array();
  21037. this.multiMaterials = new Array();
  21038. // Textures
  21039. this._texturesEnabled = true;
  21040. this.textures = new Array();
  21041. // Particles
  21042. this.particlesEnabled = true;
  21043. this.particleSystems = new Array();
  21044. // Sprites
  21045. this.spritesEnabled = true;
  21046. this.spriteManagers = new Array();
  21047. /**
  21048. * The list of layers (background and foreground) of the scene.
  21049. */
  21050. this.layers = new Array();
  21051. /**
  21052. * The list of effect layers (highlights/glow) contained in the scene.
  21053. */
  21054. this.effectLayers = new Array();
  21055. // Skeletons
  21056. this._skeletonsEnabled = true;
  21057. this.skeletons = new Array();
  21058. // Morph targets
  21059. this.morphTargetManagers = new Array();
  21060. // Lens flares
  21061. this.lensFlaresEnabled = true;
  21062. this.lensFlareSystems = new Array();
  21063. // Collisions
  21064. this.collisionsEnabled = true;
  21065. /** Defines the gravity applied to this scene */
  21066. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21067. // Postprocesses
  21068. this.postProcesses = new Array();
  21069. this.postProcessesEnabled = true;
  21070. // Customs render targets
  21071. this.renderTargetsEnabled = true;
  21072. this.dumpNextRenderTargets = false;
  21073. this.customRenderTargets = new Array();
  21074. // Imported meshes
  21075. this.importedMeshesFiles = new Array();
  21076. // Probes
  21077. this.probesEnabled = true;
  21078. this.reflectionProbes = new Array();
  21079. this._actionManagers = new Array();
  21080. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21081. // Procedural textures
  21082. this.proceduralTexturesEnabled = true;
  21083. this._proceduralTextures = new Array();
  21084. this.soundTracks = new Array();
  21085. this._audioEnabled = true;
  21086. this._headphone = false;
  21087. // Performance counters
  21088. this._totalVertices = new BABYLON.PerfCounter();
  21089. this._activeIndices = new BABYLON.PerfCounter();
  21090. this._activeParticles = new BABYLON.PerfCounter();
  21091. this._activeBones = new BABYLON.PerfCounter();
  21092. this._animationTime = 0;
  21093. this.animationTimeScale = 1;
  21094. this._renderId = 0;
  21095. this._executeWhenReadyTimeoutId = -1;
  21096. this._intermediateRendering = false;
  21097. this._viewUpdateFlag = -1;
  21098. this._projectionUpdateFlag = -1;
  21099. this._alternateViewUpdateFlag = -1;
  21100. this._alternateProjectionUpdateFlag = -1;
  21101. this._toBeDisposed = new BABYLON.SmartArray(256);
  21102. this._activeRequests = new Array();
  21103. this._pendingData = new Array();
  21104. this._isDisposed = false;
  21105. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21106. this._activeMeshes = new BABYLON.SmartArray(256);
  21107. this._processedMaterials = new BABYLON.SmartArray(256);
  21108. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21109. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21110. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21111. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21112. this._activeAnimatables = new Array();
  21113. this._transformMatrix = BABYLON.Matrix.Zero();
  21114. this._useAlternateCameraConfiguration = false;
  21115. this._alternateRendering = false;
  21116. this.requireLightSorting = false;
  21117. this._activeMeshesFrozen = false;
  21118. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21119. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21120. this._engine.scenes.push(this);
  21121. this._uid = null;
  21122. this._renderingManager = new BABYLON.RenderingManager(this);
  21123. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21124. if (BABYLON.OutlineRenderer) {
  21125. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21126. }
  21127. if (BABYLON.Tools.IsWindowObjectExist()) {
  21128. this.attachControl();
  21129. }
  21130. //simplification queue
  21131. if (BABYLON.SimplificationQueue) {
  21132. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21133. }
  21134. //collision coordinator initialization. For now legacy per default.
  21135. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21136. // Uniform Buffer
  21137. this._createUbo();
  21138. // Default Image processing definition.
  21139. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21140. }
  21141. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21142. /** The fog is deactivated */
  21143. get: function () {
  21144. return Scene._FOGMODE_NONE;
  21145. },
  21146. enumerable: true,
  21147. configurable: true
  21148. });
  21149. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21150. /** The fog density is following an exponential function */
  21151. get: function () {
  21152. return Scene._FOGMODE_EXP;
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21158. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21159. get: function () {
  21160. return Scene._FOGMODE_EXP2;
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21166. /** The fog density is following a linear function. */
  21167. get: function () {
  21168. return Scene._FOGMODE_LINEAR;
  21169. },
  21170. enumerable: true,
  21171. configurable: true
  21172. });
  21173. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21174. /**
  21175. * Texture used in all pbr material as the reflection texture.
  21176. * As in the majority of the scene they are the same (exception for multi room and so on),
  21177. * this is easier to reference from here than from all the materials.
  21178. */
  21179. get: function () {
  21180. return this._environmentTexture;
  21181. },
  21182. /**
  21183. * Texture used in all pbr material as the reflection texture.
  21184. * As in the majority of the scene they are the same (exception for multi room and so on),
  21185. * this is easier to set here than in all the materials.
  21186. */
  21187. set: function (value) {
  21188. if (this._environmentTexture === value) {
  21189. return;
  21190. }
  21191. this._environmentTexture = value;
  21192. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21193. },
  21194. enumerable: true,
  21195. configurable: true
  21196. });
  21197. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21198. /**
  21199. * Default image processing configuration used either in the rendering
  21200. * Forward main pass or through the imageProcessingPostProcess if present.
  21201. * As in the majority of the scene they are the same (exception for multi camera),
  21202. * this is easier to reference from here than from all the materials and post process.
  21203. *
  21204. * No setter as we it is a shared configuration, you can set the values instead.
  21205. */
  21206. get: function () {
  21207. return this._imageProcessingConfiguration;
  21208. },
  21209. enumerable: true,
  21210. configurable: true
  21211. });
  21212. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21213. get: function () {
  21214. return this._forcePointsCloud;
  21215. },
  21216. set: function (value) {
  21217. if (this._forcePointsCloud === value) {
  21218. return;
  21219. }
  21220. this._forcePointsCloud = value;
  21221. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21222. },
  21223. enumerable: true,
  21224. configurable: true
  21225. });
  21226. Object.defineProperty(Scene.prototype, "onDispose", {
  21227. /** A function to be executed when this scene is disposed. */
  21228. set: function (callback) {
  21229. if (this._onDisposeObserver) {
  21230. this.onDisposeObservable.remove(this._onDisposeObserver);
  21231. }
  21232. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21233. },
  21234. enumerable: true,
  21235. configurable: true
  21236. });
  21237. Object.defineProperty(Scene.prototype, "beforeRender", {
  21238. /** A function to be executed before rendering this scene */
  21239. set: function (callback) {
  21240. if (this._onBeforeRenderObserver) {
  21241. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21242. }
  21243. if (callback) {
  21244. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21245. }
  21246. },
  21247. enumerable: true,
  21248. configurable: true
  21249. });
  21250. Object.defineProperty(Scene.prototype, "afterRender", {
  21251. /** A function to be executed after rendering this scene */
  21252. set: function (callback) {
  21253. if (this._onAfterRenderObserver) {
  21254. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21255. }
  21256. if (callback) {
  21257. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21258. }
  21259. },
  21260. enumerable: true,
  21261. configurable: true
  21262. });
  21263. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21264. set: function (callback) {
  21265. if (this._onBeforeCameraRenderObserver) {
  21266. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21267. }
  21268. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21269. },
  21270. enumerable: true,
  21271. configurable: true
  21272. });
  21273. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21274. set: function (callback) {
  21275. if (this._onAfterCameraRenderObserver) {
  21276. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21277. }
  21278. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21279. },
  21280. enumerable: true,
  21281. configurable: true
  21282. });
  21283. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21284. get: function () {
  21285. if (!this._gamepadManager) {
  21286. this._gamepadManager = new BABYLON.GamepadManager(this);
  21287. }
  21288. return this._gamepadManager;
  21289. },
  21290. enumerable: true,
  21291. configurable: true
  21292. });
  21293. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21294. get: function () {
  21295. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21296. },
  21297. enumerable: true,
  21298. configurable: true
  21299. });
  21300. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21301. get: function () {
  21302. return this._useRightHandedSystem;
  21303. },
  21304. set: function (value) {
  21305. if (this._useRightHandedSystem === value) {
  21306. return;
  21307. }
  21308. this._useRightHandedSystem = value;
  21309. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21310. },
  21311. enumerable: true,
  21312. configurable: true
  21313. });
  21314. Scene.prototype.setStepId = function (newStepId) {
  21315. this._currentStepId = newStepId;
  21316. };
  21317. ;
  21318. Scene.prototype.getStepId = function () {
  21319. return this._currentStepId;
  21320. };
  21321. ;
  21322. Scene.prototype.getInternalStep = function () {
  21323. return this._currentInternalStep;
  21324. };
  21325. ;
  21326. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21327. get: function () {
  21328. return this._fogEnabled;
  21329. },
  21330. /**
  21331. * is fog enabled on this scene.
  21332. */
  21333. set: function (value) {
  21334. if (this._fogEnabled === value) {
  21335. return;
  21336. }
  21337. this._fogEnabled = value;
  21338. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Scene.prototype, "fogMode", {
  21344. get: function () {
  21345. return this._fogMode;
  21346. },
  21347. set: function (value) {
  21348. if (this._fogMode === value) {
  21349. return;
  21350. }
  21351. this._fogMode = value;
  21352. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21353. },
  21354. enumerable: true,
  21355. configurable: true
  21356. });
  21357. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21358. get: function () {
  21359. return this._shadowsEnabled;
  21360. },
  21361. set: function (value) {
  21362. if (this._shadowsEnabled === value) {
  21363. return;
  21364. }
  21365. this._shadowsEnabled = value;
  21366. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21367. },
  21368. enumerable: true,
  21369. configurable: true
  21370. });
  21371. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21372. get: function () {
  21373. return this._lightsEnabled;
  21374. },
  21375. set: function (value) {
  21376. if (this._lightsEnabled === value) {
  21377. return;
  21378. }
  21379. this._lightsEnabled = value;
  21380. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21381. },
  21382. enumerable: true,
  21383. configurable: true
  21384. });
  21385. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21386. /** The default material used on meshes when no material is affected */
  21387. get: function () {
  21388. if (!this._defaultMaterial) {
  21389. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21390. }
  21391. return this._defaultMaterial;
  21392. },
  21393. /** The default material used on meshes when no material is affected */
  21394. set: function (value) {
  21395. this._defaultMaterial = value;
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21401. get: function () {
  21402. return this._texturesEnabled;
  21403. },
  21404. set: function (value) {
  21405. if (this._texturesEnabled === value) {
  21406. return;
  21407. }
  21408. this._texturesEnabled = value;
  21409. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21410. },
  21411. enumerable: true,
  21412. configurable: true
  21413. });
  21414. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21415. get: function () {
  21416. return this._skeletonsEnabled;
  21417. },
  21418. set: function (value) {
  21419. if (this._skeletonsEnabled === value) {
  21420. return;
  21421. }
  21422. this._skeletonsEnabled = value;
  21423. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21424. },
  21425. enumerable: true,
  21426. configurable: true
  21427. });
  21428. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21429. get: function () {
  21430. if (!this._postProcessRenderPipelineManager) {
  21431. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21432. }
  21433. return this._postProcessRenderPipelineManager;
  21434. },
  21435. enumerable: true,
  21436. configurable: true
  21437. });
  21438. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21439. get: function () {
  21440. if (!this._mainSoundTrack) {
  21441. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21442. }
  21443. return this._mainSoundTrack;
  21444. },
  21445. enumerable: true,
  21446. configurable: true
  21447. });
  21448. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21449. get: function () {
  21450. return this._alternateRendering;
  21451. },
  21452. enumerable: true,
  21453. configurable: true
  21454. });
  21455. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21456. get: function () {
  21457. return this._frustumPlanes;
  21458. },
  21459. enumerable: true,
  21460. configurable: true
  21461. });
  21462. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21463. /**
  21464. * Gets the current geometry buffer associated to the scene.
  21465. */
  21466. get: function () {
  21467. return this._geometryBufferRenderer;
  21468. },
  21469. /**
  21470. * Sets the current geometry buffer for the scene.
  21471. */
  21472. set: function (geometryBufferRenderer) {
  21473. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21474. this._geometryBufferRenderer = geometryBufferRenderer;
  21475. }
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. Object.defineProperty(Scene.prototype, "debugLayer", {
  21481. // Properties
  21482. get: function () {
  21483. if (!this._debugLayer) {
  21484. this._debugLayer = new BABYLON.DebugLayer(this);
  21485. }
  21486. return this._debugLayer;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21492. get: function () {
  21493. return this._workerCollisions;
  21494. },
  21495. set: function (enabled) {
  21496. if (!BABYLON.CollisionCoordinatorLegacy) {
  21497. return;
  21498. }
  21499. enabled = (enabled && !!Worker);
  21500. this._workerCollisions = enabled;
  21501. if (this.collisionCoordinator) {
  21502. this.collisionCoordinator.destroy();
  21503. }
  21504. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21505. this.collisionCoordinator.init(this);
  21506. },
  21507. enumerable: true,
  21508. configurable: true
  21509. });
  21510. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21511. get: function () {
  21512. return this._selectionOctree;
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21518. /**
  21519. * The mesh that is currently under the pointer.
  21520. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21521. */
  21522. get: function () {
  21523. return this._pointerOverMesh;
  21524. },
  21525. enumerable: true,
  21526. configurable: true
  21527. });
  21528. Object.defineProperty(Scene.prototype, "pointerX", {
  21529. /**
  21530. * Current on-screen X position of the pointer
  21531. * @return {number} X position of the pointer
  21532. */
  21533. get: function () {
  21534. return this._pointerX;
  21535. },
  21536. enumerable: true,
  21537. configurable: true
  21538. });
  21539. Object.defineProperty(Scene.prototype, "pointerY", {
  21540. /**
  21541. * Current on-screen Y position of the pointer
  21542. * @return {number} Y position of the pointer
  21543. */
  21544. get: function () {
  21545. return this._pointerY;
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. Scene.prototype.getCachedMaterial = function () {
  21551. return this._cachedMaterial;
  21552. };
  21553. Scene.prototype.getCachedEffect = function () {
  21554. return this._cachedEffect;
  21555. };
  21556. Scene.prototype.getCachedVisibility = function () {
  21557. return this._cachedVisibility;
  21558. };
  21559. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21560. if (visibility === void 0) { visibility = 1; }
  21561. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21562. };
  21563. Scene.prototype.getBoundingBoxRenderer = function () {
  21564. if (!this._boundingBoxRenderer) {
  21565. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21566. }
  21567. return this._boundingBoxRenderer;
  21568. };
  21569. Scene.prototype.getOutlineRenderer = function () {
  21570. return this._outlineRenderer;
  21571. };
  21572. Scene.prototype.getEngine = function () {
  21573. return this._engine;
  21574. };
  21575. Scene.prototype.getTotalVertices = function () {
  21576. return this._totalVertices.current;
  21577. };
  21578. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21579. get: function () {
  21580. return this._totalVertices;
  21581. },
  21582. enumerable: true,
  21583. configurable: true
  21584. });
  21585. Scene.prototype.getActiveIndices = function () {
  21586. return this._activeIndices.current;
  21587. };
  21588. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21589. get: function () {
  21590. return this._activeIndices;
  21591. },
  21592. enumerable: true,
  21593. configurable: true
  21594. });
  21595. Scene.prototype.getActiveParticles = function () {
  21596. return this._activeParticles.current;
  21597. };
  21598. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21599. get: function () {
  21600. return this._activeParticles;
  21601. },
  21602. enumerable: true,
  21603. configurable: true
  21604. });
  21605. Scene.prototype.getActiveBones = function () {
  21606. return this._activeBones.current;
  21607. };
  21608. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21609. get: function () {
  21610. return this._activeBones;
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. // Stats
  21616. Scene.prototype.getInterFramePerfCounter = function () {
  21617. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21618. return 0;
  21619. };
  21620. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21621. get: function () {
  21622. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21623. return null;
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. Scene.prototype.getLastFrameDuration = function () {
  21629. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21630. return 0;
  21631. };
  21632. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21633. get: function () {
  21634. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21635. return null;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21641. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21642. return 0;
  21643. };
  21644. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21645. get: function () {
  21646. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21647. return null;
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. Scene.prototype.getActiveMeshes = function () {
  21653. return this._activeMeshes;
  21654. };
  21655. Scene.prototype.getRenderTargetsDuration = function () {
  21656. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21657. return 0;
  21658. };
  21659. Scene.prototype.getRenderDuration = function () {
  21660. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21661. return 0;
  21662. };
  21663. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21664. get: function () {
  21665. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21666. return null;
  21667. },
  21668. enumerable: true,
  21669. configurable: true
  21670. });
  21671. Scene.prototype.getParticlesDuration = function () {
  21672. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21673. return 0;
  21674. };
  21675. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21676. get: function () {
  21677. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21678. return null;
  21679. },
  21680. enumerable: true,
  21681. configurable: true
  21682. });
  21683. Scene.prototype.getSpritesDuration = function () {
  21684. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21685. return 0;
  21686. };
  21687. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21688. get: function () {
  21689. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21690. return null;
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. Scene.prototype.getAnimationRatio = function () {
  21696. return this._animationRatio;
  21697. };
  21698. Scene.prototype.getRenderId = function () {
  21699. return this._renderId;
  21700. };
  21701. Scene.prototype.incrementRenderId = function () {
  21702. this._renderId++;
  21703. };
  21704. Scene.prototype._updatePointerPosition = function (evt) {
  21705. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21706. if (!canvasRect) {
  21707. return;
  21708. }
  21709. this._pointerX = evt.clientX - canvasRect.left;
  21710. this._pointerY = evt.clientY - canvasRect.top;
  21711. this._unTranslatedPointerX = this._pointerX;
  21712. this._unTranslatedPointerY = this._pointerY;
  21713. };
  21714. Scene.prototype._createUbo = function () {
  21715. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21716. this._sceneUbo.addUniform("viewProjection", 16);
  21717. this._sceneUbo.addUniform("view", 16);
  21718. };
  21719. Scene.prototype._createAlternateUbo = function () {
  21720. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21721. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21722. this._alternateSceneUbo.addUniform("view", 16);
  21723. };
  21724. // Pointers handling
  21725. /**
  21726. * Use this method to simulate a pointer move on a mesh
  21727. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21728. */
  21729. Scene.prototype.simulatePointerMove = function (pickResult) {
  21730. var evt = new PointerEvent("pointermove");
  21731. return this._processPointerMove(pickResult, evt);
  21732. };
  21733. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21734. var canvas = this._engine.getRenderingCanvas();
  21735. if (!canvas) {
  21736. return this;
  21737. }
  21738. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21739. this.setPointerOverSprite(null);
  21740. this.setPointerOverMesh(pickResult.pickedMesh);
  21741. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21742. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21743. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21744. }
  21745. else {
  21746. canvas.style.cursor = this.hoverCursor;
  21747. }
  21748. }
  21749. else {
  21750. canvas.style.cursor = this.defaultCursor;
  21751. }
  21752. }
  21753. else {
  21754. this.setPointerOverMesh(null);
  21755. // Sprites
  21756. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21757. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21758. this.setPointerOverSprite(pickResult.pickedSprite);
  21759. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21760. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21761. }
  21762. else {
  21763. canvas.style.cursor = this.hoverCursor;
  21764. }
  21765. }
  21766. else {
  21767. this.setPointerOverSprite(null);
  21768. // Restore pointer
  21769. canvas.style.cursor = this.defaultCursor;
  21770. }
  21771. }
  21772. if (pickResult) {
  21773. if (this.onPointerMove) {
  21774. this.onPointerMove(evt, pickResult);
  21775. }
  21776. if (this.onPointerObservable.hasObservers()) {
  21777. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21778. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21779. this.onPointerObservable.notifyObservers(pi, type);
  21780. }
  21781. }
  21782. return this;
  21783. };
  21784. /**
  21785. * Use this method to simulate a pointer down on a mesh
  21786. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21787. */
  21788. Scene.prototype.simulatePointerDown = function (pickResult) {
  21789. var evt = new PointerEvent("pointerdown");
  21790. return this._processPointerDown(pickResult, evt);
  21791. };
  21792. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21793. var _this = this;
  21794. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21795. this._pickedDownMesh = pickResult.pickedMesh;
  21796. var actionManager = pickResult.pickedMesh.actionManager;
  21797. if (actionManager) {
  21798. if (actionManager.hasPickTriggers) {
  21799. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21800. switch (evt.button) {
  21801. case 0:
  21802. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21803. break;
  21804. case 1:
  21805. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21806. break;
  21807. case 2:
  21808. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21809. break;
  21810. }
  21811. }
  21812. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21813. window.setTimeout(function () {
  21814. 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);
  21815. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21816. if (_this._totalPointersPressed !== 0 &&
  21817. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21818. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21819. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21820. _this._startingPointerTime = 0;
  21821. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21822. }
  21823. }
  21824. }, Scene.LongPressDelay);
  21825. }
  21826. }
  21827. }
  21828. if (pickResult) {
  21829. if (this.onPointerDown) {
  21830. this.onPointerDown(evt, pickResult);
  21831. }
  21832. if (this.onPointerObservable.hasObservers()) {
  21833. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21834. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21835. this.onPointerObservable.notifyObservers(pi, type);
  21836. }
  21837. }
  21838. return this;
  21839. };
  21840. /**
  21841. * Use this method to simulate a pointer up on a mesh
  21842. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21843. */
  21844. Scene.prototype.simulatePointerUp = function (pickResult) {
  21845. var evt = new PointerEvent("pointerup");
  21846. var clickInfo = new ClickInfo();
  21847. clickInfo.singleClick = true;
  21848. clickInfo.ignore = true;
  21849. return this._processPointerUp(pickResult, evt, clickInfo);
  21850. };
  21851. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21852. if (pickResult && pickResult && pickResult.pickedMesh) {
  21853. this._pickedUpMesh = pickResult.pickedMesh;
  21854. if (this._pickedDownMesh === this._pickedUpMesh) {
  21855. if (this.onPointerPick) {
  21856. this.onPointerPick(evt, pickResult);
  21857. }
  21858. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21859. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21860. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21861. this.onPointerObservable.notifyObservers(pi, type);
  21862. }
  21863. }
  21864. if (pickResult.pickedMesh.actionManager) {
  21865. if (clickInfo.ignore) {
  21866. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21867. }
  21868. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21869. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21870. }
  21871. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21872. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21873. }
  21874. }
  21875. }
  21876. if (this._pickedDownMesh &&
  21877. this._pickedDownMesh.actionManager &&
  21878. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21879. this._pickedDownMesh !== this._pickedUpMesh) {
  21880. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21881. }
  21882. if (this.onPointerUp) {
  21883. this.onPointerUp(evt, pickResult);
  21884. }
  21885. if (this.onPointerObservable.hasObservers()) {
  21886. if (!clickInfo.ignore) {
  21887. if (!clickInfo.hasSwiped) {
  21888. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21889. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21890. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21891. this.onPointerObservable.notifyObservers(pi, type);
  21892. }
  21893. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21894. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21895. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21896. this.onPointerObservable.notifyObservers(pi, type);
  21897. }
  21898. }
  21899. }
  21900. else {
  21901. var type = BABYLON.PointerEventTypes.POINTERUP;
  21902. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21903. this.onPointerObservable.notifyObservers(pi, type);
  21904. }
  21905. }
  21906. return this;
  21907. };
  21908. /**
  21909. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21910. * @param attachUp defines if you want to attach events to pointerup
  21911. * @param attachDown defines if you want to attach events to pointerdown
  21912. * @param attachMove defines if you want to attach events to pointermove
  21913. */
  21914. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21915. var _this = this;
  21916. if (attachUp === void 0) { attachUp = true; }
  21917. if (attachDown === void 0) { attachDown = true; }
  21918. if (attachMove === void 0) { attachMove = true; }
  21919. this._initActionManager = function (act, clickInfo) {
  21920. if (!_this._meshPickProceed) {
  21921. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21922. _this._currentPickResult = pickResult;
  21923. if (pickResult) {
  21924. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21925. }
  21926. _this._meshPickProceed = true;
  21927. }
  21928. return act;
  21929. };
  21930. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21931. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21932. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21933. btn !== _this._previousButtonPressed) {
  21934. _this._doubleClickOccured = false;
  21935. clickInfo.singleClick = true;
  21936. clickInfo.ignore = false;
  21937. cb(clickInfo, _this._currentPickResult);
  21938. }
  21939. };
  21940. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21941. var clickInfo = new ClickInfo();
  21942. _this._currentPickResult = null;
  21943. var act = null;
  21944. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21945. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21946. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21947. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21948. act = _this._initActionManager(act, clickInfo);
  21949. if (act)
  21950. checkPicking = act.hasPickTriggers;
  21951. }
  21952. if (checkPicking) {
  21953. var btn = evt.button;
  21954. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21955. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21956. if (!clickInfo.hasSwiped) {
  21957. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21958. if (!checkSingleClickImmediately) {
  21959. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21960. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21961. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21962. act = _this._initActionManager(act, clickInfo);
  21963. if (act)
  21964. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21965. }
  21966. }
  21967. if (checkSingleClickImmediately) {
  21968. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21969. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21970. btn !== _this._previousButtonPressed) {
  21971. clickInfo.singleClick = true;
  21972. cb(clickInfo, _this._currentPickResult);
  21973. }
  21974. }
  21975. else {
  21976. // wait that no double click has been raised during the double click delay
  21977. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21978. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21979. }
  21980. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21981. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21982. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21983. act = _this._initActionManager(act, clickInfo);
  21984. if (act)
  21985. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21986. }
  21987. if (checkDoubleClick) {
  21988. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21989. if (btn === _this._previousButtonPressed &&
  21990. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21991. !_this._doubleClickOccured) {
  21992. // pointer has not moved for 2 clicks, it's a double click
  21993. if (!clickInfo.hasSwiped &&
  21994. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21995. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21996. _this._previousStartingPointerTime = 0;
  21997. _this._doubleClickOccured = true;
  21998. clickInfo.doubleClick = true;
  21999. clickInfo.ignore = false;
  22000. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22001. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22002. }
  22003. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22004. cb(clickInfo, _this._currentPickResult);
  22005. }
  22006. else {
  22007. _this._doubleClickOccured = false;
  22008. _this._previousStartingPointerTime = _this._startingPointerTime;
  22009. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22010. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22011. _this._previousButtonPressed = btn;
  22012. if (Scene.ExclusiveDoubleClickMode) {
  22013. if (_this._previousDelayedSimpleClickTimeout) {
  22014. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22015. }
  22016. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22017. cb(clickInfo, _this._previousPickResult);
  22018. }
  22019. else {
  22020. cb(clickInfo, _this._currentPickResult);
  22021. }
  22022. }
  22023. }
  22024. else {
  22025. _this._doubleClickOccured = false;
  22026. _this._previousStartingPointerTime = _this._startingPointerTime;
  22027. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22028. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22029. _this._previousButtonPressed = btn;
  22030. }
  22031. }
  22032. }
  22033. }
  22034. clickInfo.ignore = true;
  22035. cb(clickInfo, _this._currentPickResult);
  22036. };
  22037. this._spritePredicate = function (sprite) {
  22038. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22039. };
  22040. this._onPointerMove = function (evt) {
  22041. _this._updatePointerPosition(evt);
  22042. // PreObservable support
  22043. if (_this.onPrePointerObservable.hasObservers()) {
  22044. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22045. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22046. _this.onPrePointerObservable.notifyObservers(pi, type);
  22047. if (pi.skipOnPointerObservable) {
  22048. return;
  22049. }
  22050. }
  22051. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22052. return;
  22053. }
  22054. if (!_this.pointerMovePredicate) {
  22055. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22056. }
  22057. // Meshes
  22058. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22059. _this._processPointerMove(pickResult, evt);
  22060. };
  22061. this._onPointerDown = function (evt) {
  22062. _this._totalPointersPressed++;
  22063. _this._pickedDownMesh = null;
  22064. _this._meshPickProceed = false;
  22065. _this._updatePointerPosition(evt);
  22066. if (_this.preventDefaultOnPointerDown && canvas) {
  22067. evt.preventDefault();
  22068. canvas.focus();
  22069. }
  22070. // PreObservable support
  22071. if (_this.onPrePointerObservable.hasObservers()) {
  22072. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22073. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22074. _this.onPrePointerObservable.notifyObservers(pi, type);
  22075. if (pi.skipOnPointerObservable) {
  22076. return;
  22077. }
  22078. }
  22079. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22080. return;
  22081. }
  22082. _this._startingPointerPosition.x = _this._pointerX;
  22083. _this._startingPointerPosition.y = _this._pointerY;
  22084. _this._startingPointerTime = new Date().getTime();
  22085. if (!_this.pointerDownPredicate) {
  22086. _this.pointerDownPredicate = function (mesh) {
  22087. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22088. };
  22089. }
  22090. // Meshes
  22091. _this._pickedDownMesh = null;
  22092. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22093. _this._processPointerDown(pickResult, evt);
  22094. // Sprites
  22095. _this._pickedDownSprite = null;
  22096. if (_this.spriteManagers.length > 0) {
  22097. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22098. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22099. if (pickResult.pickedSprite.actionManager) {
  22100. _this._pickedDownSprite = pickResult.pickedSprite;
  22101. switch (evt.button) {
  22102. case 0:
  22103. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22104. break;
  22105. case 1:
  22106. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22107. break;
  22108. case 2:
  22109. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22110. break;
  22111. }
  22112. if (pickResult.pickedSprite.actionManager) {
  22113. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22114. }
  22115. }
  22116. }
  22117. }
  22118. };
  22119. this._onPointerUp = function (evt) {
  22120. if (_this._totalPointersPressed === 0) {
  22121. return; // So we need to test it the pointer down was pressed before.
  22122. }
  22123. _this._totalPointersPressed--;
  22124. _this._pickedUpMesh = null;
  22125. _this._meshPickProceed = false;
  22126. _this._updatePointerPosition(evt);
  22127. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22128. // PreObservable support
  22129. if (_this.onPrePointerObservable.hasObservers()) {
  22130. if (!clickInfo.ignore) {
  22131. if (!clickInfo.hasSwiped) {
  22132. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22133. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22134. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22135. _this.onPrePointerObservable.notifyObservers(pi, type);
  22136. if (pi.skipOnPointerObservable) {
  22137. return;
  22138. }
  22139. }
  22140. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22141. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22142. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22143. _this.onPrePointerObservable.notifyObservers(pi, type);
  22144. if (pi.skipOnPointerObservable) {
  22145. return;
  22146. }
  22147. }
  22148. }
  22149. }
  22150. else {
  22151. var type = BABYLON.PointerEventTypes.POINTERUP;
  22152. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22153. _this.onPrePointerObservable.notifyObservers(pi, type);
  22154. if (pi.skipOnPointerObservable) {
  22155. return;
  22156. }
  22157. }
  22158. }
  22159. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22160. return;
  22161. }
  22162. if (!_this.pointerUpPredicate) {
  22163. _this.pointerUpPredicate = function (mesh) {
  22164. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22165. };
  22166. }
  22167. // Meshes
  22168. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22169. _this._initActionManager(null, clickInfo);
  22170. }
  22171. if (!pickResult) {
  22172. pickResult = _this._currentPickResult;
  22173. }
  22174. _this._processPointerUp(pickResult, evt, clickInfo);
  22175. // Sprites
  22176. if (_this.spriteManagers.length > 0) {
  22177. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22178. if (spritePickResult) {
  22179. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22180. if (spritePickResult.pickedSprite.actionManager) {
  22181. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22182. if (spritePickResult.pickedSprite.actionManager) {
  22183. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22184. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22185. }
  22186. }
  22187. }
  22188. }
  22189. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22190. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22191. }
  22192. }
  22193. }
  22194. _this._previousPickResult = _this._currentPickResult;
  22195. });
  22196. };
  22197. this._onKeyDown = function (evt) {
  22198. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22199. if (_this.onPreKeyboardObservable.hasObservers()) {
  22200. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22201. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22202. if (pi.skipOnPointerObservable) {
  22203. return;
  22204. }
  22205. }
  22206. if (_this.onKeyboardObservable.hasObservers()) {
  22207. var pi = new BABYLON.KeyboardInfo(type, evt);
  22208. _this.onKeyboardObservable.notifyObservers(pi, type);
  22209. }
  22210. if (_this.actionManager) {
  22211. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22212. }
  22213. };
  22214. this._onKeyUp = function (evt) {
  22215. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22216. if (_this.onPreKeyboardObservable.hasObservers()) {
  22217. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22218. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22219. if (pi.skipOnPointerObservable) {
  22220. return;
  22221. }
  22222. }
  22223. if (_this.onKeyboardObservable.hasObservers()) {
  22224. var pi = new BABYLON.KeyboardInfo(type, evt);
  22225. _this.onKeyboardObservable.notifyObservers(pi, type);
  22226. }
  22227. if (_this.actionManager) {
  22228. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22229. }
  22230. };
  22231. var engine = this.getEngine();
  22232. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22233. if (!canvas) {
  22234. return;
  22235. }
  22236. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22237. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22238. });
  22239. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22240. if (!canvas) {
  22241. return;
  22242. }
  22243. canvas.removeEventListener("keydown", _this._onKeyDown);
  22244. canvas.removeEventListener("keyup", _this._onKeyUp);
  22245. });
  22246. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22247. var canvas = this._engine.getRenderingCanvas();
  22248. if (!canvas) {
  22249. return;
  22250. }
  22251. if (attachMove) {
  22252. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22253. // Wheel
  22254. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22255. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22256. }
  22257. if (attachDown) {
  22258. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22259. }
  22260. if (attachUp) {
  22261. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22262. }
  22263. canvas.tabIndex = 1;
  22264. };
  22265. Scene.prototype.detachControl = function () {
  22266. var engine = this.getEngine();
  22267. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22268. var canvas = engine.getRenderingCanvas();
  22269. if (!canvas) {
  22270. return;
  22271. }
  22272. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22273. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22274. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22275. if (this._onCanvasBlurObserver) {
  22276. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22277. }
  22278. if (this._onCanvasFocusObserver) {
  22279. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22280. }
  22281. // Wheel
  22282. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22283. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22284. // Keyboard
  22285. canvas.removeEventListener("keydown", this._onKeyDown);
  22286. canvas.removeEventListener("keyup", this._onKeyUp);
  22287. // Observables
  22288. this.onKeyboardObservable.clear();
  22289. this.onPreKeyboardObservable.clear();
  22290. this.onPointerObservable.clear();
  22291. this.onPrePointerObservable.clear();
  22292. };
  22293. /**
  22294. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22295. * Delay loaded resources are not taking in account
  22296. * @return true if all required resources are ready
  22297. */
  22298. Scene.prototype.isReady = function () {
  22299. if (this._isDisposed) {
  22300. return false;
  22301. }
  22302. if (this._pendingData.length > 0) {
  22303. return false;
  22304. }
  22305. var index;
  22306. var engine = this.getEngine();
  22307. // Geometries
  22308. for (index = 0; index < this._geometries.length; index++) {
  22309. var geometry = this._geometries[index];
  22310. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22311. return false;
  22312. }
  22313. }
  22314. // Meshes
  22315. for (index = 0; index < this.meshes.length; index++) {
  22316. var mesh = this.meshes[index];
  22317. if (!mesh.isEnabled()) {
  22318. continue;
  22319. }
  22320. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22321. continue;
  22322. }
  22323. if (!mesh.isReady()) {
  22324. return false;
  22325. }
  22326. // Effect layers
  22327. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22328. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22329. var layer = _a[_i];
  22330. if (!layer.hasMesh(mesh)) {
  22331. continue;
  22332. }
  22333. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22334. var subMesh = _c[_b];
  22335. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22336. return false;
  22337. }
  22338. }
  22339. }
  22340. }
  22341. return true;
  22342. };
  22343. Scene.prototype.resetCachedMaterial = function () {
  22344. this._cachedMaterial = null;
  22345. this._cachedEffect = null;
  22346. this._cachedVisibility = null;
  22347. };
  22348. Scene.prototype.registerBeforeRender = function (func) {
  22349. this.onBeforeRenderObservable.add(func);
  22350. };
  22351. Scene.prototype.unregisterBeforeRender = function (func) {
  22352. this.onBeforeRenderObservable.removeCallback(func);
  22353. };
  22354. Scene.prototype.registerAfterRender = function (func) {
  22355. this.onAfterRenderObservable.add(func);
  22356. };
  22357. Scene.prototype.unregisterAfterRender = function (func) {
  22358. this.onAfterRenderObservable.removeCallback(func);
  22359. };
  22360. Scene.prototype._executeOnceBeforeRender = function (func) {
  22361. var _this = this;
  22362. var execFunc = function () {
  22363. func();
  22364. setTimeout(function () {
  22365. _this.unregisterBeforeRender(execFunc);
  22366. });
  22367. };
  22368. this.registerBeforeRender(execFunc);
  22369. };
  22370. /**
  22371. * The provided function will run before render once and will be disposed afterwards.
  22372. * A timeout delay can be provided so that the function will be executed in N ms.
  22373. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22374. * @param func The function to be executed.
  22375. * @param timeout optional delay in ms
  22376. */
  22377. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22378. var _this = this;
  22379. if (timeout !== undefined) {
  22380. setTimeout(function () {
  22381. _this._executeOnceBeforeRender(func);
  22382. }, timeout);
  22383. }
  22384. else {
  22385. this._executeOnceBeforeRender(func);
  22386. }
  22387. };
  22388. Scene.prototype._addPendingData = function (data) {
  22389. this._pendingData.push(data);
  22390. };
  22391. Scene.prototype._removePendingData = function (data) {
  22392. var wasLoading = this.isLoading;
  22393. var index = this._pendingData.indexOf(data);
  22394. if (index !== -1) {
  22395. this._pendingData.splice(index, 1);
  22396. }
  22397. if (wasLoading && !this.isLoading) {
  22398. this.onDataLoadedObservable.notifyObservers(this);
  22399. }
  22400. };
  22401. Scene.prototype.getWaitingItemsCount = function () {
  22402. return this._pendingData.length;
  22403. };
  22404. Object.defineProperty(Scene.prototype, "isLoading", {
  22405. get: function () {
  22406. return this._pendingData.length > 0;
  22407. },
  22408. enumerable: true,
  22409. configurable: true
  22410. });
  22411. /**
  22412. * Registers a function to be executed when the scene is ready.
  22413. * @param {Function} func - the function to be executed.
  22414. */
  22415. Scene.prototype.executeWhenReady = function (func) {
  22416. var _this = this;
  22417. this.onReadyObservable.add(func);
  22418. if (this._executeWhenReadyTimeoutId !== -1) {
  22419. return;
  22420. }
  22421. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22422. _this._checkIsReady();
  22423. }, 150);
  22424. };
  22425. /**
  22426. * Returns a promise that resolves when the scene is ready.
  22427. * @returns A promise that resolves when the scene is ready.
  22428. */
  22429. Scene.prototype.whenReadyAsync = function () {
  22430. var _this = this;
  22431. return new Promise(function (resolve) {
  22432. _this.executeWhenReady(function () {
  22433. resolve();
  22434. });
  22435. });
  22436. };
  22437. Scene.prototype._checkIsReady = function () {
  22438. var _this = this;
  22439. if (this.isReady()) {
  22440. this.onReadyObservable.notifyObservers(this);
  22441. this.onReadyObservable.clear();
  22442. this._executeWhenReadyTimeoutId = -1;
  22443. return;
  22444. }
  22445. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22446. _this._checkIsReady();
  22447. }, 150);
  22448. };
  22449. // Animations
  22450. /**
  22451. * Will start the animation sequence of a given target
  22452. * @param target - the target
  22453. * @param {number} from - from which frame should animation start
  22454. * @param {number} to - till which frame should animation run.
  22455. * @param {boolean} [loop] - should the animation loop
  22456. * @param {number} [speedRatio] - the speed in which to run the animation
  22457. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22458. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22459. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22460. * See BABYLON.Animatable
  22461. */
  22462. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22463. if (speedRatio === void 0) { speedRatio = 1.0; }
  22464. if (from > to && speedRatio > 0) {
  22465. speedRatio *= -1;
  22466. }
  22467. this.stopAnimation(target);
  22468. if (!animatable) {
  22469. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22470. }
  22471. // Local animations
  22472. if (target.animations) {
  22473. animatable.appendAnimations(target, target.animations);
  22474. }
  22475. // Children animations
  22476. if (target.getAnimatables) {
  22477. var animatables = target.getAnimatables();
  22478. for (var index = 0; index < animatables.length; index++) {
  22479. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22480. }
  22481. }
  22482. animatable.reset();
  22483. return animatable;
  22484. };
  22485. /**
  22486. * Begin a new animation on a given node
  22487. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22488. * @param {BABYLON.Animation[]} defines the list of animations to start
  22489. * @param {number} from defines the initial value
  22490. * @param {number} to defines the final value
  22491. * @param {boolean} loop defines if you want animation to loop (off by default)
  22492. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22493. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22494. * @returns the list of created animatables
  22495. */
  22496. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22497. if (speedRatio === undefined) {
  22498. speedRatio = 1.0;
  22499. }
  22500. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22501. return animatable;
  22502. };
  22503. /**
  22504. * Begin a new animation on a given node and its hierarchy
  22505. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22506. * @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.
  22507. * @param {BABYLON.Animation[]} defines the list of animations to start
  22508. * @param {number} from defines the initial value
  22509. * @param {number} to defines the final value
  22510. * @param {boolean} loop defines if you want animation to loop (off by default)
  22511. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22512. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22513. * @returns the list of animatables created for all nodes
  22514. */
  22515. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22516. var children = target.getDescendants(directDescendantsOnly);
  22517. var result = [];
  22518. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22519. var child = children_1[_i];
  22520. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22521. }
  22522. return result;
  22523. };
  22524. Scene.prototype.getAnimatableByTarget = function (target) {
  22525. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22526. if (this._activeAnimatables[index].target === target) {
  22527. return this._activeAnimatables[index];
  22528. }
  22529. }
  22530. return null;
  22531. };
  22532. Object.defineProperty(Scene.prototype, "animatables", {
  22533. get: function () {
  22534. return this._activeAnimatables;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. /**
  22540. * Will stop the animation of the given target
  22541. * @param target - the target
  22542. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22543. * @see beginAnimation
  22544. */
  22545. Scene.prototype.stopAnimation = function (target, animationName) {
  22546. var animatable = this.getAnimatableByTarget(target);
  22547. if (animatable) {
  22548. animatable.stop(animationName);
  22549. }
  22550. };
  22551. /**
  22552. * Stops and removes all animations that have been applied to the scene
  22553. */
  22554. Scene.prototype.stopAllAnimations = function () {
  22555. if (this._activeAnimatables) {
  22556. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22557. this._activeAnimatables[i].stop();
  22558. }
  22559. this._activeAnimatables = [];
  22560. }
  22561. };
  22562. Scene.prototype._animate = function () {
  22563. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22564. return;
  22565. }
  22566. // Getting time
  22567. var now = BABYLON.Tools.Now;
  22568. if (!this._animationTimeLast) {
  22569. if (this._pendingData.length > 0) {
  22570. return;
  22571. }
  22572. this._animationTimeLast = now;
  22573. }
  22574. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22575. this._animationTime += deltaTime;
  22576. this._animationTimeLast = now;
  22577. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22578. this._activeAnimatables[index]._animate(this._animationTime);
  22579. }
  22580. };
  22581. // Matrix
  22582. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22583. this._useAlternateCameraConfiguration = active;
  22584. };
  22585. Scene.prototype.getViewMatrix = function () {
  22586. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22587. };
  22588. Scene.prototype.getProjectionMatrix = function () {
  22589. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22590. };
  22591. Scene.prototype.getTransformMatrix = function () {
  22592. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22593. };
  22594. Scene.prototype.setTransformMatrix = function (view, projection) {
  22595. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22596. return;
  22597. }
  22598. this._viewUpdateFlag = view.updateFlag;
  22599. this._projectionUpdateFlag = projection.updateFlag;
  22600. this._viewMatrix = view;
  22601. this._projectionMatrix = projection;
  22602. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22603. // Update frustum
  22604. if (!this._frustumPlanes) {
  22605. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22606. }
  22607. else {
  22608. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22609. }
  22610. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22611. var otherCamera = this.activeCamera._alternateCamera;
  22612. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22613. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22614. }
  22615. if (this._sceneUbo.useUbo) {
  22616. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22617. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22618. this._sceneUbo.update();
  22619. }
  22620. };
  22621. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22622. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22623. return;
  22624. }
  22625. this._alternateViewUpdateFlag = view.updateFlag;
  22626. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22627. this._alternateViewMatrix = view;
  22628. this._alternateProjectionMatrix = projection;
  22629. if (!this._alternateTransformMatrix) {
  22630. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22631. }
  22632. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22633. if (!this._alternateSceneUbo) {
  22634. this._createAlternateUbo();
  22635. }
  22636. if (this._alternateSceneUbo.useUbo) {
  22637. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22638. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22639. this._alternateSceneUbo.update();
  22640. }
  22641. };
  22642. Scene.prototype.getSceneUniformBuffer = function () {
  22643. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22644. };
  22645. // Methods
  22646. Scene.prototype.getUniqueId = function () {
  22647. var result = Scene._uniqueIdCounter;
  22648. Scene._uniqueIdCounter++;
  22649. return result;
  22650. };
  22651. Scene.prototype.addMesh = function (newMesh) {
  22652. this.meshes.push(newMesh);
  22653. //notify the collision coordinator
  22654. if (this.collisionCoordinator) {
  22655. this.collisionCoordinator.onMeshAdded(newMesh);
  22656. }
  22657. newMesh._resyncLightSources();
  22658. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22659. };
  22660. Scene.prototype.removeMesh = function (toRemove) {
  22661. var index = this.meshes.indexOf(toRemove);
  22662. if (index !== -1) {
  22663. // Remove from the scene if mesh found
  22664. this.meshes.splice(index, 1);
  22665. }
  22666. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22667. return index;
  22668. };
  22669. Scene.prototype.addTransformNode = function (newTransformNode) {
  22670. this.transformNodes.push(newTransformNode);
  22671. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22672. };
  22673. Scene.prototype.removeTransformNode = function (toRemove) {
  22674. var index = this.transformNodes.indexOf(toRemove);
  22675. if (index !== -1) {
  22676. // Remove from the scene if found
  22677. this.transformNodes.splice(index, 1);
  22678. }
  22679. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22680. return index;
  22681. };
  22682. Scene.prototype.removeSkeleton = function (toRemove) {
  22683. var index = this.skeletons.indexOf(toRemove);
  22684. if (index !== -1) {
  22685. // Remove from the scene if found
  22686. this.skeletons.splice(index, 1);
  22687. }
  22688. return index;
  22689. };
  22690. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22691. var index = this.morphTargetManagers.indexOf(toRemove);
  22692. if (index !== -1) {
  22693. // Remove from the scene if found
  22694. this.morphTargetManagers.splice(index, 1);
  22695. }
  22696. return index;
  22697. };
  22698. Scene.prototype.removeLight = function (toRemove) {
  22699. var index = this.lights.indexOf(toRemove);
  22700. if (index !== -1) {
  22701. // Remove from meshes
  22702. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22703. var mesh = _a[_i];
  22704. mesh._removeLightSource(toRemove);
  22705. }
  22706. // Remove from the scene if mesh found
  22707. this.lights.splice(index, 1);
  22708. this.sortLightsByPriority();
  22709. }
  22710. this.onLightRemovedObservable.notifyObservers(toRemove);
  22711. return index;
  22712. };
  22713. Scene.prototype.removeCamera = function (toRemove) {
  22714. var index = this.cameras.indexOf(toRemove);
  22715. if (index !== -1) {
  22716. // Remove from the scene if mesh found
  22717. this.cameras.splice(index, 1);
  22718. }
  22719. // Remove from activeCameras
  22720. var index2 = this.activeCameras.indexOf(toRemove);
  22721. if (index2 !== -1) {
  22722. // Remove from the scene if mesh found
  22723. this.activeCameras.splice(index2, 1);
  22724. }
  22725. // Reset the activeCamera
  22726. if (this.activeCamera === toRemove) {
  22727. if (this.cameras.length > 0) {
  22728. this.activeCamera = this.cameras[0];
  22729. }
  22730. else {
  22731. this.activeCamera = null;
  22732. }
  22733. }
  22734. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22735. return index;
  22736. };
  22737. Scene.prototype.removeParticleSystem = function (toRemove) {
  22738. var index = this.particleSystems.indexOf(toRemove);
  22739. if (index !== -1) {
  22740. this.particleSystems.splice(index, 1);
  22741. }
  22742. return index;
  22743. };
  22744. ;
  22745. Scene.prototype.removeAnimation = function (toRemove) {
  22746. var index = this.animations.indexOf(toRemove);
  22747. if (index !== -1) {
  22748. this.animations.splice(index, 1);
  22749. }
  22750. return index;
  22751. };
  22752. ;
  22753. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22754. var index = this.multiMaterials.indexOf(toRemove);
  22755. if (index !== -1) {
  22756. this.multiMaterials.splice(index, 1);
  22757. }
  22758. return index;
  22759. };
  22760. ;
  22761. Scene.prototype.removeMaterial = function (toRemove) {
  22762. var index = this.materials.indexOf(toRemove);
  22763. if (index !== -1) {
  22764. this.materials.splice(index, 1);
  22765. }
  22766. return index;
  22767. };
  22768. ;
  22769. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22770. var index = this.lensFlareSystems.indexOf(toRemove);
  22771. if (index !== -1) {
  22772. this.lensFlareSystems.splice(index, 1);
  22773. }
  22774. return index;
  22775. };
  22776. ;
  22777. Scene.prototype.removeActionManager = function (toRemove) {
  22778. var index = this._actionManagers.indexOf(toRemove);
  22779. if (index !== -1) {
  22780. this._actionManagers.splice(index, 1);
  22781. }
  22782. return index;
  22783. };
  22784. ;
  22785. Scene.prototype.addLight = function (newLight) {
  22786. this.lights.push(newLight);
  22787. this.sortLightsByPriority();
  22788. // Add light to all meshes (To support if the light is removed and then readded)
  22789. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22790. var mesh = _a[_i];
  22791. if (mesh._lightSources.indexOf(newLight) === -1) {
  22792. mesh._lightSources.push(newLight);
  22793. mesh._resyncLightSources();
  22794. }
  22795. }
  22796. this.onNewLightAddedObservable.notifyObservers(newLight);
  22797. };
  22798. Scene.prototype.sortLightsByPriority = function () {
  22799. if (this.requireLightSorting) {
  22800. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22801. }
  22802. };
  22803. Scene.prototype.addCamera = function (newCamera) {
  22804. this.cameras.push(newCamera);
  22805. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22806. };
  22807. Scene.prototype.addSkeleton = function (newSkeleton) {
  22808. this.skeletons.push(newSkeleton);
  22809. };
  22810. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22811. this.particleSystems.push(newParticleSystem);
  22812. };
  22813. Scene.prototype.addAnimation = function (newAnimation) {
  22814. this.animations.push(newAnimation);
  22815. };
  22816. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22817. this.multiMaterials.push(newMultiMaterial);
  22818. };
  22819. Scene.prototype.addMaterial = function (newMaterial) {
  22820. this.materials.push(newMaterial);
  22821. };
  22822. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22823. this.morphTargetManagers.push(newMorphTargetManager);
  22824. };
  22825. Scene.prototype.addGeometry = function (newGeometrie) {
  22826. this._geometries.push(newGeometrie);
  22827. };
  22828. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22829. this.lensFlareSystems.push(newLensFlareSystem);
  22830. };
  22831. Scene.prototype.addActionManager = function (newActionManager) {
  22832. this._actionManagers.push(newActionManager);
  22833. };
  22834. /**
  22835. * Switch active camera
  22836. * @param {Camera} newCamera - new active camera
  22837. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22838. */
  22839. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22840. if (attachControl === void 0) { attachControl = true; }
  22841. var canvas = this._engine.getRenderingCanvas();
  22842. if (!canvas) {
  22843. return;
  22844. }
  22845. if (this.activeCamera) {
  22846. this.activeCamera.detachControl(canvas);
  22847. }
  22848. this.activeCamera = newCamera;
  22849. if (attachControl) {
  22850. newCamera.attachControl(canvas);
  22851. }
  22852. };
  22853. /**
  22854. * sets the active camera of the scene using its ID
  22855. * @param {string} id - the camera's ID
  22856. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22857. * @see activeCamera
  22858. */
  22859. Scene.prototype.setActiveCameraByID = function (id) {
  22860. var camera = this.getCameraByID(id);
  22861. if (camera) {
  22862. this.activeCamera = camera;
  22863. return camera;
  22864. }
  22865. return null;
  22866. };
  22867. /**
  22868. * sets the active camera of the scene using its name
  22869. * @param {string} name - the camera's name
  22870. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22871. * @see activeCamera
  22872. */
  22873. Scene.prototype.setActiveCameraByName = function (name) {
  22874. var camera = this.getCameraByName(name);
  22875. if (camera) {
  22876. this.activeCamera = camera;
  22877. return camera;
  22878. }
  22879. return null;
  22880. };
  22881. /**
  22882. * get an animation group using its name
  22883. * @param {string} the material's name
  22884. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22885. */
  22886. Scene.prototype.getAnimationGroupByName = function (name) {
  22887. for (var index = 0; index < this.animationGroups.length; index++) {
  22888. if (this.animationGroups[index].name === name) {
  22889. return this.animationGroups[index];
  22890. }
  22891. }
  22892. return null;
  22893. };
  22894. /**
  22895. * get a material using its id
  22896. * @param {string} the material's ID
  22897. * @return {BABYLON.Material|null} the material or null if none found.
  22898. */
  22899. Scene.prototype.getMaterialByID = function (id) {
  22900. for (var index = 0; index < this.materials.length; index++) {
  22901. if (this.materials[index].id === id) {
  22902. return this.materials[index];
  22903. }
  22904. }
  22905. return null;
  22906. };
  22907. /**
  22908. * get a material using its name
  22909. * @param {string} the material's name
  22910. * @return {BABYLON.Material|null} the material or null if none found.
  22911. */
  22912. Scene.prototype.getMaterialByName = function (name) {
  22913. for (var index = 0; index < this.materials.length; index++) {
  22914. if (this.materials[index].name === name) {
  22915. return this.materials[index];
  22916. }
  22917. }
  22918. return null;
  22919. };
  22920. Scene.prototype.getLensFlareSystemByName = function (name) {
  22921. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22922. if (this.lensFlareSystems[index].name === name) {
  22923. return this.lensFlareSystems[index];
  22924. }
  22925. }
  22926. return null;
  22927. };
  22928. Scene.prototype.getLensFlareSystemByID = function (id) {
  22929. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22930. if (this.lensFlareSystems[index].id === id) {
  22931. return this.lensFlareSystems[index];
  22932. }
  22933. }
  22934. return null;
  22935. };
  22936. Scene.prototype.getCameraByID = function (id) {
  22937. for (var index = 0; index < this.cameras.length; index++) {
  22938. if (this.cameras[index].id === id) {
  22939. return this.cameras[index];
  22940. }
  22941. }
  22942. return null;
  22943. };
  22944. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22945. for (var index = 0; index < this.cameras.length; index++) {
  22946. if (this.cameras[index].uniqueId === uniqueId) {
  22947. return this.cameras[index];
  22948. }
  22949. }
  22950. return null;
  22951. };
  22952. /**
  22953. * get a camera using its name
  22954. * @param {string} the camera's name
  22955. * @return {BABYLON.Camera|null} the camera or null if none found.
  22956. */
  22957. Scene.prototype.getCameraByName = function (name) {
  22958. for (var index = 0; index < this.cameras.length; index++) {
  22959. if (this.cameras[index].name === name) {
  22960. return this.cameras[index];
  22961. }
  22962. }
  22963. return null;
  22964. };
  22965. /**
  22966. * get a bone using its id
  22967. * @param {string} the bone's id
  22968. * @return {BABYLON.Bone|null} the bone or null if not found
  22969. */
  22970. Scene.prototype.getBoneByID = function (id) {
  22971. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22972. var skeleton = this.skeletons[skeletonIndex];
  22973. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22974. if (skeleton.bones[boneIndex].id === id) {
  22975. return skeleton.bones[boneIndex];
  22976. }
  22977. }
  22978. }
  22979. return null;
  22980. };
  22981. /**
  22982. * get a bone using its id
  22983. * @param {string} the bone's name
  22984. * @return {BABYLON.Bone|null} the bone or null if not found
  22985. */
  22986. Scene.prototype.getBoneByName = function (name) {
  22987. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22988. var skeleton = this.skeletons[skeletonIndex];
  22989. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22990. if (skeleton.bones[boneIndex].name === name) {
  22991. return skeleton.bones[boneIndex];
  22992. }
  22993. }
  22994. }
  22995. return null;
  22996. };
  22997. /**
  22998. * get a light node using its name
  22999. * @param {string} the light's name
  23000. * @return {BABYLON.Light|null} the light or null if none found.
  23001. */
  23002. Scene.prototype.getLightByName = function (name) {
  23003. for (var index = 0; index < this.lights.length; index++) {
  23004. if (this.lights[index].name === name) {
  23005. return this.lights[index];
  23006. }
  23007. }
  23008. return null;
  23009. };
  23010. /**
  23011. * get a light node using its ID
  23012. * @param {string} the light's id
  23013. * @return {BABYLON.Light|null} the light or null if none found.
  23014. */
  23015. Scene.prototype.getLightByID = function (id) {
  23016. for (var index = 0; index < this.lights.length; index++) {
  23017. if (this.lights[index].id === id) {
  23018. return this.lights[index];
  23019. }
  23020. }
  23021. return null;
  23022. };
  23023. /**
  23024. * get a light node using its scene-generated unique ID
  23025. * @param {number} the light's unique id
  23026. * @return {BABYLON.Light|null} the light or null if none found.
  23027. */
  23028. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23029. for (var index = 0; index < this.lights.length; index++) {
  23030. if (this.lights[index].uniqueId === uniqueId) {
  23031. return this.lights[index];
  23032. }
  23033. }
  23034. return null;
  23035. };
  23036. /**
  23037. * get a particle system by id
  23038. * @param id {number} the particle system id
  23039. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23040. */
  23041. Scene.prototype.getParticleSystemByID = function (id) {
  23042. for (var index = 0; index < this.particleSystems.length; index++) {
  23043. if (this.particleSystems[index].id === id) {
  23044. return this.particleSystems[index];
  23045. }
  23046. }
  23047. return null;
  23048. };
  23049. /**
  23050. * get a geometry using its ID
  23051. * @param {string} the geometry's id
  23052. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23053. */
  23054. Scene.prototype.getGeometryByID = function (id) {
  23055. for (var index = 0; index < this._geometries.length; index++) {
  23056. if (this._geometries[index].id === id) {
  23057. return this._geometries[index];
  23058. }
  23059. }
  23060. return null;
  23061. };
  23062. /**
  23063. * add a new geometry to this scene.
  23064. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23065. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23066. * @return {boolean} was the geometry added or not
  23067. */
  23068. Scene.prototype.pushGeometry = function (geometry, force) {
  23069. if (!force && this.getGeometryByID(geometry.id)) {
  23070. return false;
  23071. }
  23072. this._geometries.push(geometry);
  23073. //notify the collision coordinator
  23074. if (this.collisionCoordinator) {
  23075. this.collisionCoordinator.onGeometryAdded(geometry);
  23076. }
  23077. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23078. return true;
  23079. };
  23080. /**
  23081. * Removes an existing geometry
  23082. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23083. * @return {boolean} was the geometry removed or not
  23084. */
  23085. Scene.prototype.removeGeometry = function (geometry) {
  23086. var index = this._geometries.indexOf(geometry);
  23087. if (index > -1) {
  23088. this._geometries.splice(index, 1);
  23089. //notify the collision coordinator
  23090. if (this.collisionCoordinator) {
  23091. this.collisionCoordinator.onGeometryDeleted(geometry);
  23092. }
  23093. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23094. return true;
  23095. }
  23096. return false;
  23097. };
  23098. Scene.prototype.getGeometries = function () {
  23099. return this._geometries;
  23100. };
  23101. /**
  23102. * Get the first added mesh found of a given ID
  23103. * @param {string} id - the id to search for
  23104. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23105. */
  23106. Scene.prototype.getMeshByID = function (id) {
  23107. for (var index = 0; index < this.meshes.length; index++) {
  23108. if (this.meshes[index].id === id) {
  23109. return this.meshes[index];
  23110. }
  23111. }
  23112. return null;
  23113. };
  23114. Scene.prototype.getMeshesByID = function (id) {
  23115. return this.meshes.filter(function (m) {
  23116. return m.id === id;
  23117. });
  23118. };
  23119. /**
  23120. * Get the first added transform node found of a given ID
  23121. * @param {string} id - the id to search for
  23122. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23123. */
  23124. Scene.prototype.getTransformNodeByID = function (id) {
  23125. for (var index = 0; index < this.transformNodes.length; index++) {
  23126. if (this.transformNodes[index].id === id) {
  23127. return this.transformNodes[index];
  23128. }
  23129. }
  23130. return null;
  23131. };
  23132. Scene.prototype.getTransformNodesByID = function (id) {
  23133. return this.transformNodes.filter(function (m) {
  23134. return m.id === id;
  23135. });
  23136. };
  23137. /**
  23138. * Get a mesh with its auto-generated unique id
  23139. * @param {number} uniqueId - the unique id to search for
  23140. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23141. */
  23142. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23143. for (var index = 0; index < this.meshes.length; index++) {
  23144. if (this.meshes[index].uniqueId === uniqueId) {
  23145. return this.meshes[index];
  23146. }
  23147. }
  23148. return null;
  23149. };
  23150. /**
  23151. * Get a the last added mesh found of a given ID
  23152. * @param {string} id - the id to search for
  23153. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23154. */
  23155. Scene.prototype.getLastMeshByID = function (id) {
  23156. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23157. if (this.meshes[index].id === id) {
  23158. return this.meshes[index];
  23159. }
  23160. }
  23161. return null;
  23162. };
  23163. /**
  23164. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23165. * @param {string} id - the id to search for
  23166. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23167. */
  23168. Scene.prototype.getLastEntryByID = function (id) {
  23169. var index;
  23170. for (index = this.meshes.length - 1; index >= 0; index--) {
  23171. if (this.meshes[index].id === id) {
  23172. return this.meshes[index];
  23173. }
  23174. }
  23175. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23176. if (this.transformNodes[index].id === id) {
  23177. return this.transformNodes[index];
  23178. }
  23179. }
  23180. for (index = this.cameras.length - 1; index >= 0; index--) {
  23181. if (this.cameras[index].id === id) {
  23182. return this.cameras[index];
  23183. }
  23184. }
  23185. for (index = this.lights.length - 1; index >= 0; index--) {
  23186. if (this.lights[index].id === id) {
  23187. return this.lights[index];
  23188. }
  23189. }
  23190. return null;
  23191. };
  23192. Scene.prototype.getNodeByID = function (id) {
  23193. var mesh = this.getMeshByID(id);
  23194. if (mesh) {
  23195. return mesh;
  23196. }
  23197. var light = this.getLightByID(id);
  23198. if (light) {
  23199. return light;
  23200. }
  23201. var camera = this.getCameraByID(id);
  23202. if (camera) {
  23203. return camera;
  23204. }
  23205. var bone = this.getBoneByID(id);
  23206. return bone;
  23207. };
  23208. Scene.prototype.getNodeByName = function (name) {
  23209. var mesh = this.getMeshByName(name);
  23210. if (mesh) {
  23211. return mesh;
  23212. }
  23213. var light = this.getLightByName(name);
  23214. if (light) {
  23215. return light;
  23216. }
  23217. var camera = this.getCameraByName(name);
  23218. if (camera) {
  23219. return camera;
  23220. }
  23221. var bone = this.getBoneByName(name);
  23222. return bone;
  23223. };
  23224. Scene.prototype.getMeshByName = function (name) {
  23225. for (var index = 0; index < this.meshes.length; index++) {
  23226. if (this.meshes[index].name === name) {
  23227. return this.meshes[index];
  23228. }
  23229. }
  23230. return null;
  23231. };
  23232. Scene.prototype.getTransformNodeByName = function (name) {
  23233. for (var index = 0; index < this.transformNodes.length; index++) {
  23234. if (this.transformNodes[index].name === name) {
  23235. return this.transformNodes[index];
  23236. }
  23237. }
  23238. return null;
  23239. };
  23240. Scene.prototype.getSoundByName = function (name) {
  23241. var index;
  23242. if (BABYLON.AudioEngine) {
  23243. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23244. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23245. return this.mainSoundTrack.soundCollection[index];
  23246. }
  23247. }
  23248. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23249. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23250. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23251. return this.soundTracks[sdIndex].soundCollection[index];
  23252. }
  23253. }
  23254. }
  23255. }
  23256. return null;
  23257. };
  23258. Scene.prototype.getLastSkeletonByID = function (id) {
  23259. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23260. if (this.skeletons[index].id === id) {
  23261. return this.skeletons[index];
  23262. }
  23263. }
  23264. return null;
  23265. };
  23266. Scene.prototype.getSkeletonById = function (id) {
  23267. for (var index = 0; index < this.skeletons.length; index++) {
  23268. if (this.skeletons[index].id === id) {
  23269. return this.skeletons[index];
  23270. }
  23271. }
  23272. return null;
  23273. };
  23274. Scene.prototype.getSkeletonByName = function (name) {
  23275. for (var index = 0; index < this.skeletons.length; index++) {
  23276. if (this.skeletons[index].name === name) {
  23277. return this.skeletons[index];
  23278. }
  23279. }
  23280. return null;
  23281. };
  23282. Scene.prototype.getMorphTargetManagerById = function (id) {
  23283. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23284. if (this.morphTargetManagers[index].uniqueId === id) {
  23285. return this.morphTargetManagers[index];
  23286. }
  23287. }
  23288. return null;
  23289. };
  23290. Scene.prototype.isActiveMesh = function (mesh) {
  23291. return (this._activeMeshes.indexOf(mesh) !== -1);
  23292. };
  23293. /**
  23294. * Return a the first highlight layer of the scene with a given name.
  23295. * @param name The name of the highlight layer to look for.
  23296. * @return The highlight layer if found otherwise null.
  23297. */
  23298. Scene.prototype.getHighlightLayerByName = function (name) {
  23299. for (var index = 0; index < this.effectLayers.length; index++) {
  23300. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23301. return this.effectLayers[index];
  23302. }
  23303. }
  23304. return null;
  23305. };
  23306. /**
  23307. * Return a the first highlight layer of the scene with a given name.
  23308. * @param name The name of the highlight layer to look for.
  23309. * @return The highlight layer if found otherwise null.
  23310. */
  23311. Scene.prototype.getGlowLayerByName = function (name) {
  23312. for (var index = 0; index < this.effectLayers.length; index++) {
  23313. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23314. return this.effectLayers[index];
  23315. }
  23316. }
  23317. return null;
  23318. };
  23319. Object.defineProperty(Scene.prototype, "uid", {
  23320. /**
  23321. * Return a unique id as a string which can serve as an identifier for the scene
  23322. */
  23323. get: function () {
  23324. if (!this._uid) {
  23325. this._uid = BABYLON.Tools.RandomId();
  23326. }
  23327. return this._uid;
  23328. },
  23329. enumerable: true,
  23330. configurable: true
  23331. });
  23332. /**
  23333. * Add an externaly attached data from its key.
  23334. * This method call will fail and return false, if such key already exists.
  23335. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23336. * @param key the unique key that identifies the data
  23337. * @param data the data object to associate to the key for this Engine instance
  23338. * @return true if no such key were already present and the data was added successfully, false otherwise
  23339. */
  23340. Scene.prototype.addExternalData = function (key, data) {
  23341. if (!this._externalData) {
  23342. this._externalData = new BABYLON.StringDictionary();
  23343. }
  23344. return this._externalData.add(key, data);
  23345. };
  23346. /**
  23347. * Get an externaly attached data from its key
  23348. * @param key the unique key that identifies the data
  23349. * @return the associated data, if present (can be null), or undefined if not present
  23350. */
  23351. Scene.prototype.getExternalData = function (key) {
  23352. if (!this._externalData) {
  23353. return null;
  23354. }
  23355. return this._externalData.get(key);
  23356. };
  23357. /**
  23358. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23359. * @param key the unique key that identifies the data
  23360. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23361. * @return the associated data, can be null if the factory returned null.
  23362. */
  23363. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23364. if (!this._externalData) {
  23365. this._externalData = new BABYLON.StringDictionary();
  23366. }
  23367. return this._externalData.getOrAddWithFactory(key, factory);
  23368. };
  23369. /**
  23370. * Remove an externaly attached data from the Engine instance
  23371. * @param key the unique key that identifies the data
  23372. * @return true if the data was successfully removed, false if it doesn't exist
  23373. */
  23374. Scene.prototype.removeExternalData = function (key) {
  23375. return this._externalData.remove(key);
  23376. };
  23377. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23378. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23379. if (mesh.showSubMeshesBoundingBox) {
  23380. var boundingInfo = subMesh.getBoundingInfo();
  23381. if (boundingInfo !== null && boundingInfo !== undefined) {
  23382. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23383. }
  23384. }
  23385. var material = subMesh.getMaterial();
  23386. if (material !== null && material !== undefined) {
  23387. // Render targets
  23388. if (material.getRenderTargetTextures !== undefined) {
  23389. if (this._processedMaterials.indexOf(material) === -1) {
  23390. this._processedMaterials.push(material);
  23391. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23392. }
  23393. }
  23394. // Dispatch
  23395. this._activeIndices.addCount(subMesh.indexCount, false);
  23396. this._renderingManager.dispatch(subMesh, mesh, material);
  23397. }
  23398. }
  23399. };
  23400. Scene.prototype._isInIntermediateRendering = function () {
  23401. return this._intermediateRendering;
  23402. };
  23403. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23404. this._activeMeshCandidateProvider = provider;
  23405. };
  23406. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23407. return this._activeMeshCandidateProvider;
  23408. };
  23409. /**
  23410. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23411. */
  23412. Scene.prototype.freezeActiveMeshes = function () {
  23413. this._evaluateActiveMeshes();
  23414. this._activeMeshesFrozen = true;
  23415. return this;
  23416. };
  23417. /**
  23418. * Use this function to restart evaluating active meshes on every frame
  23419. */
  23420. Scene.prototype.unfreezeActiveMeshes = function () {
  23421. this._activeMeshesFrozen = false;
  23422. return this;
  23423. };
  23424. Scene.prototype._evaluateActiveMeshes = function () {
  23425. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23426. return;
  23427. }
  23428. if (!this.activeCamera) {
  23429. return;
  23430. }
  23431. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23432. this.activeCamera._activeMeshes.reset();
  23433. this._activeMeshes.reset();
  23434. this._renderingManager.reset();
  23435. this._processedMaterials.reset();
  23436. this._activeParticleSystems.reset();
  23437. this._activeSkeletons.reset();
  23438. this._softwareSkinnedMeshes.reset();
  23439. if (this._boundingBoxRenderer) {
  23440. this._boundingBoxRenderer.reset();
  23441. }
  23442. // Meshes
  23443. var meshes;
  23444. var len;
  23445. var checkIsEnabled = true;
  23446. // Determine mesh candidates
  23447. if (this._activeMeshCandidateProvider !== undefined) {
  23448. // Use _activeMeshCandidateProvider
  23449. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23450. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23451. if (meshes !== undefined) {
  23452. len = meshes.length;
  23453. }
  23454. else {
  23455. len = 0;
  23456. }
  23457. }
  23458. else if (this._selectionOctree !== undefined) {
  23459. // Octree
  23460. var selection = this._selectionOctree.select(this._frustumPlanes);
  23461. meshes = selection.data;
  23462. len = selection.length;
  23463. }
  23464. else {
  23465. // Full scene traversal
  23466. len = this.meshes.length;
  23467. meshes = this.meshes;
  23468. }
  23469. // Check each mesh
  23470. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23471. mesh = meshes[meshIndex];
  23472. if (mesh.isBlocked) {
  23473. continue;
  23474. }
  23475. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23476. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23477. continue;
  23478. }
  23479. mesh.computeWorldMatrix();
  23480. // Intersections
  23481. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23482. this._meshesForIntersections.pushNoDuplicate(mesh);
  23483. }
  23484. // Switch to current LOD
  23485. meshLOD = mesh.getLOD(this.activeCamera);
  23486. if (meshLOD === undefined || meshLOD === null) {
  23487. continue;
  23488. }
  23489. mesh._preActivate();
  23490. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23491. this._activeMeshes.push(mesh);
  23492. this.activeCamera._activeMeshes.push(mesh);
  23493. mesh._activate(this._renderId);
  23494. if (meshLOD !== mesh) {
  23495. meshLOD._activate(this._renderId);
  23496. }
  23497. this._activeMesh(mesh, meshLOD);
  23498. }
  23499. }
  23500. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23501. // Particle systems
  23502. if (this.particlesEnabled) {
  23503. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23504. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23505. var particleSystem = this.particleSystems[particleIndex];
  23506. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23507. continue;
  23508. }
  23509. var emitter = particleSystem.emitter;
  23510. if (!emitter.position || emitter.isEnabled()) {
  23511. this._activeParticleSystems.push(particleSystem);
  23512. particleSystem.animate();
  23513. this._renderingManager.dispatchParticles(particleSystem);
  23514. }
  23515. }
  23516. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23517. }
  23518. };
  23519. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23520. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23521. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23522. mesh.skeleton.prepare();
  23523. }
  23524. if (!mesh.computeBonesUsingShaders) {
  23525. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23526. }
  23527. }
  23528. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23529. var boundingInfo = sourceMesh.getBoundingInfo();
  23530. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23531. }
  23532. if (mesh !== undefined && mesh !== null
  23533. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23534. // Submeshes Octrees
  23535. var len;
  23536. var subMeshes;
  23537. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23538. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23539. len = intersections.length;
  23540. subMeshes = intersections.data;
  23541. }
  23542. else {
  23543. subMeshes = mesh.subMeshes;
  23544. len = subMeshes.length;
  23545. }
  23546. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23547. subMesh = subMeshes[subIndex];
  23548. this._evaluateSubMesh(subMesh, mesh);
  23549. }
  23550. }
  23551. };
  23552. Scene.prototype.updateTransformMatrix = function (force) {
  23553. if (!this.activeCamera) {
  23554. return;
  23555. }
  23556. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23557. };
  23558. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23559. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23560. };
  23561. Scene.prototype._renderForCamera = function (camera) {
  23562. if (camera && camera._skipRendering) {
  23563. return;
  23564. }
  23565. var engine = this._engine;
  23566. this.activeCamera = camera;
  23567. if (!this.activeCamera)
  23568. throw new Error("Active camera not set");
  23569. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23570. // Viewport
  23571. engine.setViewport(this.activeCamera.viewport);
  23572. // Camera
  23573. this.resetCachedMaterial();
  23574. this._renderId++;
  23575. this.activeCamera.update();
  23576. this.updateTransformMatrix();
  23577. if (camera._alternateCamera) {
  23578. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23579. this._alternateRendering = true;
  23580. }
  23581. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23582. // Meshes
  23583. this._evaluateActiveMeshes();
  23584. // Software skinning
  23585. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23586. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23587. mesh.applySkeleton(mesh.skeleton);
  23588. }
  23589. // Render targets
  23590. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23591. var needsRestoreFrameBuffer = false;
  23592. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23593. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23594. }
  23595. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23596. this._intermediateRendering = true;
  23597. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23598. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23599. var renderTarget = this._renderTargets.data[renderIndex];
  23600. if (renderTarget._shouldRender()) {
  23601. this._renderId++;
  23602. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23603. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23604. }
  23605. }
  23606. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23607. this._intermediateRendering = false;
  23608. this._renderId++;
  23609. needsRestoreFrameBuffer = true; // Restore back buffer
  23610. }
  23611. // Render EffecttLayer Texture
  23612. var stencilState = this._engine.getStencilBuffer();
  23613. var renderEffects = false;
  23614. var needStencil = false;
  23615. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23616. this._intermediateRendering = true;
  23617. for (var i = 0; i < this.effectLayers.length; i++) {
  23618. var effectLayer = this.effectLayers[i];
  23619. if (effectLayer.shouldRender() &&
  23620. (!effectLayer.camera ||
  23621. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23622. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23623. renderEffects = true;
  23624. needStencil = needStencil || effectLayer.needStencil();
  23625. var renderTarget = effectLayer._mainTexture;
  23626. if (renderTarget._shouldRender()) {
  23627. this._renderId++;
  23628. renderTarget.render(false, false);
  23629. needsRestoreFrameBuffer = true;
  23630. }
  23631. }
  23632. }
  23633. this._intermediateRendering = false;
  23634. this._renderId++;
  23635. }
  23636. if (needsRestoreFrameBuffer) {
  23637. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23638. }
  23639. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23640. // Prepare Frame
  23641. this.postProcessManager._prepareFrame();
  23642. // Backgrounds
  23643. var layerIndex;
  23644. var layer;
  23645. if (this.layers.length) {
  23646. engine.setDepthBuffer(false);
  23647. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23648. layer = this.layers[layerIndex];
  23649. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23650. layer.render();
  23651. }
  23652. }
  23653. engine.setDepthBuffer(true);
  23654. }
  23655. // Activate effect Layer stencil
  23656. if (needStencil) {
  23657. this._engine.setStencilBuffer(true);
  23658. }
  23659. // Render
  23660. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23661. this._renderingManager.render(null, null, true, true);
  23662. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23663. // Restore effect Layer stencil
  23664. if (needStencil) {
  23665. this._engine.setStencilBuffer(stencilState);
  23666. }
  23667. // Bounding boxes
  23668. if (this._boundingBoxRenderer) {
  23669. this._boundingBoxRenderer.render();
  23670. }
  23671. // Lens flares
  23672. if (this.lensFlaresEnabled) {
  23673. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23674. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23675. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23676. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23677. lensFlareSystem.render();
  23678. }
  23679. }
  23680. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23681. }
  23682. // Foregrounds
  23683. if (this.layers.length) {
  23684. engine.setDepthBuffer(false);
  23685. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23686. layer = this.layers[layerIndex];
  23687. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23688. layer.render();
  23689. }
  23690. }
  23691. engine.setDepthBuffer(true);
  23692. }
  23693. // Effect Layer
  23694. if (renderEffects) {
  23695. engine.setDepthBuffer(false);
  23696. for (var i = 0; i < this.effectLayers.length; i++) {
  23697. if (this.effectLayers[i].shouldRender()) {
  23698. this.effectLayers[i].render();
  23699. }
  23700. }
  23701. engine.setDepthBuffer(true);
  23702. }
  23703. // Finalize frame
  23704. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23705. // Reset some special arrays
  23706. this._renderTargets.reset();
  23707. this._alternateRendering = false;
  23708. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23709. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23710. };
  23711. Scene.prototype._processSubCameras = function (camera) {
  23712. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23713. this._renderForCamera(camera);
  23714. return;
  23715. }
  23716. // Update camera
  23717. if (this.activeCamera) {
  23718. this.activeCamera.update();
  23719. }
  23720. // rig cameras
  23721. for (var index = 0; index < camera._rigCameras.length; index++) {
  23722. this._renderForCamera(camera._rigCameras[index]);
  23723. }
  23724. this.activeCamera = camera;
  23725. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23726. };
  23727. Scene.prototype._checkIntersections = function () {
  23728. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23729. var sourceMesh = this._meshesForIntersections.data[index];
  23730. if (!sourceMesh.actionManager) {
  23731. continue;
  23732. }
  23733. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23734. var action = sourceMesh.actionManager.actions[actionIndex];
  23735. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23736. var parameters = action.getTriggerParameter();
  23737. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23738. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23739. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23740. if (areIntersecting && currentIntersectionInProgress === -1) {
  23741. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23742. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23743. sourceMesh._intersectionsInProgress.push(otherMesh);
  23744. }
  23745. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23746. sourceMesh._intersectionsInProgress.push(otherMesh);
  23747. }
  23748. }
  23749. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23750. //They intersected, and now they don't.
  23751. //is this trigger an exit trigger? execute an event.
  23752. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23753. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23754. }
  23755. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23756. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23757. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23758. }
  23759. }
  23760. }
  23761. }
  23762. }
  23763. };
  23764. Scene.prototype.render = function () {
  23765. if (this.isDisposed) {
  23766. return;
  23767. }
  23768. this._activeParticles.fetchNewFrame();
  23769. this._totalVertices.fetchNewFrame();
  23770. this._activeIndices.fetchNewFrame();
  23771. this._activeBones.fetchNewFrame();
  23772. this._meshesForIntersections.reset();
  23773. this.resetCachedMaterial();
  23774. this.onBeforeAnimationsObservable.notifyObservers(this);
  23775. // Actions
  23776. if (this.actionManager) {
  23777. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23778. }
  23779. //Simplification Queue
  23780. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23781. this.simplificationQueue.executeNext();
  23782. }
  23783. if (this._engine.isDeterministicLockStep()) {
  23784. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23785. var defaultFPS = (60.0 / 1000.0);
  23786. var defaultFrameTime = 1000 / 60; // frame time in MS
  23787. if (this._physicsEngine) {
  23788. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23789. }
  23790. var stepsTaken = 0;
  23791. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23792. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23793. internalSteps = Math.min(internalSteps, maxSubSteps);
  23794. do {
  23795. this.onBeforeStepObservable.notifyObservers(this);
  23796. // Animations
  23797. this._animationRatio = defaultFrameTime * defaultFPS;
  23798. this._animate();
  23799. this.onAfterAnimationsObservable.notifyObservers(this);
  23800. // Physics
  23801. if (this._physicsEngine) {
  23802. this.onBeforePhysicsObservable.notifyObservers(this);
  23803. this._physicsEngine._step(defaultFrameTime / 1000);
  23804. this.onAfterPhysicsObservable.notifyObservers(this);
  23805. }
  23806. this.onAfterStepObservable.notifyObservers(this);
  23807. this._currentStepId++;
  23808. stepsTaken++;
  23809. deltaTime -= defaultFrameTime;
  23810. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23811. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23812. }
  23813. else {
  23814. // Animations
  23815. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23816. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23817. this._animate();
  23818. this.onAfterAnimationsObservable.notifyObservers(this);
  23819. // Physics
  23820. if (this._physicsEngine) {
  23821. this.onBeforePhysicsObservable.notifyObservers(this);
  23822. this._physicsEngine._step(deltaTime / 1000.0);
  23823. this.onAfterPhysicsObservable.notifyObservers(this);
  23824. }
  23825. }
  23826. // update gamepad manager
  23827. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23828. this._gamepadManager._checkGamepadsStatus();
  23829. }
  23830. // Before render
  23831. this.onBeforeRenderObservable.notifyObservers(this);
  23832. // Customs render targets
  23833. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23834. var engine = this.getEngine();
  23835. var currentActiveCamera = this.activeCamera;
  23836. if (this.renderTargetsEnabled) {
  23837. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23838. this._intermediateRendering = true;
  23839. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23840. var renderTarget = this.customRenderTargets[customIndex];
  23841. if (renderTarget._shouldRender()) {
  23842. this._renderId++;
  23843. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23844. if (!this.activeCamera)
  23845. throw new Error("Active camera not set");
  23846. // Viewport
  23847. engine.setViewport(this.activeCamera.viewport);
  23848. // Camera
  23849. this.updateTransformMatrix();
  23850. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23851. }
  23852. }
  23853. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23854. this._intermediateRendering = false;
  23855. this._renderId++;
  23856. }
  23857. // Restore back buffer
  23858. if (this.customRenderTargets.length > 0) {
  23859. engine.restoreDefaultFramebuffer();
  23860. }
  23861. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23862. this.activeCamera = currentActiveCamera;
  23863. // Procedural textures
  23864. if (this.proceduralTexturesEnabled) {
  23865. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23866. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23867. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23868. if (proceduralTexture._shouldRender()) {
  23869. proceduralTexture.render();
  23870. }
  23871. }
  23872. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23873. }
  23874. // Clear
  23875. if (this.autoClearDepthAndStencil || this.autoClear) {
  23876. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23877. }
  23878. // Shadows
  23879. if (this.shadowsEnabled) {
  23880. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23881. var light = this.lights[lightIndex];
  23882. var shadowGenerator = light.getShadowGenerator();
  23883. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23884. var shadowMap = (shadowGenerator.getShadowMap());
  23885. if (this.textures.indexOf(shadowMap) !== -1) {
  23886. this._renderTargets.push(shadowMap);
  23887. }
  23888. }
  23889. }
  23890. }
  23891. // Depth renderer
  23892. if (this._depthRenderer) {
  23893. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23894. }
  23895. // Geometry renderer
  23896. if (this._geometryBufferRenderer) {
  23897. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23898. }
  23899. // RenderPipeline
  23900. if (this._postProcessRenderPipelineManager) {
  23901. this._postProcessRenderPipelineManager.update();
  23902. }
  23903. // Multi-cameras?
  23904. if (this.activeCameras.length > 0) {
  23905. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23906. if (cameraIndex > 0) {
  23907. this._engine.clear(null, false, true, true);
  23908. }
  23909. this._processSubCameras(this.activeCameras[cameraIndex]);
  23910. }
  23911. }
  23912. else {
  23913. if (!this.activeCamera) {
  23914. throw new Error("No camera defined");
  23915. }
  23916. this._processSubCameras(this.activeCamera);
  23917. }
  23918. // Intersection checks
  23919. this._checkIntersections();
  23920. // Update the audio listener attached to the camera
  23921. if (BABYLON.AudioEngine) {
  23922. this._updateAudioParameters();
  23923. }
  23924. // After render
  23925. if (this.afterRender) {
  23926. this.afterRender();
  23927. }
  23928. this.onAfterRenderObservable.notifyObservers(this);
  23929. // Cleaning
  23930. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23931. var data = this._toBeDisposed.data[index];
  23932. if (data) {
  23933. data.dispose();
  23934. }
  23935. this._toBeDisposed[index] = null;
  23936. }
  23937. this._toBeDisposed.reset();
  23938. if (this.dumpNextRenderTargets) {
  23939. this.dumpNextRenderTargets = false;
  23940. }
  23941. this._activeBones.addCount(0, true);
  23942. this._activeIndices.addCount(0, true);
  23943. this._activeParticles.addCount(0, true);
  23944. };
  23945. Scene.prototype._updateAudioParameters = function () {
  23946. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23947. return;
  23948. }
  23949. var listeningCamera;
  23950. var audioEngine = BABYLON.Engine.audioEngine;
  23951. if (this.activeCameras.length > 0) {
  23952. listeningCamera = this.activeCameras[0];
  23953. }
  23954. else {
  23955. listeningCamera = this.activeCamera;
  23956. }
  23957. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23958. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23959. // for VR cameras
  23960. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23961. listeningCamera = listeningCamera.rigCameras[0];
  23962. }
  23963. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23964. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23965. cameraDirection.normalize();
  23966. // To avoid some errors on GearVR
  23967. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23968. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23969. }
  23970. var i;
  23971. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23972. var sound = this.mainSoundTrack.soundCollection[i];
  23973. if (sound.useCustomAttenuation) {
  23974. sound.updateDistanceFromListener();
  23975. }
  23976. }
  23977. for (i = 0; i < this.soundTracks.length; i++) {
  23978. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23979. sound = this.soundTracks[i].soundCollection[j];
  23980. if (sound.useCustomAttenuation) {
  23981. sound.updateDistanceFromListener();
  23982. }
  23983. }
  23984. }
  23985. }
  23986. };
  23987. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23988. // Audio
  23989. get: function () {
  23990. return this._audioEnabled;
  23991. },
  23992. set: function (value) {
  23993. this._audioEnabled = value;
  23994. if (BABYLON.AudioEngine) {
  23995. if (this._audioEnabled) {
  23996. this._enableAudio();
  23997. }
  23998. else {
  23999. this._disableAudio();
  24000. }
  24001. }
  24002. },
  24003. enumerable: true,
  24004. configurable: true
  24005. });
  24006. Scene.prototype._disableAudio = function () {
  24007. var i;
  24008. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24009. this.mainSoundTrack.soundCollection[i].pause();
  24010. }
  24011. for (i = 0; i < this.soundTracks.length; i++) {
  24012. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24013. this.soundTracks[i].soundCollection[j].pause();
  24014. }
  24015. }
  24016. };
  24017. Scene.prototype._enableAudio = function () {
  24018. var i;
  24019. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24020. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24021. this.mainSoundTrack.soundCollection[i].play();
  24022. }
  24023. }
  24024. for (i = 0; i < this.soundTracks.length; i++) {
  24025. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24026. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24027. this.soundTracks[i].soundCollection[j].play();
  24028. }
  24029. }
  24030. }
  24031. };
  24032. Object.defineProperty(Scene.prototype, "headphone", {
  24033. get: function () {
  24034. return this._headphone;
  24035. },
  24036. set: function (value) {
  24037. this._headphone = value;
  24038. if (BABYLON.AudioEngine) {
  24039. if (this._headphone) {
  24040. this._switchAudioModeForHeadphones();
  24041. }
  24042. else {
  24043. this._switchAudioModeForNormalSpeakers();
  24044. }
  24045. }
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. Scene.prototype._switchAudioModeForHeadphones = function () {
  24051. this.mainSoundTrack.switchPanningModelToHRTF();
  24052. for (var i = 0; i < this.soundTracks.length; i++) {
  24053. this.soundTracks[i].switchPanningModelToHRTF();
  24054. }
  24055. };
  24056. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24057. this.mainSoundTrack.switchPanningModelToEqualPower();
  24058. for (var i = 0; i < this.soundTracks.length; i++) {
  24059. this.soundTracks[i].switchPanningModelToEqualPower();
  24060. }
  24061. };
  24062. Scene.prototype.enableDepthRenderer = function () {
  24063. if (this._depthRenderer) {
  24064. return this._depthRenderer;
  24065. }
  24066. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24067. return this._depthRenderer;
  24068. };
  24069. Scene.prototype.disableDepthRenderer = function () {
  24070. if (!this._depthRenderer) {
  24071. return;
  24072. }
  24073. this._depthRenderer.dispose();
  24074. this._depthRenderer = null;
  24075. };
  24076. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24077. if (ratio === void 0) { ratio = 1; }
  24078. if (this._geometryBufferRenderer) {
  24079. return this._geometryBufferRenderer;
  24080. }
  24081. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24082. if (!this._geometryBufferRenderer.isSupported) {
  24083. this._geometryBufferRenderer = null;
  24084. }
  24085. return this._geometryBufferRenderer;
  24086. };
  24087. Scene.prototype.disableGeometryBufferRenderer = function () {
  24088. if (!this._geometryBufferRenderer) {
  24089. return;
  24090. }
  24091. this._geometryBufferRenderer.dispose();
  24092. this._geometryBufferRenderer = null;
  24093. };
  24094. Scene.prototype.freezeMaterials = function () {
  24095. for (var i = 0; i < this.materials.length; i++) {
  24096. this.materials[i].freeze();
  24097. }
  24098. };
  24099. Scene.prototype.unfreezeMaterials = function () {
  24100. for (var i = 0; i < this.materials.length; i++) {
  24101. this.materials[i].unfreeze();
  24102. }
  24103. };
  24104. Scene.prototype.dispose = function () {
  24105. this.beforeRender = null;
  24106. this.afterRender = null;
  24107. this.skeletons = [];
  24108. this.morphTargetManagers = [];
  24109. this.importedMeshesFiles = new Array();
  24110. this.stopAllAnimations();
  24111. this.resetCachedMaterial();
  24112. if (this._depthRenderer) {
  24113. this._depthRenderer.dispose();
  24114. }
  24115. if (this._gamepadManager) {
  24116. this._gamepadManager.dispose();
  24117. this._gamepadManager = null;
  24118. }
  24119. // Smart arrays
  24120. if (this.activeCamera) {
  24121. this.activeCamera._activeMeshes.dispose();
  24122. this.activeCamera = null;
  24123. }
  24124. this._activeMeshes.dispose();
  24125. this._renderingManager.dispose();
  24126. this._processedMaterials.dispose();
  24127. this._activeParticleSystems.dispose();
  24128. this._activeSkeletons.dispose();
  24129. this._softwareSkinnedMeshes.dispose();
  24130. this._renderTargets.dispose();
  24131. if (this._boundingBoxRenderer) {
  24132. this._boundingBoxRenderer.dispose();
  24133. }
  24134. this._meshesForIntersections.dispose();
  24135. this._toBeDisposed.dispose();
  24136. // Abort active requests
  24137. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24138. var request = _a[_i];
  24139. request.abort();
  24140. }
  24141. // Debug layer
  24142. if (this._debugLayer) {
  24143. this._debugLayer.hide();
  24144. }
  24145. // Events
  24146. this.onDisposeObservable.notifyObservers(this);
  24147. this.onDisposeObservable.clear();
  24148. this.onBeforeRenderObservable.clear();
  24149. this.onAfterRenderObservable.clear();
  24150. this.OnBeforeRenderTargetsRenderObservable.clear();
  24151. this.OnAfterRenderTargetsRenderObservable.clear();
  24152. this.onAfterStepObservable.clear();
  24153. this.onBeforeStepObservable.clear();
  24154. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24155. this.onAfterActiveMeshesEvaluationObservable.clear();
  24156. this.onBeforeParticlesRenderingObservable.clear();
  24157. this.onAfterParticlesRenderingObservable.clear();
  24158. this.onBeforeSpritesRenderingObservable.clear();
  24159. this.onAfterSpritesRenderingObservable.clear();
  24160. this.onBeforeDrawPhaseObservable.clear();
  24161. this.onAfterDrawPhaseObservable.clear();
  24162. this.onBeforePhysicsObservable.clear();
  24163. this.onAfterPhysicsObservable.clear();
  24164. this.onBeforeAnimationsObservable.clear();
  24165. this.onAfterAnimationsObservable.clear();
  24166. this.onDataLoadedObservable.clear();
  24167. this.detachControl();
  24168. // Release sounds & sounds tracks
  24169. if (BABYLON.AudioEngine) {
  24170. this.disposeSounds();
  24171. }
  24172. // VR Helper
  24173. if (this.VRHelper) {
  24174. this.VRHelper.dispose();
  24175. }
  24176. // Detach cameras
  24177. var canvas = this._engine.getRenderingCanvas();
  24178. if (canvas) {
  24179. var index;
  24180. for (index = 0; index < this.cameras.length; index++) {
  24181. this.cameras[index].detachControl(canvas);
  24182. }
  24183. }
  24184. // Release animation groups
  24185. while (this.animationGroups.length) {
  24186. this.animationGroups[0].dispose();
  24187. }
  24188. // Release lights
  24189. while (this.lights.length) {
  24190. this.lights[0].dispose();
  24191. }
  24192. // Release meshes
  24193. while (this.meshes.length) {
  24194. this.meshes[0].dispose(true);
  24195. }
  24196. while (this.transformNodes.length) {
  24197. this.removeTransformNode(this.transformNodes[0]);
  24198. }
  24199. // Release cameras
  24200. while (this.cameras.length) {
  24201. this.cameras[0].dispose();
  24202. }
  24203. // Release materials
  24204. if (this.defaultMaterial) {
  24205. this.defaultMaterial.dispose();
  24206. }
  24207. while (this.multiMaterials.length) {
  24208. this.multiMaterials[0].dispose();
  24209. }
  24210. while (this.materials.length) {
  24211. this.materials[0].dispose();
  24212. }
  24213. // Release particles
  24214. while (this.particleSystems.length) {
  24215. this.particleSystems[0].dispose();
  24216. }
  24217. // Release sprites
  24218. while (this.spriteManagers.length) {
  24219. this.spriteManagers[0].dispose();
  24220. }
  24221. // Release postProcesses
  24222. while (this.postProcesses.length) {
  24223. this.postProcesses[0].dispose();
  24224. }
  24225. // Release layers
  24226. while (this.layers.length) {
  24227. this.layers[0].dispose();
  24228. }
  24229. while (this.effectLayers.length) {
  24230. this.effectLayers[0].dispose();
  24231. }
  24232. // Release textures
  24233. while (this.textures.length) {
  24234. this.textures[0].dispose();
  24235. }
  24236. // Release UBO
  24237. this._sceneUbo.dispose();
  24238. if (this._alternateSceneUbo) {
  24239. this._alternateSceneUbo.dispose();
  24240. }
  24241. // Post-processes
  24242. this.postProcessManager.dispose();
  24243. if (this._postProcessRenderPipelineManager) {
  24244. this._postProcessRenderPipelineManager.dispose();
  24245. }
  24246. // Physics
  24247. if (this._physicsEngine) {
  24248. this.disablePhysicsEngine();
  24249. }
  24250. // Remove from engine
  24251. index = this._engine.scenes.indexOf(this);
  24252. if (index > -1) {
  24253. this._engine.scenes.splice(index, 1);
  24254. }
  24255. this._engine.wipeCaches(true);
  24256. this._isDisposed = true;
  24257. };
  24258. Object.defineProperty(Scene.prototype, "isDisposed", {
  24259. get: function () {
  24260. return this._isDisposed;
  24261. },
  24262. enumerable: true,
  24263. configurable: true
  24264. });
  24265. // Release sounds & sounds tracks
  24266. Scene.prototype.disposeSounds = function () {
  24267. if (!this._mainSoundTrack) {
  24268. return;
  24269. }
  24270. this.mainSoundTrack.dispose();
  24271. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24272. this.soundTracks[scIndex].dispose();
  24273. }
  24274. };
  24275. // Octrees
  24276. Scene.prototype.getWorldExtends = function () {
  24277. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24278. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24279. for (var index = 0; index < this.meshes.length; index++) {
  24280. var mesh = this.meshes[index];
  24281. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24282. continue;
  24283. }
  24284. mesh.computeWorldMatrix(true);
  24285. var boundingInfo = mesh.getBoundingInfo();
  24286. var minBox = boundingInfo.boundingBox.minimumWorld;
  24287. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24288. BABYLON.Tools.CheckExtends(minBox, min, max);
  24289. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24290. }
  24291. return {
  24292. min: min,
  24293. max: max
  24294. };
  24295. };
  24296. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24297. if (maxCapacity === void 0) { maxCapacity = 64; }
  24298. if (maxDepth === void 0) { maxDepth = 2; }
  24299. if (!this._selectionOctree) {
  24300. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24301. }
  24302. var worldExtends = this.getWorldExtends();
  24303. // Update octree
  24304. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24305. return this._selectionOctree;
  24306. };
  24307. // Picking
  24308. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24309. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24310. var result = BABYLON.Ray.Zero();
  24311. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24312. return result;
  24313. };
  24314. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24315. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24316. var engine = this._engine;
  24317. if (!camera) {
  24318. if (!this.activeCamera)
  24319. throw new Error("Active camera not set");
  24320. camera = this.activeCamera;
  24321. }
  24322. var cameraViewport = camera.viewport;
  24323. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24324. // Moving coordinates to local viewport world
  24325. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24326. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24327. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24328. return this;
  24329. };
  24330. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24331. var result = BABYLON.Ray.Zero();
  24332. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24333. return result;
  24334. };
  24335. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24336. if (!BABYLON.PickingInfo) {
  24337. return this;
  24338. }
  24339. var engine = this._engine;
  24340. if (!camera) {
  24341. if (!this.activeCamera)
  24342. throw new Error("Active camera not set");
  24343. camera = this.activeCamera;
  24344. }
  24345. var cameraViewport = camera.viewport;
  24346. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24347. var identity = BABYLON.Matrix.Identity();
  24348. // Moving coordinates to local viewport world
  24349. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24350. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24351. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24352. return this;
  24353. };
  24354. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24355. if (!BABYLON.PickingInfo) {
  24356. return null;
  24357. }
  24358. var pickingInfo = null;
  24359. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24360. var mesh = this.meshes[meshIndex];
  24361. if (predicate) {
  24362. if (!predicate(mesh)) {
  24363. continue;
  24364. }
  24365. }
  24366. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24367. continue;
  24368. }
  24369. var world = mesh.getWorldMatrix();
  24370. var ray = rayFunction(world);
  24371. var result = mesh.intersects(ray, fastCheck);
  24372. if (!result || !result.hit)
  24373. continue;
  24374. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24375. continue;
  24376. pickingInfo = result;
  24377. if (fastCheck) {
  24378. break;
  24379. }
  24380. }
  24381. return pickingInfo || new BABYLON.PickingInfo();
  24382. };
  24383. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24384. if (!BABYLON.PickingInfo) {
  24385. return null;
  24386. }
  24387. var pickingInfos = new Array();
  24388. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24389. var mesh = this.meshes[meshIndex];
  24390. if (predicate) {
  24391. if (!predicate(mesh)) {
  24392. continue;
  24393. }
  24394. }
  24395. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24396. continue;
  24397. }
  24398. var world = mesh.getWorldMatrix();
  24399. var ray = rayFunction(world);
  24400. var result = mesh.intersects(ray, false);
  24401. if (!result || !result.hit)
  24402. continue;
  24403. pickingInfos.push(result);
  24404. }
  24405. return pickingInfos;
  24406. };
  24407. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24408. if (!BABYLON.PickingInfo) {
  24409. return null;
  24410. }
  24411. var pickingInfo = null;
  24412. if (!camera) {
  24413. if (!this.activeCamera) {
  24414. return null;
  24415. }
  24416. camera = this.activeCamera;
  24417. }
  24418. if (this.spriteManagers.length > 0) {
  24419. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24420. var spriteManager = this.spriteManagers[spriteIndex];
  24421. if (!spriteManager.isPickable) {
  24422. continue;
  24423. }
  24424. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24425. if (!result || !result.hit)
  24426. continue;
  24427. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24428. continue;
  24429. pickingInfo = result;
  24430. if (fastCheck) {
  24431. break;
  24432. }
  24433. }
  24434. }
  24435. return pickingInfo || new BABYLON.PickingInfo();
  24436. };
  24437. /** Launch a ray to try to pick a mesh in the scene
  24438. * @param x position on screen
  24439. * @param y position on screen
  24440. * @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
  24441. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24442. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24443. */
  24444. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24445. var _this = this;
  24446. if (!BABYLON.PickingInfo) {
  24447. return null;
  24448. }
  24449. return this._internalPick(function (world) {
  24450. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24451. return _this._tempPickingRay;
  24452. }, predicate, fastCheck);
  24453. };
  24454. /** Launch a ray to try to pick a sprite in the scene
  24455. * @param x position on screen
  24456. * @param y position on screen
  24457. * @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
  24458. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24459. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24460. */
  24461. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24462. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24463. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24464. };
  24465. /** Use the given ray to pick a mesh in the scene
  24466. * @param ray The ray to use to pick meshes
  24467. * @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
  24468. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24469. */
  24470. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24471. var _this = this;
  24472. return this._internalPick(function (world) {
  24473. if (!_this._pickWithRayInverseMatrix) {
  24474. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24475. }
  24476. world.invertToRef(_this._pickWithRayInverseMatrix);
  24477. if (!_this._cachedRayForTransform) {
  24478. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24479. }
  24480. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24481. return _this._cachedRayForTransform;
  24482. }, predicate, fastCheck);
  24483. };
  24484. /**
  24485. * Launch a ray to try to pick a mesh in the scene
  24486. * @param x X position on screen
  24487. * @param y Y position on screen
  24488. * @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
  24489. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24490. */
  24491. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24492. var _this = this;
  24493. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24494. };
  24495. /**
  24496. * Launch a ray to try to pick a mesh in the scene
  24497. * @param ray Ray to use
  24498. * @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
  24499. */
  24500. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24501. var _this = this;
  24502. return this._internalMultiPick(function (world) {
  24503. if (!_this._pickWithRayInverseMatrix) {
  24504. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24505. }
  24506. world.invertToRef(_this._pickWithRayInverseMatrix);
  24507. if (!_this._cachedRayForTransform) {
  24508. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24509. }
  24510. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24511. return _this._cachedRayForTransform;
  24512. }, predicate);
  24513. };
  24514. Scene.prototype.setPointerOverMesh = function (mesh) {
  24515. if (this._pointerOverMesh === mesh) {
  24516. return;
  24517. }
  24518. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24519. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24520. }
  24521. this._pointerOverMesh = mesh;
  24522. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24523. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24524. }
  24525. };
  24526. Scene.prototype.getPointerOverMesh = function () {
  24527. return this._pointerOverMesh;
  24528. };
  24529. Scene.prototype.setPointerOverSprite = function (sprite) {
  24530. if (this._pointerOverSprite === sprite) {
  24531. return;
  24532. }
  24533. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24534. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24535. }
  24536. this._pointerOverSprite = sprite;
  24537. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24538. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24539. }
  24540. };
  24541. Scene.prototype.getPointerOverSprite = function () {
  24542. return this._pointerOverSprite;
  24543. };
  24544. // Physics
  24545. Scene.prototype.getPhysicsEngine = function () {
  24546. return this._physicsEngine;
  24547. };
  24548. /**
  24549. * Enables physics to the current scene
  24550. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24551. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24552. * @return {boolean} was the physics engine initialized
  24553. */
  24554. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24555. if (gravity === void 0) { gravity = null; }
  24556. if (this._physicsEngine) {
  24557. return true;
  24558. }
  24559. try {
  24560. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24561. return true;
  24562. }
  24563. catch (e) {
  24564. BABYLON.Tools.Error(e.message);
  24565. return false;
  24566. }
  24567. };
  24568. Scene.prototype.disablePhysicsEngine = function () {
  24569. if (!this._physicsEngine) {
  24570. return;
  24571. }
  24572. this._physicsEngine.dispose();
  24573. this._physicsEngine = null;
  24574. };
  24575. Scene.prototype.isPhysicsEnabled = function () {
  24576. return this._physicsEngine !== undefined;
  24577. };
  24578. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24579. var mesh = compound.parts[0].mesh;
  24580. if (mesh.physicsImpostor) {
  24581. mesh.physicsImpostor.dispose();
  24582. mesh.physicsImpostor = null;
  24583. }
  24584. };
  24585. // Misc.
  24586. Scene.prototype._rebuildGeometries = function () {
  24587. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24588. var geometry = _a[_i];
  24589. geometry._rebuild();
  24590. }
  24591. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24592. var mesh = _c[_b];
  24593. mesh._rebuild();
  24594. }
  24595. if (this.postProcessManager) {
  24596. this.postProcessManager._rebuild();
  24597. }
  24598. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24599. var layer = _e[_d];
  24600. layer._rebuild();
  24601. }
  24602. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24603. var effectLayer = _g[_f];
  24604. effectLayer._rebuild();
  24605. }
  24606. if (this._boundingBoxRenderer) {
  24607. this._boundingBoxRenderer._rebuild();
  24608. }
  24609. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24610. var system = _j[_h];
  24611. system.rebuild();
  24612. }
  24613. if (this._postProcessRenderPipelineManager) {
  24614. this._postProcessRenderPipelineManager._rebuild();
  24615. }
  24616. };
  24617. Scene.prototype._rebuildTextures = function () {
  24618. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24619. var texture = _a[_i];
  24620. texture._rebuild();
  24621. }
  24622. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24623. };
  24624. /**
  24625. * Creates a default light for the scene.
  24626. * @param replace Whether to replace the existing lights in the scene.
  24627. */
  24628. Scene.prototype.createDefaultLight = function (replace) {
  24629. if (replace === void 0) { replace = false; }
  24630. // Dispose existing light in replace mode.
  24631. if (replace) {
  24632. if (this.lights) {
  24633. for (var i = 0; i < this.lights.length; i++) {
  24634. this.lights[i].dispose();
  24635. }
  24636. }
  24637. }
  24638. // Light
  24639. if (this.lights.length === 0) {
  24640. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24641. }
  24642. };
  24643. /**
  24644. * Creates a default camera for the scene.
  24645. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24646. * @param replace Whether to replace the existing active camera in the scene.
  24647. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24648. */
  24649. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24650. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24651. if (replace === void 0) { replace = false; }
  24652. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24653. // Dispose existing camera in replace mode.
  24654. if (replace) {
  24655. if (this.activeCamera) {
  24656. this.activeCamera.dispose();
  24657. this.activeCamera = null;
  24658. }
  24659. }
  24660. // Camera
  24661. if (!this.activeCamera) {
  24662. var worldExtends = this.getWorldExtends();
  24663. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24664. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24665. var camera;
  24666. var radius = worldSize.length() * 1.5;
  24667. // empty scene scenario!
  24668. if (!isFinite(radius)) {
  24669. radius = 1;
  24670. worldCenter.copyFromFloats(0, 0, 0);
  24671. }
  24672. if (createArcRotateCamera) {
  24673. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24674. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24675. arcRotateCamera.wheelPrecision = 100 / radius;
  24676. camera = arcRotateCamera;
  24677. }
  24678. else {
  24679. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24680. freeCamera.setTarget(worldCenter);
  24681. camera = freeCamera;
  24682. }
  24683. camera.minZ = radius * 0.01;
  24684. camera.maxZ = radius * 1000;
  24685. camera.speed = radius * 0.2;
  24686. this.activeCamera = camera;
  24687. var canvas = this.getEngine().getRenderingCanvas();
  24688. if (attachCameraControls && canvas) {
  24689. camera.attachControl(canvas);
  24690. }
  24691. }
  24692. };
  24693. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24694. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24695. if (replace === void 0) { replace = false; }
  24696. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24697. this.createDefaultLight(replace);
  24698. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24699. };
  24700. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24701. if (pbr === void 0) { pbr = false; }
  24702. if (scale === void 0) { scale = 1000; }
  24703. if (blur === void 0) { blur = 0; }
  24704. if (environmentTexture) {
  24705. this.environmentTexture = environmentTexture;
  24706. }
  24707. if (!this.environmentTexture) {
  24708. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24709. return null;
  24710. }
  24711. // Skybox
  24712. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24713. if (pbr) {
  24714. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24715. hdrSkyboxMaterial.backFaceCulling = false;
  24716. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24717. if (hdrSkyboxMaterial.reflectionTexture) {
  24718. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24719. }
  24720. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24721. hdrSkyboxMaterial.disableLighting = true;
  24722. hdrSkyboxMaterial.twoSidedLighting = true;
  24723. hdrSkybox.infiniteDistance = true;
  24724. hdrSkybox.material = hdrSkyboxMaterial;
  24725. }
  24726. else {
  24727. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24728. skyboxMaterial.backFaceCulling = false;
  24729. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24730. if (skyboxMaterial.reflectionTexture) {
  24731. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24732. }
  24733. skyboxMaterial.disableLighting = true;
  24734. hdrSkybox.infiniteDistance = true;
  24735. hdrSkybox.material = skyboxMaterial;
  24736. }
  24737. return hdrSkybox;
  24738. };
  24739. Scene.prototype.createDefaultEnvironment = function (options) {
  24740. if (BABYLON.EnvironmentHelper) {
  24741. return new BABYLON.EnvironmentHelper(options, this);
  24742. }
  24743. return null;
  24744. };
  24745. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24746. if (webVROptions === void 0) { webVROptions = {}; }
  24747. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24748. };
  24749. // Tags
  24750. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24751. if (tagsQuery === undefined) {
  24752. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24753. return list;
  24754. }
  24755. var listByTags = [];
  24756. forEach = forEach || (function (item) { return; });
  24757. for (var i in list) {
  24758. var item = list[i];
  24759. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24760. listByTags.push(item);
  24761. forEach(item);
  24762. }
  24763. }
  24764. return listByTags;
  24765. };
  24766. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24767. return this._getByTags(this.meshes, tagsQuery, forEach);
  24768. };
  24769. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24770. return this._getByTags(this.cameras, tagsQuery, forEach);
  24771. };
  24772. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24773. return this._getByTags(this.lights, tagsQuery, forEach);
  24774. };
  24775. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24776. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24777. };
  24778. /**
  24779. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24780. * This allowed control for front to back rendering or reversly depending of the special needs.
  24781. *
  24782. * @param renderingGroupId The rendering group id corresponding to its index
  24783. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24784. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24785. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24786. */
  24787. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24788. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24789. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24790. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24791. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24792. };
  24793. /**
  24794. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24795. *
  24796. * @param renderingGroupId The rendering group id corresponding to its index
  24797. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24798. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24799. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24800. */
  24801. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24802. if (depth === void 0) { depth = true; }
  24803. if (stencil === void 0) { stencil = true; }
  24804. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24805. };
  24806. /**
  24807. * Will flag all materials as dirty to trigger new shader compilation
  24808. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24809. */
  24810. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24811. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24812. var material = _a[_i];
  24813. if (predicate && !predicate(material)) {
  24814. continue;
  24815. }
  24816. material.markAsDirty(flag);
  24817. }
  24818. };
  24819. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24820. var _this = this;
  24821. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24822. this._activeRequests.push(request);
  24823. request.onCompleteObservable.add(function (request) {
  24824. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24825. });
  24826. return request;
  24827. };
  24828. /** @ignore */
  24829. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24830. var _this = this;
  24831. return new Promise(function (resolve, reject) {
  24832. _this._loadFile(url, function (data) {
  24833. resolve(data);
  24834. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24835. reject(exception);
  24836. });
  24837. });
  24838. };
  24839. // Statics
  24840. Scene._FOGMODE_NONE = 0;
  24841. Scene._FOGMODE_EXP = 1;
  24842. Scene._FOGMODE_EXP2 = 2;
  24843. Scene._FOGMODE_LINEAR = 3;
  24844. Scene._uniqueIdCounter = 0;
  24845. Scene.MinDeltaTime = 1.0;
  24846. Scene.MaxDeltaTime = 1000.0;
  24847. /** The distance in pixel that you have to move to prevent some events */
  24848. Scene.DragMovementThreshold = 10; // in pixels
  24849. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24850. Scene.LongPressDelay = 500; // in milliseconds
  24851. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24852. Scene.DoubleClickDelay = 300; // in milliseconds
  24853. /** If you need to check double click without raising a single click at first click, enable this flag */
  24854. Scene.ExclusiveDoubleClickMode = false;
  24855. return Scene;
  24856. }());
  24857. BABYLON.Scene = Scene;
  24858. })(BABYLON || (BABYLON = {}));
  24859. //# sourceMappingURL=babylon.scene.js.map
  24860. var BABYLON;
  24861. (function (BABYLON) {
  24862. /**
  24863. * Set of assets to keep when moving a scene into an asset container.
  24864. */
  24865. var KeepAssets = /** @class */ (function () {
  24866. function KeepAssets() {
  24867. /**
  24868. * Cameras to keep.
  24869. */
  24870. this.cameras = new Array();
  24871. /**
  24872. * Lights to keep.
  24873. */
  24874. this.lights = new Array();
  24875. /**
  24876. * Meshes to keep.
  24877. */
  24878. this.meshes = new Array();
  24879. /**
  24880. * Skeletons to keep.
  24881. */
  24882. this.skeletons = new Array();
  24883. /**
  24884. * ParticleSystems to keep.
  24885. */
  24886. this.particleSystems = new Array();
  24887. /**
  24888. * Animations to keep.
  24889. */
  24890. this.animations = new Array();
  24891. /**
  24892. * MultiMaterials to keep.
  24893. */
  24894. this.multiMaterials = new Array();
  24895. /**
  24896. * Materials to keep.
  24897. */
  24898. this.materials = new Array();
  24899. /**
  24900. * MorphTargetManagers to keep.
  24901. */
  24902. this.morphTargetManagers = new Array();
  24903. /**
  24904. * Geometries to keep.
  24905. */
  24906. this.geometries = new Array();
  24907. /**
  24908. * TransformNodes to keep.
  24909. */
  24910. this.transformNodes = new Array();
  24911. /**
  24912. * LensFlareSystems to keep.
  24913. */
  24914. this.lensFlareSystems = new Array();
  24915. /**
  24916. * ShadowGenerators to keep.
  24917. */
  24918. this.shadowGenerators = new Array();
  24919. /**
  24920. * ActionManagers to keep.
  24921. */
  24922. this.actionManagers = new Array();
  24923. /**
  24924. * Sounds to keep.
  24925. */
  24926. this.sounds = new Array();
  24927. }
  24928. return KeepAssets;
  24929. }());
  24930. BABYLON.KeepAssets = KeepAssets;
  24931. /**
  24932. * Container with a set of assets that can be added or removed from a scene.
  24933. */
  24934. var AssetContainer = /** @class */ (function () {
  24935. /**
  24936. * Instantiates an AssetContainer.
  24937. * @param scene The scene the AssetContainer belongs to.
  24938. */
  24939. function AssetContainer(scene) {
  24940. // Objects
  24941. /**
  24942. * Cameras populated in the container.
  24943. */
  24944. this.cameras = new Array();
  24945. /**
  24946. * Lights populated in the container.
  24947. */
  24948. this.lights = new Array();
  24949. /**
  24950. * Meshes populated in the container.
  24951. */
  24952. this.meshes = new Array();
  24953. /**
  24954. * Skeletons populated in the container.
  24955. */
  24956. this.skeletons = new Array();
  24957. /**
  24958. * ParticleSystems populated in the container.
  24959. */
  24960. this.particleSystems = new Array();
  24961. /**
  24962. * Animations populated in the container.
  24963. */
  24964. this.animations = new Array();
  24965. /**
  24966. * MultiMaterials populated in the container.
  24967. */
  24968. this.multiMaterials = new Array();
  24969. /**
  24970. * Materials populated in the container.
  24971. */
  24972. this.materials = new Array();
  24973. /**
  24974. * MorphTargetManagers populated in the container.
  24975. */
  24976. this.morphTargetManagers = new Array();
  24977. /**
  24978. * Geometries populated in the container.
  24979. */
  24980. this.geometries = new Array();
  24981. /**
  24982. * TransformNodes populated in the container.
  24983. */
  24984. this.transformNodes = new Array();
  24985. /**
  24986. * LensFlareSystems populated in the container.
  24987. */
  24988. this.lensFlareSystems = new Array();
  24989. /**
  24990. * ShadowGenerators populated in the container.
  24991. */
  24992. this.shadowGenerators = new Array();
  24993. /**
  24994. * ActionManagers populated in the container.
  24995. */
  24996. this.actionManagers = new Array();
  24997. /**
  24998. * Sounds populated in the container.
  24999. */
  25000. this.sounds = new Array();
  25001. this.scene = scene;
  25002. }
  25003. /**
  25004. * Adds all the assets from the container to the scene.
  25005. */
  25006. AssetContainer.prototype.addAllToScene = function () {
  25007. var _this = this;
  25008. this.cameras.forEach(function (o) {
  25009. _this.scene.addCamera(o);
  25010. });
  25011. this.lights.forEach(function (o) {
  25012. _this.scene.addLight(o);
  25013. });
  25014. this.meshes.forEach(function (o) {
  25015. _this.scene.addMesh(o);
  25016. });
  25017. this.skeletons.forEach(function (o) {
  25018. _this.scene.addSkeleton(o);
  25019. });
  25020. this.particleSystems.forEach(function (o) {
  25021. _this.scene.addParticleSystem(o);
  25022. });
  25023. this.animations.forEach(function (o) {
  25024. _this.scene.addAnimation(o);
  25025. });
  25026. this.multiMaterials.forEach(function (o) {
  25027. _this.scene.addMultiMaterial(o);
  25028. });
  25029. this.materials.forEach(function (o) {
  25030. _this.scene.addMaterial(o);
  25031. });
  25032. this.morphTargetManagers.forEach(function (o) {
  25033. _this.scene.addMorphTargetManager(o);
  25034. });
  25035. this.geometries.forEach(function (o) {
  25036. _this.scene.addGeometry(o);
  25037. });
  25038. this.transformNodes.forEach(function (o) {
  25039. _this.scene.addTransformNode(o);
  25040. });
  25041. this.lensFlareSystems.forEach(function (o) {
  25042. _this.scene.addLensFlareSystem(o);
  25043. });
  25044. this.actionManagers.forEach(function (o) {
  25045. _this.scene.addActionManager(o);
  25046. });
  25047. this.sounds.forEach(function (o) {
  25048. o.play();
  25049. o.autoplay = true;
  25050. _this.scene.mainSoundTrack.AddSound(o);
  25051. });
  25052. };
  25053. /**
  25054. * Removes all the assets in the container from the scene
  25055. */
  25056. AssetContainer.prototype.removeAllFromScene = function () {
  25057. var _this = this;
  25058. this.cameras.forEach(function (o) {
  25059. _this.scene.removeCamera(o);
  25060. });
  25061. this.lights.forEach(function (o) {
  25062. _this.scene.removeLight(o);
  25063. });
  25064. this.meshes.forEach(function (o) {
  25065. _this.scene.removeMesh(o);
  25066. });
  25067. this.skeletons.forEach(function (o) {
  25068. _this.scene.removeSkeleton(o);
  25069. });
  25070. this.particleSystems.forEach(function (o) {
  25071. _this.scene.removeParticleSystem(o);
  25072. });
  25073. this.animations.forEach(function (o) {
  25074. _this.scene.removeAnimation(o);
  25075. });
  25076. this.multiMaterials.forEach(function (o) {
  25077. _this.scene.removeMultiMaterial(o);
  25078. });
  25079. this.materials.forEach(function (o) {
  25080. _this.scene.removeMaterial(o);
  25081. });
  25082. this.morphTargetManagers.forEach(function (o) {
  25083. _this.scene.removeMorphTargetManager(o);
  25084. });
  25085. this.geometries.forEach(function (o) {
  25086. _this.scene.removeGeometry(o);
  25087. });
  25088. this.transformNodes.forEach(function (o) {
  25089. _this.scene.removeTransformNode(o);
  25090. });
  25091. this.lensFlareSystems.forEach(function (o) {
  25092. _this.scene.removeLensFlareSystem(o);
  25093. });
  25094. this.actionManagers.forEach(function (o) {
  25095. _this.scene.removeActionManager(o);
  25096. });
  25097. this.sounds.forEach(function (o) {
  25098. o.stop();
  25099. o.autoplay = false;
  25100. _this.scene.mainSoundTrack.RemoveSound(o);
  25101. });
  25102. };
  25103. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25104. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25105. var asset = sourceAssets_1[_i];
  25106. var move = true;
  25107. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25108. var keepAsset = keepAssets_1[_a];
  25109. if (asset === keepAsset) {
  25110. move = false;
  25111. break;
  25112. }
  25113. }
  25114. if (move) {
  25115. targetAssets.push(asset);
  25116. }
  25117. }
  25118. };
  25119. /**
  25120. * Removes all the assets contained in the scene and adds them to the container.
  25121. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25122. */
  25123. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25124. if (keepAssets === undefined) {
  25125. keepAssets = new KeepAssets();
  25126. }
  25127. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25128. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25129. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25130. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25131. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25132. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25133. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25134. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25135. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25136. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25137. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25138. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25139. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25140. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25141. this.removeAllFromScene();
  25142. };
  25143. return AssetContainer;
  25144. }());
  25145. BABYLON.AssetContainer = AssetContainer;
  25146. })(BABYLON || (BABYLON = {}));
  25147. //# sourceMappingURL=babylon.assetContainer.js.map
  25148. var BABYLON;
  25149. (function (BABYLON) {
  25150. var Buffer = /** @class */ (function () {
  25151. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25152. if (instanced === void 0) { instanced = false; }
  25153. if (engine instanceof BABYLON.Mesh) {
  25154. this._engine = engine.getScene().getEngine();
  25155. }
  25156. else {
  25157. this._engine = engine;
  25158. }
  25159. this._updatable = updatable;
  25160. this._data = data;
  25161. this._strideSize = stride;
  25162. if (!postponeInternalCreation) {
  25163. this.create();
  25164. }
  25165. this._instanced = instanced;
  25166. this._instanceDivisor = instanced ? 1 : 0;
  25167. }
  25168. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  25169. // a lot of these parameters are ignored as they are overriden by the buffer
  25170. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  25171. };
  25172. // Properties
  25173. Buffer.prototype.isUpdatable = function () {
  25174. return this._updatable;
  25175. };
  25176. Buffer.prototype.getData = function () {
  25177. return this._data;
  25178. };
  25179. Buffer.prototype.getBuffer = function () {
  25180. return this._buffer;
  25181. };
  25182. Buffer.prototype.getStrideSize = function () {
  25183. return this._strideSize;
  25184. };
  25185. Buffer.prototype.getIsInstanced = function () {
  25186. return this._instanced;
  25187. };
  25188. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  25189. get: function () {
  25190. return this._instanceDivisor;
  25191. },
  25192. set: function (value) {
  25193. this._instanceDivisor = value;
  25194. if (value == 0) {
  25195. this._instanced = false;
  25196. }
  25197. else {
  25198. this._instanced = true;
  25199. }
  25200. },
  25201. enumerable: true,
  25202. configurable: true
  25203. });
  25204. // Methods
  25205. Buffer.prototype.create = function (data) {
  25206. if (data === void 0) { data = null; }
  25207. if (!data && this._buffer) {
  25208. return; // nothing to do
  25209. }
  25210. data = data || this._data;
  25211. if (!data) {
  25212. return;
  25213. }
  25214. if (!this._buffer) {
  25215. if (this._updatable) {
  25216. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25217. this._data = data;
  25218. }
  25219. else {
  25220. this._buffer = this._engine.createVertexBuffer(data);
  25221. }
  25222. }
  25223. else if (this._updatable) {
  25224. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25225. this._data = data;
  25226. }
  25227. };
  25228. Buffer.prototype._rebuild = function () {
  25229. this._buffer = null;
  25230. this.create(this._data);
  25231. };
  25232. Buffer.prototype.update = function (data) {
  25233. this.create(data);
  25234. };
  25235. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25236. if (!this._buffer) {
  25237. return;
  25238. }
  25239. if (this._updatable) {
  25240. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25241. this._data = null;
  25242. }
  25243. };
  25244. Buffer.prototype.dispose = function () {
  25245. if (!this._buffer) {
  25246. return;
  25247. }
  25248. if (this._engine._releaseBuffer(this._buffer)) {
  25249. this._buffer = null;
  25250. }
  25251. };
  25252. return Buffer;
  25253. }());
  25254. BABYLON.Buffer = Buffer;
  25255. })(BABYLON || (BABYLON = {}));
  25256. //# sourceMappingURL=babylon.buffer.js.map
  25257. var BABYLON;
  25258. (function (BABYLON) {
  25259. var VertexBuffer = /** @class */ (function () {
  25260. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25261. if (!stride) {
  25262. stride = VertexBuffer.DeduceStride(kind);
  25263. }
  25264. if (data instanceof BABYLON.Buffer) {
  25265. if (!stride) {
  25266. stride = data.getStrideSize();
  25267. }
  25268. this._buffer = data;
  25269. this._ownsBuffer = false;
  25270. }
  25271. else {
  25272. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25273. this._ownsBuffer = true;
  25274. }
  25275. this._stride = stride;
  25276. this._offset = offset ? offset : 0;
  25277. this._size = size ? size : stride;
  25278. this._kind = kind;
  25279. }
  25280. VertexBuffer.prototype._rebuild = function () {
  25281. if (!this._buffer) {
  25282. return;
  25283. }
  25284. this._buffer._rebuild();
  25285. };
  25286. /**
  25287. * Returns the kind of the VertexBuffer (string).
  25288. */
  25289. VertexBuffer.prototype.getKind = function () {
  25290. return this._kind;
  25291. };
  25292. // Properties
  25293. /**
  25294. * Boolean : is the VertexBuffer updatable ?
  25295. */
  25296. VertexBuffer.prototype.isUpdatable = function () {
  25297. return this._buffer.isUpdatable();
  25298. };
  25299. /**
  25300. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25301. */
  25302. VertexBuffer.prototype.getData = function () {
  25303. return this._buffer.getData();
  25304. };
  25305. /**
  25306. * Returns the WebGLBuffer associated to the VertexBuffer.
  25307. */
  25308. VertexBuffer.prototype.getBuffer = function () {
  25309. return this._buffer.getBuffer();
  25310. };
  25311. /**
  25312. * Returns the stride of the VertexBuffer (integer).
  25313. */
  25314. VertexBuffer.prototype.getStrideSize = function () {
  25315. return this._stride;
  25316. };
  25317. /**
  25318. * Returns the offset (integer).
  25319. */
  25320. VertexBuffer.prototype.getOffset = function () {
  25321. return this._offset;
  25322. };
  25323. /**
  25324. * Returns the VertexBuffer total size (integer).
  25325. */
  25326. VertexBuffer.prototype.getSize = function () {
  25327. return this._size;
  25328. };
  25329. /**
  25330. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25331. */
  25332. VertexBuffer.prototype.getIsInstanced = function () {
  25333. return this._buffer.getIsInstanced();
  25334. };
  25335. /**
  25336. * Returns the instancing divisor, zero for non-instanced (integer).
  25337. */
  25338. VertexBuffer.prototype.getInstanceDivisor = function () {
  25339. return this._buffer.instanceDivisor;
  25340. };
  25341. // Methods
  25342. /**
  25343. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25344. * Returns the created WebGLBuffer.
  25345. */
  25346. VertexBuffer.prototype.create = function (data) {
  25347. return this._buffer.create(data);
  25348. };
  25349. /**
  25350. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25351. * This function will create a new buffer if the current one is not updatable
  25352. * Returns the updated WebGLBuffer.
  25353. */
  25354. VertexBuffer.prototype.update = function (data) {
  25355. return this._buffer.update(data);
  25356. };
  25357. /**
  25358. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25359. * Returns the directly updated WebGLBuffer.
  25360. */
  25361. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25362. return this._buffer.updateDirectly(data, offset);
  25363. };
  25364. /**
  25365. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25366. */
  25367. VertexBuffer.prototype.dispose = function () {
  25368. if (this._ownsBuffer) {
  25369. this._buffer.dispose();
  25370. }
  25371. };
  25372. Object.defineProperty(VertexBuffer, "PositionKind", {
  25373. get: function () {
  25374. return VertexBuffer._PositionKind;
  25375. },
  25376. enumerable: true,
  25377. configurable: true
  25378. });
  25379. Object.defineProperty(VertexBuffer, "NormalKind", {
  25380. get: function () {
  25381. return VertexBuffer._NormalKind;
  25382. },
  25383. enumerable: true,
  25384. configurable: true
  25385. });
  25386. Object.defineProperty(VertexBuffer, "TangentKind", {
  25387. get: function () {
  25388. return VertexBuffer._TangentKind;
  25389. },
  25390. enumerable: true,
  25391. configurable: true
  25392. });
  25393. Object.defineProperty(VertexBuffer, "UVKind", {
  25394. get: function () {
  25395. return VertexBuffer._UVKind;
  25396. },
  25397. enumerable: true,
  25398. configurable: true
  25399. });
  25400. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25401. get: function () {
  25402. return VertexBuffer._UV2Kind;
  25403. },
  25404. enumerable: true,
  25405. configurable: true
  25406. });
  25407. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25408. get: function () {
  25409. return VertexBuffer._UV3Kind;
  25410. },
  25411. enumerable: true,
  25412. configurable: true
  25413. });
  25414. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25415. get: function () {
  25416. return VertexBuffer._UV4Kind;
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25422. get: function () {
  25423. return VertexBuffer._UV5Kind;
  25424. },
  25425. enumerable: true,
  25426. configurable: true
  25427. });
  25428. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25429. get: function () {
  25430. return VertexBuffer._UV6Kind;
  25431. },
  25432. enumerable: true,
  25433. configurable: true
  25434. });
  25435. Object.defineProperty(VertexBuffer, "ColorKind", {
  25436. get: function () {
  25437. return VertexBuffer._ColorKind;
  25438. },
  25439. enumerable: true,
  25440. configurable: true
  25441. });
  25442. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25443. get: function () {
  25444. return VertexBuffer._MatricesIndicesKind;
  25445. },
  25446. enumerable: true,
  25447. configurable: true
  25448. });
  25449. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25450. get: function () {
  25451. return VertexBuffer._MatricesWeightsKind;
  25452. },
  25453. enumerable: true,
  25454. configurable: true
  25455. });
  25456. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25457. get: function () {
  25458. return VertexBuffer._MatricesIndicesExtraKind;
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25464. get: function () {
  25465. return VertexBuffer._MatricesWeightsExtraKind;
  25466. },
  25467. enumerable: true,
  25468. configurable: true
  25469. });
  25470. /**
  25471. * Deduces the stride given a kind.
  25472. * @param kind The kind string to deduce
  25473. * @returns The deduced stride
  25474. */
  25475. VertexBuffer.DeduceStride = function (kind) {
  25476. switch (kind) {
  25477. case VertexBuffer.PositionKind:
  25478. return 3;
  25479. case VertexBuffer.NormalKind:
  25480. return 3;
  25481. case VertexBuffer.UVKind:
  25482. case VertexBuffer.UV2Kind:
  25483. case VertexBuffer.UV3Kind:
  25484. case VertexBuffer.UV4Kind:
  25485. case VertexBuffer.UV5Kind:
  25486. case VertexBuffer.UV6Kind:
  25487. return 2;
  25488. case VertexBuffer.TangentKind:
  25489. case VertexBuffer.ColorKind:
  25490. return 4;
  25491. case VertexBuffer.MatricesIndicesKind:
  25492. case VertexBuffer.MatricesIndicesExtraKind:
  25493. return 4;
  25494. case VertexBuffer.MatricesWeightsKind:
  25495. case VertexBuffer.MatricesWeightsExtraKind:
  25496. return 4;
  25497. default:
  25498. throw new Error("Invalid kind '" + kind + "'");
  25499. }
  25500. };
  25501. // Enums
  25502. VertexBuffer._PositionKind = "position";
  25503. VertexBuffer._NormalKind = "normal";
  25504. VertexBuffer._TangentKind = "tangent";
  25505. VertexBuffer._UVKind = "uv";
  25506. VertexBuffer._UV2Kind = "uv2";
  25507. VertexBuffer._UV3Kind = "uv3";
  25508. VertexBuffer._UV4Kind = "uv4";
  25509. VertexBuffer._UV5Kind = "uv5";
  25510. VertexBuffer._UV6Kind = "uv6";
  25511. VertexBuffer._ColorKind = "color";
  25512. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25513. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25514. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25515. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25516. return VertexBuffer;
  25517. }());
  25518. BABYLON.VertexBuffer = VertexBuffer;
  25519. })(BABYLON || (BABYLON = {}));
  25520. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25521. var BABYLON;
  25522. (function (BABYLON) {
  25523. /**
  25524. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25525. */
  25526. var DummyInternalTextureTracker = /** @class */ (function () {
  25527. function DummyInternalTextureTracker() {
  25528. /**
  25529. * Gets or set the previous tracker in the list
  25530. */
  25531. this.previous = null;
  25532. /**
  25533. * Gets or set the next tracker in the list
  25534. */
  25535. this.next = null;
  25536. }
  25537. return DummyInternalTextureTracker;
  25538. }());
  25539. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25540. })(BABYLON || (BABYLON = {}));
  25541. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25542. var BABYLON;
  25543. (function (BABYLON) {
  25544. /**
  25545. * Class used to store data associated with WebGL texture data for the engine
  25546. * This class should not be used directly
  25547. */
  25548. var InternalTexture = /** @class */ (function () {
  25549. /**
  25550. * Creates a new InternalTexture
  25551. * @param engine defines the engine to use
  25552. * @param dataSource defines the type of data that will be used
  25553. */
  25554. function InternalTexture(engine, dataSource) {
  25555. /**
  25556. * Observable called when the texture is loaded
  25557. */
  25558. this.onLoadedObservable = new BABYLON.Observable();
  25559. /**
  25560. * Gets or set the previous tracker in the list
  25561. */
  25562. this.previous = null;
  25563. /**
  25564. * Gets or set the next tracker in the list
  25565. */
  25566. this.next = null;
  25567. // Private
  25568. /** @ignore */
  25569. this._initialSlot = -1;
  25570. /** @ignore */
  25571. this._designatedSlot = -1;
  25572. /** @ignore */
  25573. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25574. /** @ignore */
  25575. this._references = 1;
  25576. this._engine = engine;
  25577. this._dataSource = dataSource;
  25578. this._webGLTexture = engine._createTexture();
  25579. }
  25580. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25581. /**
  25582. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25583. */
  25584. get: function () {
  25585. return this._dataSource;
  25586. },
  25587. enumerable: true,
  25588. configurable: true
  25589. });
  25590. /**
  25591. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25592. */
  25593. InternalTexture.prototype.incrementReferences = function () {
  25594. this._references++;
  25595. };
  25596. /**
  25597. * Change the size of the texture (not the size of the content)
  25598. * @param width defines the new width
  25599. * @param height defines the new height
  25600. * @param depth defines the new depth (1 by default)
  25601. */
  25602. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25603. if (depth === void 0) { depth = 1; }
  25604. this.width = width;
  25605. this.height = height;
  25606. this.depth = depth;
  25607. this.baseWidth = width;
  25608. this.baseHeight = height;
  25609. this.baseDepth = depth;
  25610. this._size = width * height * depth;
  25611. };
  25612. /** @ignore */
  25613. InternalTexture.prototype._rebuild = function () {
  25614. var _this = this;
  25615. var proxy;
  25616. this.isReady = false;
  25617. this._cachedCoordinatesMode = null;
  25618. this._cachedWrapU = null;
  25619. this._cachedWrapV = null;
  25620. this._cachedAnisotropicFilteringLevel = null;
  25621. switch (this._dataSource) {
  25622. case InternalTexture.DATASOURCE_TEMP:
  25623. return;
  25624. case InternalTexture.DATASOURCE_URL:
  25625. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25626. _this.isReady = true;
  25627. }, null, this._buffer, undefined, this.format);
  25628. proxy._swapAndDie(this);
  25629. return;
  25630. case InternalTexture.DATASOURCE_RAW:
  25631. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25632. proxy._swapAndDie(this);
  25633. this.isReady = true;
  25634. return;
  25635. case InternalTexture.DATASOURCE_RAW3D:
  25636. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25637. proxy._swapAndDie(this);
  25638. this.isReady = true;
  25639. return;
  25640. case InternalTexture.DATASOURCE_DYNAMIC:
  25641. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25642. proxy._swapAndDie(this);
  25643. // The engine will make sure to update content so no need to flag it as isReady = true
  25644. return;
  25645. case InternalTexture.DATASOURCE_RENDERTARGET:
  25646. var options = new BABYLON.RenderTargetCreationOptions();
  25647. options.generateDepthBuffer = this._generateDepthBuffer;
  25648. options.generateMipMaps = this.generateMipMaps;
  25649. options.generateStencilBuffer = this._generateStencilBuffer;
  25650. options.samplingMode = this.samplingMode;
  25651. options.type = this.type;
  25652. if (this.isCube) {
  25653. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25654. }
  25655. else {
  25656. var size = {
  25657. width: this.width,
  25658. height: this.height
  25659. };
  25660. proxy = this._engine.createRenderTargetTexture(size, options);
  25661. }
  25662. proxy._swapAndDie(this);
  25663. this.isReady = true;
  25664. return;
  25665. case InternalTexture.DATASOURCE_CUBE:
  25666. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25667. _this.isReady = true;
  25668. }, null, this.format, this._extension);
  25669. proxy._swapAndDie(this);
  25670. return;
  25671. case InternalTexture.DATASOURCE_CUBERAW:
  25672. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25673. proxy._swapAndDie(this);
  25674. this.isReady = true;
  25675. return;
  25676. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25677. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25678. if (proxy) {
  25679. proxy._swapAndDie(_this);
  25680. }
  25681. _this.isReady = true;
  25682. }, null, this.format, this._extension);
  25683. return;
  25684. }
  25685. };
  25686. InternalTexture.prototype._swapAndDie = function (target) {
  25687. target._webGLTexture = this._webGLTexture;
  25688. if (this._framebuffer) {
  25689. target._framebuffer = this._framebuffer;
  25690. }
  25691. if (this._depthStencilBuffer) {
  25692. target._depthStencilBuffer = this._depthStencilBuffer;
  25693. }
  25694. if (this._lodTextureHigh) {
  25695. if (target._lodTextureHigh) {
  25696. target._lodTextureHigh.dispose();
  25697. }
  25698. target._lodTextureHigh = this._lodTextureHigh;
  25699. }
  25700. if (this._lodTextureMid) {
  25701. if (target._lodTextureMid) {
  25702. target._lodTextureMid.dispose();
  25703. }
  25704. target._lodTextureMid = this._lodTextureMid;
  25705. }
  25706. if (this._lodTextureLow) {
  25707. if (target._lodTextureLow) {
  25708. target._lodTextureLow.dispose();
  25709. }
  25710. target._lodTextureLow = this._lodTextureLow;
  25711. }
  25712. var cache = this._engine.getLoadedTexturesCache();
  25713. var index = cache.indexOf(this);
  25714. if (index !== -1) {
  25715. cache.splice(index, 1);
  25716. }
  25717. };
  25718. /**
  25719. * Dispose the current allocated resources
  25720. */
  25721. InternalTexture.prototype.dispose = function () {
  25722. if (!this._webGLTexture) {
  25723. return;
  25724. }
  25725. this._references--;
  25726. if (this._references === 0) {
  25727. this._engine._releaseTexture(this);
  25728. this._webGLTexture = null;
  25729. this.previous = null;
  25730. this.next = null;
  25731. }
  25732. };
  25733. /**
  25734. * The source of the texture data is unknown
  25735. */
  25736. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25737. /**
  25738. * Texture data comes from an URL
  25739. */
  25740. InternalTexture.DATASOURCE_URL = 1;
  25741. /**
  25742. * Texture data is only used for temporary storage
  25743. */
  25744. InternalTexture.DATASOURCE_TEMP = 2;
  25745. /**
  25746. * Texture data comes from raw data (ArrayBuffer)
  25747. */
  25748. InternalTexture.DATASOURCE_RAW = 3;
  25749. /**
  25750. * Texture content is dynamic (video or dynamic texture)
  25751. */
  25752. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25753. /**
  25754. * Texture content is generated by rendering to it
  25755. */
  25756. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25757. /**
  25758. * Texture content is part of a multi render target process
  25759. */
  25760. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25761. /**
  25762. * Texture data comes from a cube data file
  25763. */
  25764. InternalTexture.DATASOURCE_CUBE = 7;
  25765. /**
  25766. * Texture data comes from a raw cube data
  25767. */
  25768. InternalTexture.DATASOURCE_CUBERAW = 8;
  25769. /**
  25770. * Texture data come from a prefiltered cube data file
  25771. */
  25772. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25773. /**
  25774. * Texture content is raw 3D data
  25775. */
  25776. InternalTexture.DATASOURCE_RAW3D = 10;
  25777. return InternalTexture;
  25778. }());
  25779. BABYLON.InternalTexture = InternalTexture;
  25780. })(BABYLON || (BABYLON = {}));
  25781. //# sourceMappingURL=babylon.internalTexture.js.map
  25782. var BABYLON;
  25783. (function (BABYLON) {
  25784. var BaseTexture = /** @class */ (function () {
  25785. function BaseTexture(scene) {
  25786. this._hasAlpha = false;
  25787. this.getAlphaFromRGB = false;
  25788. this.level = 1;
  25789. this.coordinatesIndex = 0;
  25790. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25791. /*
  25792. * How a texture is mapped.
  25793. *
  25794. * | Value | Type | Description |
  25795. * | ----- | ----------------------------------- | ----------- |
  25796. * | 0 | EXPLICIT_MODE | |
  25797. * | 1 | SPHERICAL_MODE | |
  25798. * | 2 | PLANAR_MODE | |
  25799. * | 3 | CUBIC_MODE | |
  25800. * | 4 | PROJECTION_MODE | |
  25801. * | 5 | SKYBOX_MODE | |
  25802. * | 6 | INVCUBIC_MODE | |
  25803. * | 7 | EQUIRECTANGULAR_MODE | |
  25804. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25805. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25806. */
  25807. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25808. /*
  25809. * | Value | Type | Description |
  25810. * | ----- | ------------------ | ----------- |
  25811. * | 0 | CLAMP_ADDRESSMODE | |
  25812. * | 1 | WRAP_ADDRESSMODE | |
  25813. * | 2 | MIRROR_ADDRESSMODE | |
  25814. */
  25815. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25816. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25817. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25818. this.isCube = false;
  25819. this.is3D = false;
  25820. this.gammaSpace = true;
  25821. this.invertZ = false;
  25822. this.lodLevelInAlpha = false;
  25823. this.lodGenerationOffset = 0.0;
  25824. this.lodGenerationScale = 0.8;
  25825. this.isRenderTarget = false;
  25826. this.animations = new Array();
  25827. /**
  25828. * An event triggered when the texture is disposed.
  25829. * @type {BABYLON.Observable}
  25830. */
  25831. this.onDisposeObservable = new BABYLON.Observable();
  25832. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25833. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25834. if (this._scene) {
  25835. this._scene.textures.push(this);
  25836. }
  25837. this._uid = null;
  25838. }
  25839. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25840. get: function () {
  25841. return this._hasAlpha;
  25842. },
  25843. set: function (value) {
  25844. if (this._hasAlpha === value) {
  25845. return;
  25846. }
  25847. this._hasAlpha = value;
  25848. if (this._scene) {
  25849. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25850. }
  25851. },
  25852. enumerable: true,
  25853. configurable: true
  25854. });
  25855. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25856. get: function () {
  25857. return this._coordinatesMode;
  25858. },
  25859. set: function (value) {
  25860. if (this._coordinatesMode === value) {
  25861. return;
  25862. }
  25863. this._coordinatesMode = value;
  25864. if (this._scene) {
  25865. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25866. }
  25867. },
  25868. enumerable: true,
  25869. configurable: true
  25870. });
  25871. Object.defineProperty(BaseTexture.prototype, "uid", {
  25872. get: function () {
  25873. if (!this._uid) {
  25874. this._uid = BABYLON.Tools.RandomId();
  25875. }
  25876. return this._uid;
  25877. },
  25878. enumerable: true,
  25879. configurable: true
  25880. });
  25881. BaseTexture.prototype.toString = function () {
  25882. return this.name;
  25883. };
  25884. BaseTexture.prototype.getClassName = function () {
  25885. return "BaseTexture";
  25886. };
  25887. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25888. set: function (callback) {
  25889. if (this._onDisposeObserver) {
  25890. this.onDisposeObservable.remove(this._onDisposeObserver);
  25891. }
  25892. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25893. },
  25894. enumerable: true,
  25895. configurable: true
  25896. });
  25897. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25898. get: function () {
  25899. return true;
  25900. },
  25901. enumerable: true,
  25902. configurable: true
  25903. });
  25904. BaseTexture.prototype.getScene = function () {
  25905. return this._scene;
  25906. };
  25907. BaseTexture.prototype.getTextureMatrix = function () {
  25908. return BABYLON.Matrix.IdentityReadOnly;
  25909. };
  25910. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25911. return BABYLON.Matrix.IdentityReadOnly;
  25912. };
  25913. BaseTexture.prototype.getInternalTexture = function () {
  25914. return this._texture;
  25915. };
  25916. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25917. return !this.isBlocking || this.isReady();
  25918. };
  25919. BaseTexture.prototype.isReady = function () {
  25920. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25921. this.delayLoad();
  25922. return false;
  25923. }
  25924. if (this._texture) {
  25925. return this._texture.isReady;
  25926. }
  25927. return false;
  25928. };
  25929. BaseTexture.prototype.getSize = function () {
  25930. if (this._texture && this._texture.width) {
  25931. return new BABYLON.Size(this._texture.width, this._texture.height);
  25932. }
  25933. if (this._texture && this._texture._size) {
  25934. return new BABYLON.Size(this._texture._size, this._texture._size);
  25935. }
  25936. return BABYLON.Size.Zero();
  25937. };
  25938. BaseTexture.prototype.getBaseSize = function () {
  25939. if (!this.isReady() || !this._texture)
  25940. return BABYLON.Size.Zero();
  25941. if (this._texture._size) {
  25942. return new BABYLON.Size(this._texture._size, this._texture._size);
  25943. }
  25944. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25945. };
  25946. BaseTexture.prototype.scale = function (ratio) {
  25947. };
  25948. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25949. get: function () {
  25950. return false;
  25951. },
  25952. enumerable: true,
  25953. configurable: true
  25954. });
  25955. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25956. if (!this._scene) {
  25957. return null;
  25958. }
  25959. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25960. for (var index = 0; index < texturesCache.length; index++) {
  25961. var texturesCacheEntry = texturesCache[index];
  25962. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25963. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25964. texturesCacheEntry.incrementReferences();
  25965. return texturesCacheEntry;
  25966. }
  25967. }
  25968. }
  25969. return null;
  25970. };
  25971. BaseTexture.prototype._rebuild = function () {
  25972. };
  25973. BaseTexture.prototype.delayLoad = function () {
  25974. };
  25975. BaseTexture.prototype.clone = function () {
  25976. return null;
  25977. };
  25978. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25979. get: function () {
  25980. if (!this._texture) {
  25981. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25982. }
  25983. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25984. },
  25985. enumerable: true,
  25986. configurable: true
  25987. });
  25988. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25989. get: function () {
  25990. if (!this._texture) {
  25991. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25992. }
  25993. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25994. },
  25995. enumerable: true,
  25996. configurable: true
  25997. });
  25998. BaseTexture.prototype.readPixels = function (faceIndex) {
  25999. if (faceIndex === void 0) { faceIndex = 0; }
  26000. if (!this._texture) {
  26001. return null;
  26002. }
  26003. var size = this.getSize();
  26004. var scene = this.getScene();
  26005. if (!scene) {
  26006. return null;
  26007. }
  26008. var engine = scene.getEngine();
  26009. if (this._texture.isCube) {
  26010. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26011. }
  26012. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26013. };
  26014. BaseTexture.prototype.releaseInternalTexture = function () {
  26015. if (this._texture) {
  26016. this._texture.dispose();
  26017. this._texture = null;
  26018. }
  26019. };
  26020. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26021. get: function () {
  26022. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26023. return null;
  26024. }
  26025. if (!this._texture._sphericalPolynomial) {
  26026. this._texture._sphericalPolynomial =
  26027. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26028. }
  26029. return this._texture._sphericalPolynomial;
  26030. },
  26031. set: function (value) {
  26032. if (this._texture) {
  26033. this._texture._sphericalPolynomial = value;
  26034. }
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26040. get: function () {
  26041. if (this._texture) {
  26042. return this._texture._lodTextureHigh;
  26043. }
  26044. return null;
  26045. },
  26046. enumerable: true,
  26047. configurable: true
  26048. });
  26049. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26050. get: function () {
  26051. if (this._texture) {
  26052. return this._texture._lodTextureMid;
  26053. }
  26054. return null;
  26055. },
  26056. enumerable: true,
  26057. configurable: true
  26058. });
  26059. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26060. get: function () {
  26061. if (this._texture) {
  26062. return this._texture._lodTextureLow;
  26063. }
  26064. return null;
  26065. },
  26066. enumerable: true,
  26067. configurable: true
  26068. });
  26069. BaseTexture.prototype.dispose = function () {
  26070. if (!this._scene) {
  26071. return;
  26072. }
  26073. // Animations
  26074. this._scene.stopAnimation(this);
  26075. // Remove from scene
  26076. this._scene._removePendingData(this);
  26077. var index = this._scene.textures.indexOf(this);
  26078. if (index >= 0) {
  26079. this._scene.textures.splice(index, 1);
  26080. }
  26081. if (this._texture === undefined) {
  26082. return;
  26083. }
  26084. // Release
  26085. this.releaseInternalTexture();
  26086. // Callback
  26087. this.onDisposeObservable.notifyObservers(this);
  26088. this.onDisposeObservable.clear();
  26089. };
  26090. BaseTexture.prototype.serialize = function () {
  26091. if (!this.name) {
  26092. return null;
  26093. }
  26094. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26095. // Animations
  26096. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26097. return serializationObject;
  26098. };
  26099. BaseTexture.WhenAllReady = function (textures, callback) {
  26100. var numRemaining = textures.length;
  26101. if (numRemaining === 0) {
  26102. callback();
  26103. return;
  26104. }
  26105. var _loop_1 = function () {
  26106. texture = textures[i];
  26107. if (texture.isReady()) {
  26108. if (--numRemaining === 0) {
  26109. callback();
  26110. }
  26111. }
  26112. else {
  26113. onLoadObservable = texture.onLoadObservable;
  26114. var onLoadCallback_1 = function () {
  26115. onLoadObservable.removeCallback(onLoadCallback_1);
  26116. if (--numRemaining === 0) {
  26117. callback();
  26118. }
  26119. };
  26120. onLoadObservable.add(onLoadCallback_1);
  26121. }
  26122. };
  26123. var texture, onLoadObservable;
  26124. for (var i = 0; i < textures.length; i++) {
  26125. _loop_1();
  26126. }
  26127. };
  26128. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26129. __decorate([
  26130. BABYLON.serialize()
  26131. ], BaseTexture.prototype, "name", void 0);
  26132. __decorate([
  26133. BABYLON.serialize("hasAlpha")
  26134. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26135. __decorate([
  26136. BABYLON.serialize()
  26137. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26138. __decorate([
  26139. BABYLON.serialize()
  26140. ], BaseTexture.prototype, "level", void 0);
  26141. __decorate([
  26142. BABYLON.serialize()
  26143. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26144. __decorate([
  26145. BABYLON.serialize("coordinatesMode")
  26146. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26147. __decorate([
  26148. BABYLON.serialize()
  26149. ], BaseTexture.prototype, "wrapU", void 0);
  26150. __decorate([
  26151. BABYLON.serialize()
  26152. ], BaseTexture.prototype, "wrapV", void 0);
  26153. __decorate([
  26154. BABYLON.serialize()
  26155. ], BaseTexture.prototype, "wrapR", void 0);
  26156. __decorate([
  26157. BABYLON.serialize()
  26158. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26159. __decorate([
  26160. BABYLON.serialize()
  26161. ], BaseTexture.prototype, "isCube", void 0);
  26162. __decorate([
  26163. BABYLON.serialize()
  26164. ], BaseTexture.prototype, "is3D", void 0);
  26165. __decorate([
  26166. BABYLON.serialize()
  26167. ], BaseTexture.prototype, "gammaSpace", void 0);
  26168. __decorate([
  26169. BABYLON.serialize()
  26170. ], BaseTexture.prototype, "invertZ", void 0);
  26171. __decorate([
  26172. BABYLON.serialize()
  26173. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26174. __decorate([
  26175. BABYLON.serialize()
  26176. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26177. __decorate([
  26178. BABYLON.serialize()
  26179. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26180. __decorate([
  26181. BABYLON.serialize()
  26182. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26183. return BaseTexture;
  26184. }());
  26185. BABYLON.BaseTexture = BaseTexture;
  26186. })(BABYLON || (BABYLON = {}));
  26187. //# sourceMappingURL=babylon.baseTexture.js.map
  26188. var BABYLON;
  26189. (function (BABYLON) {
  26190. var Texture = /** @class */ (function (_super) {
  26191. __extends(Texture, _super);
  26192. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26193. if (noMipmap === void 0) { noMipmap = false; }
  26194. if (invertY === void 0) { invertY = true; }
  26195. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26196. if (onLoad === void 0) { onLoad = null; }
  26197. if (onError === void 0) { onError = null; }
  26198. if (buffer === void 0) { buffer = null; }
  26199. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26200. var _this = _super.call(this, scene) || this;
  26201. _this.uOffset = 0;
  26202. _this.vOffset = 0;
  26203. _this.uScale = 1.0;
  26204. _this.vScale = 1.0;
  26205. _this.uAng = 0;
  26206. _this.vAng = 0;
  26207. _this.wAng = 0;
  26208. _this._isBlocking = true;
  26209. _this.name = url || "";
  26210. _this.url = url;
  26211. _this._noMipmap = noMipmap;
  26212. _this._invertY = invertY;
  26213. _this._samplingMode = samplingMode;
  26214. _this._buffer = buffer;
  26215. _this._deleteBuffer = deleteBuffer;
  26216. if (format) {
  26217. _this._format = format;
  26218. }
  26219. scene = _this.getScene();
  26220. if (!scene) {
  26221. return _this;
  26222. }
  26223. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26224. var load = function () {
  26225. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26226. _this.onLoadObservable.notifyObservers(_this);
  26227. }
  26228. if (onLoad) {
  26229. onLoad();
  26230. }
  26231. if (!_this.isBlocking && scene) {
  26232. scene.resetCachedMaterial();
  26233. }
  26234. };
  26235. if (!_this.url) {
  26236. _this._delayedOnLoad = load;
  26237. _this._delayedOnError = onError;
  26238. return _this;
  26239. }
  26240. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26241. if (!_this._texture) {
  26242. if (!scene.useDelayedTextureLoading) {
  26243. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26244. if (deleteBuffer) {
  26245. delete _this._buffer;
  26246. }
  26247. }
  26248. else {
  26249. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26250. _this._delayedOnLoad = load;
  26251. _this._delayedOnError = onError;
  26252. }
  26253. }
  26254. else {
  26255. if (_this._texture.isReady) {
  26256. BABYLON.Tools.SetImmediate(function () { return load(); });
  26257. }
  26258. else {
  26259. _this._texture.onLoadedObservable.add(load);
  26260. }
  26261. }
  26262. return _this;
  26263. }
  26264. Object.defineProperty(Texture.prototype, "noMipmap", {
  26265. get: function () {
  26266. return this._noMipmap;
  26267. },
  26268. enumerable: true,
  26269. configurable: true
  26270. });
  26271. Object.defineProperty(Texture.prototype, "isBlocking", {
  26272. get: function () {
  26273. return this._isBlocking;
  26274. },
  26275. set: function (value) {
  26276. this._isBlocking = value;
  26277. },
  26278. enumerable: true,
  26279. configurable: true
  26280. });
  26281. Object.defineProperty(Texture.prototype, "samplingMode", {
  26282. get: function () {
  26283. return this._samplingMode;
  26284. },
  26285. enumerable: true,
  26286. configurable: true
  26287. });
  26288. Texture.prototype.updateURL = function (url) {
  26289. this.url = url;
  26290. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26291. this.delayLoad();
  26292. };
  26293. Texture.prototype.delayLoad = function () {
  26294. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26295. return;
  26296. }
  26297. var scene = this.getScene();
  26298. if (!scene) {
  26299. return;
  26300. }
  26301. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26302. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26303. if (!this._texture) {
  26304. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26305. if (this._deleteBuffer) {
  26306. delete this._buffer;
  26307. }
  26308. }
  26309. else {
  26310. if (this._delayedOnLoad) {
  26311. if (this._texture.isReady) {
  26312. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26313. }
  26314. else {
  26315. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26316. }
  26317. }
  26318. }
  26319. this._delayedOnLoad = null;
  26320. this._delayedOnError = null;
  26321. };
  26322. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26323. if (!this._texture) {
  26324. return;
  26325. }
  26326. var scene = this.getScene();
  26327. if (!scene) {
  26328. return;
  26329. }
  26330. this._samplingMode = samplingMode;
  26331. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26332. };
  26333. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26334. x *= this.uScale;
  26335. y *= this.vScale;
  26336. x -= 0.5 * this.uScale;
  26337. y -= 0.5 * this.vScale;
  26338. z -= 0.5;
  26339. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26340. t.x += 0.5 * this.uScale + this.uOffset;
  26341. t.y += 0.5 * this.vScale + this.vOffset;
  26342. t.z += 0.5;
  26343. };
  26344. Texture.prototype.getTextureMatrix = function () {
  26345. var _this = this;
  26346. if (this.uOffset === this._cachedUOffset &&
  26347. this.vOffset === this._cachedVOffset &&
  26348. this.uScale === this._cachedUScale &&
  26349. this.vScale === this._cachedVScale &&
  26350. this.uAng === this._cachedUAng &&
  26351. this.vAng === this._cachedVAng &&
  26352. this.wAng === this._cachedWAng) {
  26353. return this._cachedTextureMatrix;
  26354. }
  26355. this._cachedUOffset = this.uOffset;
  26356. this._cachedVOffset = this.vOffset;
  26357. this._cachedUScale = this.uScale;
  26358. this._cachedVScale = this.vScale;
  26359. this._cachedUAng = this.uAng;
  26360. this._cachedVAng = this.vAng;
  26361. this._cachedWAng = this.wAng;
  26362. if (!this._cachedTextureMatrix) {
  26363. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26364. this._rowGenerationMatrix = new BABYLON.Matrix();
  26365. this._t0 = BABYLON.Vector3.Zero();
  26366. this._t1 = BABYLON.Vector3.Zero();
  26367. this._t2 = BABYLON.Vector3.Zero();
  26368. }
  26369. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26370. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26371. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26372. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26373. this._t1.subtractInPlace(this._t0);
  26374. this._t2.subtractInPlace(this._t0);
  26375. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26376. this._cachedTextureMatrix.m[0] = this._t1.x;
  26377. this._cachedTextureMatrix.m[1] = this._t1.y;
  26378. this._cachedTextureMatrix.m[2] = this._t1.z;
  26379. this._cachedTextureMatrix.m[4] = this._t2.x;
  26380. this._cachedTextureMatrix.m[5] = this._t2.y;
  26381. this._cachedTextureMatrix.m[6] = this._t2.z;
  26382. this._cachedTextureMatrix.m[8] = this._t0.x;
  26383. this._cachedTextureMatrix.m[9] = this._t0.y;
  26384. this._cachedTextureMatrix.m[10] = this._t0.z;
  26385. var scene = this.getScene();
  26386. if (!scene) {
  26387. return this._cachedTextureMatrix;
  26388. }
  26389. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26390. return mat.hasTexture(_this);
  26391. });
  26392. return this._cachedTextureMatrix;
  26393. };
  26394. Texture.prototype.getReflectionTextureMatrix = function () {
  26395. var _this = this;
  26396. var scene = this.getScene();
  26397. if (!scene) {
  26398. return this._cachedTextureMatrix;
  26399. }
  26400. if (this.uOffset === this._cachedUOffset &&
  26401. this.vOffset === this._cachedVOffset &&
  26402. this.uScale === this._cachedUScale &&
  26403. this.vScale === this._cachedVScale &&
  26404. this.coordinatesMode === this._cachedCoordinatesMode) {
  26405. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26406. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26407. return this._cachedTextureMatrix;
  26408. }
  26409. }
  26410. else {
  26411. return this._cachedTextureMatrix;
  26412. }
  26413. }
  26414. if (!this._cachedTextureMatrix) {
  26415. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26416. }
  26417. if (!this._projectionModeMatrix) {
  26418. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26419. }
  26420. this._cachedUOffset = this.uOffset;
  26421. this._cachedVOffset = this.vOffset;
  26422. this._cachedUScale = this.uScale;
  26423. this._cachedVScale = this.vScale;
  26424. this._cachedCoordinatesMode = this.coordinatesMode;
  26425. switch (this.coordinatesMode) {
  26426. case Texture.PLANAR_MODE:
  26427. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26428. this._cachedTextureMatrix[0] = this.uScale;
  26429. this._cachedTextureMatrix[5] = this.vScale;
  26430. this._cachedTextureMatrix[12] = this.uOffset;
  26431. this._cachedTextureMatrix[13] = this.vOffset;
  26432. break;
  26433. case Texture.PROJECTION_MODE:
  26434. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26435. this._projectionModeMatrix.m[0] = 0.5;
  26436. this._projectionModeMatrix.m[5] = -0.5;
  26437. this._projectionModeMatrix.m[10] = 0.0;
  26438. this._projectionModeMatrix.m[12] = 0.5;
  26439. this._projectionModeMatrix.m[13] = 0.5;
  26440. this._projectionModeMatrix.m[14] = 1.0;
  26441. this._projectionModeMatrix.m[15] = 1.0;
  26442. var projectionMatrix = scene.getProjectionMatrix();
  26443. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26444. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26445. break;
  26446. default:
  26447. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26448. break;
  26449. }
  26450. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26451. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26452. });
  26453. return this._cachedTextureMatrix;
  26454. };
  26455. Texture.prototype.clone = function () {
  26456. var _this = this;
  26457. return BABYLON.SerializationHelper.Clone(function () {
  26458. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26459. }, this);
  26460. };
  26461. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26462. get: function () {
  26463. if (!this._onLoadObservable) {
  26464. this._onLoadObservable = new BABYLON.Observable();
  26465. }
  26466. return this._onLoadObservable;
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Texture.prototype.serialize = function () {
  26472. var serializationObject = _super.prototype.serialize.call(this);
  26473. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26474. serializationObject.base64String = this._buffer;
  26475. serializationObject.name = serializationObject.name.replace("data:", "");
  26476. }
  26477. return serializationObject;
  26478. };
  26479. Texture.prototype.getClassName = function () {
  26480. return "Texture";
  26481. };
  26482. Texture.prototype.dispose = function () {
  26483. _super.prototype.dispose.call(this);
  26484. if (this.onLoadObservable) {
  26485. this.onLoadObservable.clear();
  26486. this._onLoadObservable = null;
  26487. }
  26488. this._delayedOnLoad = null;
  26489. this._delayedOnError = null;
  26490. };
  26491. // Statics
  26492. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26493. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26494. if (onLoad === void 0) { onLoad = null; }
  26495. if (onError === void 0) { onError = null; }
  26496. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26497. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26498. };
  26499. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26500. if (parsedTexture.customType) {
  26501. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26502. // Update Sampling Mode
  26503. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26504. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26505. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26506. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26507. }
  26508. }
  26509. return parsedCustomTexture;
  26510. }
  26511. if (parsedTexture.isCube) {
  26512. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26513. }
  26514. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26515. return null;
  26516. }
  26517. var texture = BABYLON.SerializationHelper.Parse(function () {
  26518. var generateMipMaps = true;
  26519. if (parsedTexture.noMipmap) {
  26520. generateMipMaps = false;
  26521. }
  26522. if (parsedTexture.mirrorPlane) {
  26523. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26524. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26525. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26526. return mirrorTexture;
  26527. }
  26528. else if (parsedTexture.isRenderTarget) {
  26529. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26530. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26531. return renderTargetTexture;
  26532. }
  26533. else {
  26534. var texture;
  26535. if (parsedTexture.base64String) {
  26536. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26537. }
  26538. else {
  26539. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26540. }
  26541. return texture;
  26542. }
  26543. }, parsedTexture, scene);
  26544. // Update Sampling Mode
  26545. if (parsedTexture.samplingMode) {
  26546. var sampling = parsedTexture.samplingMode;
  26547. if (texture._samplingMode !== sampling) {
  26548. texture.updateSamplingMode(sampling);
  26549. }
  26550. }
  26551. // Animations
  26552. if (parsedTexture.animations) {
  26553. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26554. var parsedAnimation = parsedTexture.animations[animationIndex];
  26555. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26556. }
  26557. }
  26558. return texture;
  26559. };
  26560. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26561. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26562. if (noMipmap === void 0) { noMipmap = false; }
  26563. if (invertY === void 0) { invertY = true; }
  26564. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26565. if (onLoad === void 0) { onLoad = null; }
  26566. if (onError === void 0) { onError = null; }
  26567. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26568. if (name.substr(0, 5) !== "data:") {
  26569. name = "data:" + name;
  26570. }
  26571. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26572. };
  26573. // Constants
  26574. Texture.NEAREST_SAMPLINGMODE = 1;
  26575. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26576. Texture.BILINEAR_SAMPLINGMODE = 2;
  26577. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26578. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26579. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26580. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26581. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26582. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26583. Texture.NEAREST_LINEAR = 7;
  26584. Texture.NEAREST_NEAREST = 8;
  26585. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26586. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26587. Texture.LINEAR_LINEAR = 11;
  26588. Texture.LINEAR_NEAREST = 12;
  26589. Texture.EXPLICIT_MODE = 0;
  26590. Texture.SPHERICAL_MODE = 1;
  26591. Texture.PLANAR_MODE = 2;
  26592. Texture.CUBIC_MODE = 3;
  26593. Texture.PROJECTION_MODE = 4;
  26594. Texture.SKYBOX_MODE = 5;
  26595. Texture.INVCUBIC_MODE = 6;
  26596. Texture.EQUIRECTANGULAR_MODE = 7;
  26597. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26598. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26599. Texture.CLAMP_ADDRESSMODE = 0;
  26600. Texture.WRAP_ADDRESSMODE = 1;
  26601. Texture.MIRROR_ADDRESSMODE = 2;
  26602. __decorate([
  26603. BABYLON.serialize()
  26604. ], Texture.prototype, "url", void 0);
  26605. __decorate([
  26606. BABYLON.serialize()
  26607. ], Texture.prototype, "uOffset", void 0);
  26608. __decorate([
  26609. BABYLON.serialize()
  26610. ], Texture.prototype, "vOffset", void 0);
  26611. __decorate([
  26612. BABYLON.serialize()
  26613. ], Texture.prototype, "uScale", void 0);
  26614. __decorate([
  26615. BABYLON.serialize()
  26616. ], Texture.prototype, "vScale", void 0);
  26617. __decorate([
  26618. BABYLON.serialize()
  26619. ], Texture.prototype, "uAng", void 0);
  26620. __decorate([
  26621. BABYLON.serialize()
  26622. ], Texture.prototype, "vAng", void 0);
  26623. __decorate([
  26624. BABYLON.serialize()
  26625. ], Texture.prototype, "wAng", void 0);
  26626. __decorate([
  26627. BABYLON.serialize()
  26628. ], Texture.prototype, "isBlocking", null);
  26629. return Texture;
  26630. }(BABYLON.BaseTexture));
  26631. BABYLON.Texture = Texture;
  26632. })(BABYLON || (BABYLON = {}));
  26633. //# sourceMappingURL=babylon.texture.js.map
  26634. var BABYLON;
  26635. (function (BABYLON) {
  26636. var _InstancesBatch = /** @class */ (function () {
  26637. function _InstancesBatch() {
  26638. this.mustReturn = false;
  26639. this.visibleInstances = new Array();
  26640. this.renderSelf = new Array();
  26641. }
  26642. return _InstancesBatch;
  26643. }());
  26644. BABYLON._InstancesBatch = _InstancesBatch;
  26645. var Mesh = /** @class */ (function (_super) {
  26646. __extends(Mesh, _super);
  26647. /**
  26648. * @constructor
  26649. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26650. * @param {Scene} scene The scene to add this mesh to.
  26651. * @param {Node} parent The parent of this mesh, if it has one
  26652. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26653. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26654. * When false, achieved by calling a clone(), also passing False.
  26655. * This will make creation of children, recursive.
  26656. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26657. */
  26658. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26659. if (scene === void 0) { scene = null; }
  26660. if (parent === void 0) { parent = null; }
  26661. if (source === void 0) { source = null; }
  26662. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26663. var _this = _super.call(this, name, scene) || this;
  26664. // Events
  26665. /**
  26666. * An event triggered before rendering the mesh
  26667. * @type {BABYLON.Observable}
  26668. */
  26669. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26670. /**
  26671. * An event triggered after rendering the mesh
  26672. * @type {BABYLON.Observable}
  26673. */
  26674. _this.onAfterRenderObservable = new BABYLON.Observable();
  26675. /**
  26676. * An event triggered before drawing the mesh
  26677. * @type {BABYLON.Observable}
  26678. */
  26679. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26680. // Members
  26681. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26682. _this.instances = new Array();
  26683. _this._LODLevels = new Array();
  26684. _this._visibleInstances = {};
  26685. _this._renderIdForInstances = new Array();
  26686. _this._batchCache = new _InstancesBatch();
  26687. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26688. // Use by builder only to know what orientation were the mesh build in.
  26689. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26690. _this.overrideMaterialSideOrientation = null;
  26691. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26692. // Will be used to save a source mesh reference, If any
  26693. _this._source = null;
  26694. scene = _this.getScene();
  26695. if (source) {
  26696. // Source mesh
  26697. _this._source = source;
  26698. // Geometry
  26699. if (source._geometry) {
  26700. source._geometry.applyToMesh(_this);
  26701. }
  26702. // Deep copy
  26703. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26704. // Metadata
  26705. if (source.metadata && source.metadata.clone) {
  26706. _this.metadata = source.metadata.clone();
  26707. }
  26708. else {
  26709. _this.metadata = source.metadata;
  26710. }
  26711. // Tags
  26712. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26713. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26714. }
  26715. // Parent
  26716. _this.parent = source.parent;
  26717. // Pivot
  26718. _this.setPivotMatrix(source.getPivotMatrix());
  26719. _this.id = name + "." + source.id;
  26720. // Material
  26721. _this.material = source.material;
  26722. var index;
  26723. if (!doNotCloneChildren) {
  26724. // Children
  26725. var directDescendants = source.getDescendants(true);
  26726. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26727. var child = directDescendants[index_1];
  26728. if (child.clone) {
  26729. child.clone(name + "." + child.name, _this);
  26730. }
  26731. }
  26732. }
  26733. // Physics clone
  26734. var physicsEngine = _this.getScene().getPhysicsEngine();
  26735. if (clonePhysicsImpostor && physicsEngine) {
  26736. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26737. if (impostor) {
  26738. _this.physicsImpostor = impostor.clone(_this);
  26739. }
  26740. }
  26741. // Particles
  26742. for (index = 0; index < scene.particleSystems.length; index++) {
  26743. var system = scene.particleSystems[index];
  26744. if (system.emitter === source) {
  26745. system.clone(system.name, _this);
  26746. }
  26747. }
  26748. _this.computeWorldMatrix(true);
  26749. }
  26750. // Parent
  26751. if (parent !== null) {
  26752. _this.parent = parent;
  26753. }
  26754. return _this;
  26755. }
  26756. Object.defineProperty(Mesh, "FRONTSIDE", {
  26757. /**
  26758. * Mesh side orientation : usually the external or front surface
  26759. */
  26760. get: function () {
  26761. return Mesh._FRONTSIDE;
  26762. },
  26763. enumerable: true,
  26764. configurable: true
  26765. });
  26766. Object.defineProperty(Mesh, "BACKSIDE", {
  26767. /**
  26768. * Mesh side orientation : usually the internal or back surface
  26769. */
  26770. get: function () {
  26771. return Mesh._BACKSIDE;
  26772. },
  26773. enumerable: true,
  26774. configurable: true
  26775. });
  26776. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26777. /**
  26778. * Mesh side orientation : both internal and external or front and back surfaces
  26779. */
  26780. get: function () {
  26781. return Mesh._DOUBLESIDE;
  26782. },
  26783. enumerable: true,
  26784. configurable: true
  26785. });
  26786. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26787. /**
  26788. * Mesh side orientation : by default, `FRONTSIDE`
  26789. */
  26790. get: function () {
  26791. return Mesh._DEFAULTSIDE;
  26792. },
  26793. enumerable: true,
  26794. configurable: true
  26795. });
  26796. Object.defineProperty(Mesh, "NO_CAP", {
  26797. /**
  26798. * Mesh cap setting : no cap
  26799. */
  26800. get: function () {
  26801. return Mesh._NO_CAP;
  26802. },
  26803. enumerable: true,
  26804. configurable: true
  26805. });
  26806. Object.defineProperty(Mesh, "CAP_START", {
  26807. /**
  26808. * Mesh cap setting : one cap at the beginning of the mesh
  26809. */
  26810. get: function () {
  26811. return Mesh._CAP_START;
  26812. },
  26813. enumerable: true,
  26814. configurable: true
  26815. });
  26816. Object.defineProperty(Mesh, "CAP_END", {
  26817. /**
  26818. * Mesh cap setting : one cap at the end of the mesh
  26819. */
  26820. get: function () {
  26821. return Mesh._CAP_END;
  26822. },
  26823. enumerable: true,
  26824. configurable: true
  26825. });
  26826. Object.defineProperty(Mesh, "CAP_ALL", {
  26827. /**
  26828. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26829. */
  26830. get: function () {
  26831. return Mesh._CAP_ALL;
  26832. },
  26833. enumerable: true,
  26834. configurable: true
  26835. });
  26836. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26837. set: function (callback) {
  26838. if (this._onBeforeDrawObserver) {
  26839. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26840. }
  26841. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26842. },
  26843. enumerable: true,
  26844. configurable: true
  26845. });
  26846. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26847. get: function () {
  26848. return this._morphTargetManager;
  26849. },
  26850. set: function (value) {
  26851. if (this._morphTargetManager === value) {
  26852. return;
  26853. }
  26854. this._morphTargetManager = value;
  26855. this._syncGeometryWithMorphTargetManager();
  26856. },
  26857. enumerable: true,
  26858. configurable: true
  26859. });
  26860. Object.defineProperty(Mesh.prototype, "source", {
  26861. get: function () {
  26862. return this._source;
  26863. },
  26864. enumerable: true,
  26865. configurable: true
  26866. });
  26867. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26868. get: function () {
  26869. return this._unIndexed;
  26870. },
  26871. set: function (value) {
  26872. if (this._unIndexed !== value) {
  26873. this._unIndexed = value;
  26874. this._markSubMeshesAsAttributesDirty();
  26875. }
  26876. },
  26877. enumerable: true,
  26878. configurable: true
  26879. });
  26880. // Methods
  26881. /**
  26882. * Returns the string "Mesh".
  26883. */
  26884. Mesh.prototype.getClassName = function () {
  26885. return "Mesh";
  26886. };
  26887. /**
  26888. * Returns a string.
  26889. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26890. */
  26891. Mesh.prototype.toString = function (fullDetails) {
  26892. var ret = _super.prototype.toString.call(this, fullDetails);
  26893. ret += ", n vertices: " + this.getTotalVertices();
  26894. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26895. if (this.animations) {
  26896. for (var i = 0; i < this.animations.length; i++) {
  26897. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26898. }
  26899. }
  26900. if (fullDetails) {
  26901. if (this._geometry) {
  26902. var ib = this.getIndices();
  26903. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26904. if (vb && ib) {
  26905. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26906. }
  26907. }
  26908. else {
  26909. ret += ", flat shading: UNKNOWN";
  26910. }
  26911. }
  26912. return ret;
  26913. };
  26914. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26915. /**
  26916. * True if the mesh has some Levels Of Details (LOD).
  26917. * Returns a boolean.
  26918. */
  26919. get: function () {
  26920. return this._LODLevels.length > 0;
  26921. },
  26922. enumerable: true,
  26923. configurable: true
  26924. });
  26925. /**
  26926. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26927. * @returns an array of {BABYLON.MeshLODLevel}
  26928. */
  26929. Mesh.prototype.getLODLevels = function () {
  26930. return this._LODLevels;
  26931. };
  26932. Mesh.prototype._sortLODLevels = function () {
  26933. this._LODLevels.sort(function (a, b) {
  26934. if (a.distance < b.distance) {
  26935. return 1;
  26936. }
  26937. if (a.distance > b.distance) {
  26938. return -1;
  26939. }
  26940. return 0;
  26941. });
  26942. };
  26943. /**
  26944. * Add a mesh as LOD level triggered at the given distance.
  26945. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26946. * @param {number} distance The distance from the center of the object to show this level
  26947. * @param {Mesh} mesh The mesh to be added as LOD level
  26948. * @return {Mesh} This mesh (for chaining)
  26949. */
  26950. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26951. if (mesh && mesh._masterMesh) {
  26952. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26953. return this;
  26954. }
  26955. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26956. this._LODLevels.push(level);
  26957. if (mesh) {
  26958. mesh._masterMesh = this;
  26959. }
  26960. this._sortLODLevels();
  26961. return this;
  26962. };
  26963. /**
  26964. * Returns the LOD level mesh at the passed distance or null if not found.
  26965. * It is related to the method `addLODLevel(distance, mesh)`.
  26966. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26967. * Returns an object Mesh or `null`.
  26968. */
  26969. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26970. for (var index = 0; index < this._LODLevels.length; index++) {
  26971. var level = this._LODLevels[index];
  26972. if (level.distance === distance) {
  26973. return level.mesh;
  26974. }
  26975. }
  26976. return null;
  26977. };
  26978. /**
  26979. * Remove a mesh from the LOD array
  26980. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26981. * @param {Mesh} mesh The mesh to be removed.
  26982. * @return {Mesh} This mesh (for chaining)
  26983. */
  26984. Mesh.prototype.removeLODLevel = function (mesh) {
  26985. for (var index = 0; index < this._LODLevels.length; index++) {
  26986. if (this._LODLevels[index].mesh === mesh) {
  26987. this._LODLevels.splice(index, 1);
  26988. if (mesh) {
  26989. mesh._masterMesh = null;
  26990. }
  26991. }
  26992. }
  26993. this._sortLODLevels();
  26994. return this;
  26995. };
  26996. /**
  26997. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26998. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26999. */
  27000. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27001. if (!this._LODLevels || this._LODLevels.length === 0) {
  27002. return this;
  27003. }
  27004. var bSphere;
  27005. if (boundingSphere) {
  27006. bSphere = boundingSphere;
  27007. }
  27008. else {
  27009. var boundingInfo = this.getBoundingInfo();
  27010. bSphere = boundingInfo.boundingSphere;
  27011. }
  27012. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27013. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27014. if (this.onLODLevelSelection) {
  27015. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27016. }
  27017. return this;
  27018. }
  27019. for (var index = 0; index < this._LODLevels.length; index++) {
  27020. var level = this._LODLevels[index];
  27021. if (level.distance < distanceToCamera) {
  27022. if (level.mesh) {
  27023. level.mesh._preActivate();
  27024. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27025. }
  27026. if (this.onLODLevelSelection) {
  27027. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27028. }
  27029. return level.mesh;
  27030. }
  27031. }
  27032. if (this.onLODLevelSelection) {
  27033. this.onLODLevelSelection(distanceToCamera, this, this);
  27034. }
  27035. return this;
  27036. };
  27037. Object.defineProperty(Mesh.prototype, "geometry", {
  27038. /**
  27039. * Returns the mesh internal Geometry object.
  27040. */
  27041. get: function () {
  27042. return this._geometry;
  27043. },
  27044. enumerable: true,
  27045. configurable: true
  27046. });
  27047. /**
  27048. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27049. */
  27050. Mesh.prototype.getTotalVertices = function () {
  27051. if (this._geometry === null || this._geometry === undefined) {
  27052. return 0;
  27053. }
  27054. return this._geometry.getTotalVertices();
  27055. };
  27056. /**
  27057. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27058. * 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.
  27059. * You can force the copy with forceCopy === true
  27060. * Returns null if the mesh has no geometry or no vertex buffer.
  27061. * Possible `kind` values :
  27062. * - BABYLON.VertexBuffer.PositionKind
  27063. * - BABYLON.VertexBuffer.UVKind
  27064. * - BABYLON.VertexBuffer.UV2Kind
  27065. * - BABYLON.VertexBuffer.UV3Kind
  27066. * - BABYLON.VertexBuffer.UV4Kind
  27067. * - BABYLON.VertexBuffer.UV5Kind
  27068. * - BABYLON.VertexBuffer.UV6Kind
  27069. * - BABYLON.VertexBuffer.ColorKind
  27070. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27071. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27072. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27073. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27074. */
  27075. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27076. if (!this._geometry) {
  27077. return null;
  27078. }
  27079. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27080. };
  27081. /**
  27082. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27083. * Returns `null` if the mesh has no geometry.
  27084. * Possible `kind` values :
  27085. * - BABYLON.VertexBuffer.PositionKind
  27086. * - BABYLON.VertexBuffer.UVKind
  27087. * - BABYLON.VertexBuffer.UV2Kind
  27088. * - BABYLON.VertexBuffer.UV3Kind
  27089. * - BABYLON.VertexBuffer.UV4Kind
  27090. * - BABYLON.VertexBuffer.UV5Kind
  27091. * - BABYLON.VertexBuffer.UV6Kind
  27092. * - BABYLON.VertexBuffer.ColorKind
  27093. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27094. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27095. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27096. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27097. */
  27098. Mesh.prototype.getVertexBuffer = function (kind) {
  27099. if (!this._geometry) {
  27100. return null;
  27101. }
  27102. return this._geometry.getVertexBuffer(kind);
  27103. };
  27104. /**
  27105. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27106. * Possible `kind` values :
  27107. * - BABYLON.VertexBuffer.PositionKind
  27108. * - BABYLON.VertexBuffer.UVKind
  27109. * - BABYLON.VertexBuffer.UV2Kind
  27110. * - BABYLON.VertexBuffer.UV3Kind
  27111. * - BABYLON.VertexBuffer.UV4Kind
  27112. * - BABYLON.VertexBuffer.UV5Kind
  27113. * - BABYLON.VertexBuffer.UV6Kind
  27114. * - BABYLON.VertexBuffer.ColorKind
  27115. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27116. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27117. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27118. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27119. */
  27120. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27121. if (!this._geometry) {
  27122. if (this._delayInfo) {
  27123. return this._delayInfo.indexOf(kind) !== -1;
  27124. }
  27125. return false;
  27126. }
  27127. return this._geometry.isVerticesDataPresent(kind);
  27128. };
  27129. /**
  27130. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27131. * Possible `kind` values :
  27132. * - BABYLON.VertexBuffer.PositionKind
  27133. * - BABYLON.VertexBuffer.UVKind
  27134. * - BABYLON.VertexBuffer.UV2Kind
  27135. * - BABYLON.VertexBuffer.UV3Kind
  27136. * - BABYLON.VertexBuffer.UV4Kind
  27137. * - BABYLON.VertexBuffer.UV5Kind
  27138. * - BABYLON.VertexBuffer.UV6Kind
  27139. * - BABYLON.VertexBuffer.ColorKind
  27140. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27141. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27142. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27143. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27144. */
  27145. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27146. if (!this._geometry) {
  27147. if (this._delayInfo) {
  27148. return this._delayInfo.indexOf(kind) !== -1;
  27149. }
  27150. return false;
  27151. }
  27152. return this._geometry.isVertexBufferUpdatable(kind);
  27153. };
  27154. /**
  27155. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27156. * Possible `kind` values :
  27157. * - BABYLON.VertexBuffer.PositionKind
  27158. * - BABYLON.VertexBuffer.UVKind
  27159. * - BABYLON.VertexBuffer.UV2Kind
  27160. * - BABYLON.VertexBuffer.UV3Kind
  27161. * - BABYLON.VertexBuffer.UV4Kind
  27162. * - BABYLON.VertexBuffer.UV5Kind
  27163. * - BABYLON.VertexBuffer.UV6Kind
  27164. * - BABYLON.VertexBuffer.ColorKind
  27165. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27166. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27167. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27168. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27169. */
  27170. Mesh.prototype.getVerticesDataKinds = function () {
  27171. if (!this._geometry) {
  27172. var result = new Array();
  27173. if (this._delayInfo) {
  27174. this._delayInfo.forEach(function (kind, index, array) {
  27175. result.push(kind);
  27176. });
  27177. }
  27178. return result;
  27179. }
  27180. return this._geometry.getVerticesDataKinds();
  27181. };
  27182. /**
  27183. * Returns a positive integer : the total number of indices in this mesh geometry.
  27184. * Returns zero if the mesh has no geometry.
  27185. */
  27186. Mesh.prototype.getTotalIndices = function () {
  27187. if (!this._geometry) {
  27188. return 0;
  27189. }
  27190. return this._geometry.getTotalIndices();
  27191. };
  27192. /**
  27193. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27194. * 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.
  27195. * Returns an empty array if the mesh has no geometry.
  27196. */
  27197. Mesh.prototype.getIndices = function (copyWhenShared) {
  27198. if (!this._geometry) {
  27199. return [];
  27200. }
  27201. return this._geometry.getIndices(copyWhenShared);
  27202. };
  27203. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27204. get: function () {
  27205. return this._masterMesh !== null && this._masterMesh !== undefined;
  27206. },
  27207. enumerable: true,
  27208. configurable: true
  27209. });
  27210. /**
  27211. * Determine if the current mesh is ready to be rendered
  27212. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27213. * @returns true if all associated assets are ready (material, textures, shaders)
  27214. */
  27215. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27216. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27217. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27218. return false;
  27219. }
  27220. if (!_super.prototype.isReady.call(this)) {
  27221. return false;
  27222. }
  27223. if (!this.subMeshes || this.subMeshes.length === 0) {
  27224. return true;
  27225. }
  27226. var engine = this.getEngine();
  27227. var scene = this.getScene();
  27228. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27229. this.computeWorldMatrix();
  27230. var mat = this.material || scene.defaultMaterial;
  27231. if (mat) {
  27232. if (mat.storeEffectOnSubMeshes) {
  27233. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27234. var subMesh = _a[_i];
  27235. var effectiveMaterial = subMesh.getMaterial();
  27236. if (effectiveMaterial) {
  27237. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27238. return false;
  27239. }
  27240. }
  27241. }
  27242. }
  27243. else {
  27244. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27245. return false;
  27246. }
  27247. }
  27248. }
  27249. // Shadows
  27250. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27251. var light = _c[_b];
  27252. var generator = light.getShadowGenerator();
  27253. if (generator) {
  27254. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27255. var subMesh = _e[_d];
  27256. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27257. return false;
  27258. }
  27259. }
  27260. }
  27261. }
  27262. // LOD
  27263. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27264. var lod = _g[_f];
  27265. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27266. return false;
  27267. }
  27268. }
  27269. return true;
  27270. };
  27271. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27272. /**
  27273. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27274. * This property is pertinent only for updatable parametric shapes.
  27275. */
  27276. get: function () {
  27277. return this._areNormalsFrozen;
  27278. },
  27279. enumerable: true,
  27280. configurable: true
  27281. });
  27282. /**
  27283. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27284. * It has no effect at all on other shapes.
  27285. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27286. * Returns the Mesh.
  27287. */
  27288. Mesh.prototype.freezeNormals = function () {
  27289. this._areNormalsFrozen = true;
  27290. return this;
  27291. };
  27292. /**
  27293. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27294. * It has no effect at all on other shapes.
  27295. * It reactivates the mesh normals computation if it was previously frozen.
  27296. * Returns the Mesh.
  27297. */
  27298. Mesh.prototype.unfreezeNormals = function () {
  27299. this._areNormalsFrozen = false;
  27300. return this;
  27301. };
  27302. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27303. /**
  27304. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27305. */
  27306. set: function (count) {
  27307. this._overridenInstanceCount = count;
  27308. },
  27309. enumerable: true,
  27310. configurable: true
  27311. });
  27312. // Methods
  27313. Mesh.prototype._preActivate = function () {
  27314. var sceneRenderId = this.getScene().getRenderId();
  27315. if (this._preActivateId === sceneRenderId) {
  27316. return this;
  27317. }
  27318. this._preActivateId = sceneRenderId;
  27319. this._visibleInstances = null;
  27320. return this;
  27321. };
  27322. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27323. if (this._visibleInstances) {
  27324. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27325. }
  27326. return this;
  27327. };
  27328. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27329. if (!this._visibleInstances) {
  27330. this._visibleInstances = {};
  27331. this._visibleInstances.defaultRenderId = renderId;
  27332. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27333. }
  27334. if (!this._visibleInstances[renderId]) {
  27335. this._visibleInstances[renderId] = new Array();
  27336. }
  27337. this._visibleInstances[renderId].push(instance);
  27338. return this;
  27339. };
  27340. /**
  27341. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27342. * This means the mesh underlying bounding box and sphere are recomputed.
  27343. * Returns the Mesh.
  27344. */
  27345. Mesh.prototype.refreshBoundingInfo = function () {
  27346. return this._refreshBoundingInfo(false);
  27347. };
  27348. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27349. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27350. return this;
  27351. }
  27352. var data = this._getPositionData(applySkeleton);
  27353. if (data) {
  27354. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27355. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27356. }
  27357. if (this.subMeshes) {
  27358. for (var index = 0; index < this.subMeshes.length; index++) {
  27359. this.subMeshes[index].refreshBoundingInfo();
  27360. }
  27361. }
  27362. this._updateBoundingInfo();
  27363. return this;
  27364. };
  27365. Mesh.prototype._getPositionData = function (applySkeleton) {
  27366. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27367. if (data && applySkeleton && this.skeleton) {
  27368. data = BABYLON.Tools.Slice(data);
  27369. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27370. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27371. if (matricesWeightsData && matricesIndicesData) {
  27372. var needExtras = this.numBoneInfluencers > 4;
  27373. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27374. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27375. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27376. var tempVector = BABYLON.Tmp.Vector3[0];
  27377. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27378. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27379. var matWeightIdx = 0;
  27380. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27381. finalMatrix.reset();
  27382. var inf;
  27383. var weight;
  27384. for (inf = 0; inf < 4; inf++) {
  27385. weight = matricesWeightsData[matWeightIdx + inf];
  27386. if (weight <= 0)
  27387. break;
  27388. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27389. finalMatrix.addToSelf(tempMatrix);
  27390. }
  27391. if (needExtras) {
  27392. for (inf = 0; inf < 4; inf++) {
  27393. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27394. if (weight <= 0)
  27395. break;
  27396. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27397. finalMatrix.addToSelf(tempMatrix);
  27398. }
  27399. }
  27400. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27401. tempVector.toArray(data, index);
  27402. }
  27403. }
  27404. }
  27405. return data;
  27406. };
  27407. Mesh.prototype._createGlobalSubMesh = function (force) {
  27408. var totalVertices = this.getTotalVertices();
  27409. if (!totalVertices || !this.getIndices()) {
  27410. return null;
  27411. }
  27412. // Check if we need to recreate the submeshes
  27413. if (this.subMeshes && this.subMeshes.length > 0) {
  27414. var ib = this.getIndices();
  27415. if (!ib) {
  27416. return null;
  27417. }
  27418. var totalIndices = ib.length;
  27419. var needToRecreate = false;
  27420. if (force) {
  27421. needToRecreate = true;
  27422. }
  27423. else {
  27424. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27425. var submesh = _a[_i];
  27426. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27427. needToRecreate = true;
  27428. break;
  27429. }
  27430. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27431. needToRecreate = true;
  27432. break;
  27433. }
  27434. }
  27435. }
  27436. if (!needToRecreate) {
  27437. return this.subMeshes[0];
  27438. }
  27439. }
  27440. this.releaseSubMeshes();
  27441. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27442. };
  27443. Mesh.prototype.subdivide = function (count) {
  27444. if (count < 1) {
  27445. return;
  27446. }
  27447. var totalIndices = this.getTotalIndices();
  27448. var subdivisionSize = (totalIndices / count) | 0;
  27449. var offset = 0;
  27450. // Ensure that subdivisionSize is a multiple of 3
  27451. while (subdivisionSize % 3 !== 0) {
  27452. subdivisionSize++;
  27453. }
  27454. this.releaseSubMeshes();
  27455. for (var index = 0; index < count; index++) {
  27456. if (offset >= totalIndices) {
  27457. break;
  27458. }
  27459. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27460. offset += subdivisionSize;
  27461. }
  27462. this.synchronizeInstances();
  27463. };
  27464. /**
  27465. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27466. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27467. * The `data` are either a numeric array either a Float32Array.
  27468. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27469. * 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).
  27470. * Note that a new underlying VertexBuffer object is created each call.
  27471. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27472. *
  27473. * Possible `kind` values :
  27474. * - BABYLON.VertexBuffer.PositionKind
  27475. * - BABYLON.VertexBuffer.UVKind
  27476. * - BABYLON.VertexBuffer.UV2Kind
  27477. * - BABYLON.VertexBuffer.UV3Kind
  27478. * - BABYLON.VertexBuffer.UV4Kind
  27479. * - BABYLON.VertexBuffer.UV5Kind
  27480. * - BABYLON.VertexBuffer.UV6Kind
  27481. * - BABYLON.VertexBuffer.ColorKind
  27482. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27483. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27484. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27485. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27486. *
  27487. * Returns the Mesh.
  27488. */
  27489. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27490. if (updatable === void 0) { updatable = false; }
  27491. if (!this._geometry) {
  27492. var vertexData = new BABYLON.VertexData();
  27493. vertexData.set(data, kind);
  27494. var scene = this.getScene();
  27495. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27496. }
  27497. else {
  27498. this._geometry.setVerticesData(kind, data, updatable, stride);
  27499. }
  27500. return this;
  27501. };
  27502. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27503. if (updatable === void 0) { updatable = true; }
  27504. var vb = this.getVertexBuffer(kind);
  27505. if (!vb || vb.isUpdatable() === updatable) {
  27506. return;
  27507. }
  27508. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27509. };
  27510. /**
  27511. * Sets the mesh VertexBuffer.
  27512. * Returns the Mesh.
  27513. */
  27514. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27515. if (!this._geometry) {
  27516. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27517. }
  27518. this._geometry.setVerticesBuffer(buffer);
  27519. return this;
  27520. };
  27521. /**
  27522. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27523. * If the mesh has no geometry, it is simply returned as it is.
  27524. * The `data` are either a numeric array either a Float32Array.
  27525. * No new underlying VertexBuffer object is created.
  27526. * 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.
  27527. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27528. *
  27529. * Possible `kind` values :
  27530. * - BABYLON.VertexBuffer.PositionKind
  27531. * - BABYLON.VertexBuffer.UVKind
  27532. * - BABYLON.VertexBuffer.UV2Kind
  27533. * - BABYLON.VertexBuffer.UV3Kind
  27534. * - BABYLON.VertexBuffer.UV4Kind
  27535. * - BABYLON.VertexBuffer.UV5Kind
  27536. * - BABYLON.VertexBuffer.UV6Kind
  27537. * - BABYLON.VertexBuffer.ColorKind
  27538. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27539. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27540. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27541. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27542. *
  27543. * Returns the Mesh.
  27544. */
  27545. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27546. if (!this._geometry) {
  27547. return this;
  27548. }
  27549. if (!makeItUnique) {
  27550. this._geometry.updateVerticesData(kind, data, updateExtends);
  27551. }
  27552. else {
  27553. this.makeGeometryUnique();
  27554. this.updateVerticesData(kind, data, updateExtends, false);
  27555. }
  27556. return this;
  27557. };
  27558. /**
  27559. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27560. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27561. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27562. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27563. * Returns the Mesh.
  27564. */
  27565. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27566. if (computeNormals === void 0) { computeNormals = true; }
  27567. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27568. if (!positions) {
  27569. return this;
  27570. }
  27571. positionFunction(positions);
  27572. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27573. if (computeNormals) {
  27574. var indices = this.getIndices();
  27575. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27576. if (!normals) {
  27577. return this;
  27578. }
  27579. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27580. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27581. }
  27582. return this;
  27583. };
  27584. /**
  27585. * Creates a un-shared specific occurence of the geometry for the mesh.
  27586. * Returns the Mesh.
  27587. */
  27588. Mesh.prototype.makeGeometryUnique = function () {
  27589. if (!this._geometry) {
  27590. return this;
  27591. }
  27592. var oldGeometry = this._geometry;
  27593. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27594. oldGeometry.releaseForMesh(this, true);
  27595. geometry.applyToMesh(this);
  27596. return this;
  27597. };
  27598. /**
  27599. * Sets the mesh indices.
  27600. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27601. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27602. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27603. * This method creates a new index buffer each call.
  27604. * Returns the Mesh.
  27605. */
  27606. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27607. if (totalVertices === void 0) { totalVertices = null; }
  27608. if (updatable === void 0) { updatable = false; }
  27609. if (!this._geometry) {
  27610. var vertexData = new BABYLON.VertexData();
  27611. vertexData.indices = indices;
  27612. var scene = this.getScene();
  27613. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27614. }
  27615. else {
  27616. this._geometry.setIndices(indices, totalVertices, updatable);
  27617. }
  27618. return this;
  27619. };
  27620. /**
  27621. * Update the current index buffer
  27622. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27623. * Returns the Mesh.
  27624. */
  27625. Mesh.prototype.updateIndices = function (indices, offset) {
  27626. if (!this._geometry) {
  27627. return this;
  27628. }
  27629. this._geometry.updateIndices(indices, offset);
  27630. return this;
  27631. };
  27632. /**
  27633. * Invert the geometry to move from a right handed system to a left handed one.
  27634. * Returns the Mesh.
  27635. */
  27636. Mesh.prototype.toLeftHanded = function () {
  27637. if (!this._geometry) {
  27638. return this;
  27639. }
  27640. this._geometry.toLeftHanded();
  27641. return this;
  27642. };
  27643. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27644. if (!this._geometry) {
  27645. return this;
  27646. }
  27647. var engine = this.getScene().getEngine();
  27648. // Wireframe
  27649. var indexToBind;
  27650. if (this._unIndexed) {
  27651. indexToBind = null;
  27652. }
  27653. else {
  27654. switch (fillMode) {
  27655. case BABYLON.Material.PointFillMode:
  27656. indexToBind = null;
  27657. break;
  27658. case BABYLON.Material.WireFrameFillMode:
  27659. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27660. break;
  27661. default:
  27662. case BABYLON.Material.TriangleFillMode:
  27663. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27664. break;
  27665. }
  27666. }
  27667. // VBOs
  27668. this._geometry._bind(effect, indexToBind);
  27669. return this;
  27670. };
  27671. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27672. if (alternate === void 0) { alternate = false; }
  27673. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27674. return this;
  27675. }
  27676. this.onBeforeDrawObservable.notifyObservers(this);
  27677. var scene = this.getScene();
  27678. var engine = scene.getEngine();
  27679. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27680. // or triangles as points
  27681. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27682. }
  27683. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27684. // Triangles as wireframe
  27685. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27686. }
  27687. else {
  27688. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27689. }
  27690. if (scene._isAlternateRenderingEnabled && !alternate) {
  27691. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27692. if (!effect || !scene.activeCamera) {
  27693. return this;
  27694. }
  27695. scene._switchToAlternateCameraConfiguration(true);
  27696. this._effectiveMaterial.bindView(effect);
  27697. this._effectiveMaterial.bindViewProjection(effect);
  27698. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27699. this._draw(subMesh, fillMode, instancesCount, true);
  27700. engine.setViewport(scene.activeCamera.viewport);
  27701. scene._switchToAlternateCameraConfiguration(false);
  27702. this._effectiveMaterial.bindView(effect);
  27703. this._effectiveMaterial.bindViewProjection(effect);
  27704. }
  27705. return this;
  27706. };
  27707. /**
  27708. * Registers for this mesh a javascript function called just before the rendering process.
  27709. * This function is passed the current mesh.
  27710. * Return the Mesh.
  27711. */
  27712. Mesh.prototype.registerBeforeRender = function (func) {
  27713. this.onBeforeRenderObservable.add(func);
  27714. return this;
  27715. };
  27716. /**
  27717. * Disposes a previously registered javascript function called before the rendering.
  27718. * This function is passed the current mesh.
  27719. * Returns the Mesh.
  27720. */
  27721. Mesh.prototype.unregisterBeforeRender = function (func) {
  27722. this.onBeforeRenderObservable.removeCallback(func);
  27723. return this;
  27724. };
  27725. /**
  27726. * Registers for this mesh a javascript function called just after the rendering is complete.
  27727. * This function is passed the current mesh.
  27728. * Returns the Mesh.
  27729. */
  27730. Mesh.prototype.registerAfterRender = function (func) {
  27731. this.onAfterRenderObservable.add(func);
  27732. return this;
  27733. };
  27734. /**
  27735. * Disposes a previously registered javascript function called after the rendering.
  27736. * This function is passed the current mesh.
  27737. * Return the Mesh.
  27738. */
  27739. Mesh.prototype.unregisterAfterRender = function (func) {
  27740. this.onAfterRenderObservable.removeCallback(func);
  27741. return this;
  27742. };
  27743. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27744. var scene = this.getScene();
  27745. this._batchCache.mustReturn = false;
  27746. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27747. this._batchCache.visibleInstances[subMeshId] = null;
  27748. if (this._visibleInstances) {
  27749. var currentRenderId = scene.getRenderId();
  27750. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27751. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27752. var selfRenderId = this._renderId;
  27753. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27754. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27755. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27756. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27757. }
  27758. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27759. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27760. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27761. this._batchCache.mustReturn = true;
  27762. return this._batchCache;
  27763. }
  27764. if (currentRenderId !== selfRenderId) {
  27765. this._batchCache.renderSelf[subMeshId] = false;
  27766. }
  27767. }
  27768. this._renderIdForInstances[subMeshId] = currentRenderId;
  27769. }
  27770. return this._batchCache;
  27771. };
  27772. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27773. var visibleInstances = batch.visibleInstances[subMesh._id];
  27774. if (!visibleInstances) {
  27775. return this;
  27776. }
  27777. var matricesCount = visibleInstances.length + 1;
  27778. var bufferSize = matricesCount * 16 * 4;
  27779. var currentInstancesBufferSize = this._instancesBufferSize;
  27780. var instancesBuffer = this._instancesBuffer;
  27781. while (this._instancesBufferSize < bufferSize) {
  27782. this._instancesBufferSize *= 2;
  27783. }
  27784. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27785. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27786. }
  27787. var offset = 0;
  27788. var instancesCount = 0;
  27789. var world = this.getWorldMatrix();
  27790. if (batch.renderSelf[subMesh._id]) {
  27791. world.copyToArray(this._instancesData, offset);
  27792. offset += 16;
  27793. instancesCount++;
  27794. }
  27795. if (visibleInstances) {
  27796. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27797. var instance = visibleInstances[instanceIndex];
  27798. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27799. offset += 16;
  27800. instancesCount++;
  27801. }
  27802. }
  27803. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27804. if (instancesBuffer) {
  27805. instancesBuffer.dispose();
  27806. }
  27807. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27808. this._instancesBuffer = instancesBuffer;
  27809. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27810. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27811. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27812. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27813. }
  27814. else {
  27815. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27816. }
  27817. this._bind(subMesh, effect, fillMode);
  27818. this._draw(subMesh, fillMode, instancesCount);
  27819. engine.unbindInstanceAttributes();
  27820. return this;
  27821. };
  27822. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27823. var scene = this.getScene();
  27824. var engine = scene.getEngine();
  27825. if (hardwareInstancedRendering) {
  27826. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27827. }
  27828. else {
  27829. if (batch.renderSelf[subMesh._id]) {
  27830. // Draw
  27831. if (onBeforeDraw) {
  27832. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27833. }
  27834. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27835. }
  27836. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27837. if (visibleInstancesForSubMesh) {
  27838. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27839. var instance = visibleInstancesForSubMesh[instanceIndex];
  27840. // World
  27841. var world = instance.getWorldMatrix();
  27842. if (onBeforeDraw) {
  27843. onBeforeDraw(true, world, effectiveMaterial);
  27844. }
  27845. // Draw
  27846. this._draw(subMesh, fillMode);
  27847. }
  27848. }
  27849. }
  27850. return this;
  27851. };
  27852. /**
  27853. * Triggers the draw call for the mesh.
  27854. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27855. * Returns the Mesh.
  27856. */
  27857. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27858. this.checkOcclusionQuery();
  27859. if (this._isOccluded) {
  27860. return this;
  27861. }
  27862. var scene = this.getScene();
  27863. // Managing instances
  27864. var batch = this._getInstancesRenderList(subMesh._id);
  27865. if (batch.mustReturn) {
  27866. return this;
  27867. }
  27868. // Checking geometry state
  27869. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27870. return this;
  27871. }
  27872. this.onBeforeRenderObservable.notifyObservers(this);
  27873. var engine = scene.getEngine();
  27874. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27875. // Material
  27876. var material = subMesh.getMaterial();
  27877. if (!material) {
  27878. return this;
  27879. }
  27880. this._effectiveMaterial = material;
  27881. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27882. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27883. return this;
  27884. }
  27885. }
  27886. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27887. return this;
  27888. }
  27889. // Alpha mode
  27890. if (enableAlphaMode) {
  27891. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27892. }
  27893. // Outline - step 1
  27894. var savedDepthWrite = engine.getDepthWrite();
  27895. if (this.renderOutline) {
  27896. engine.setDepthWrite(false);
  27897. scene.getOutlineRenderer().render(subMesh, batch);
  27898. engine.setDepthWrite(savedDepthWrite);
  27899. }
  27900. var effect;
  27901. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27902. effect = subMesh.effect;
  27903. }
  27904. else {
  27905. effect = this._effectiveMaterial.getEffect();
  27906. }
  27907. if (!effect) {
  27908. return this;
  27909. }
  27910. var sideOrientation = this.overrideMaterialSideOrientation;
  27911. if (sideOrientation == null) {
  27912. sideOrientation = this._effectiveMaterial.sideOrientation;
  27913. if (this._getWorldMatrixDeterminant() < 0) {
  27914. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27915. }
  27916. }
  27917. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27918. if (this._effectiveMaterial.forceDepthWrite) {
  27919. engine.setDepthWrite(true);
  27920. }
  27921. // Bind
  27922. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27923. if (!hardwareInstancedRendering) {
  27924. this._bind(subMesh, effect, fillMode);
  27925. }
  27926. var world = this.getWorldMatrix();
  27927. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27928. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27929. }
  27930. else {
  27931. this._effectiveMaterial.bind(world, this);
  27932. }
  27933. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27934. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27935. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27936. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27937. }
  27938. // Draw
  27939. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27940. // Unbind
  27941. this._effectiveMaterial.unbind();
  27942. // Outline - step 2
  27943. if (this.renderOutline && savedDepthWrite) {
  27944. engine.setDepthWrite(true);
  27945. engine.setColorWrite(false);
  27946. scene.getOutlineRenderer().render(subMesh, batch);
  27947. engine.setColorWrite(true);
  27948. }
  27949. // Overlay
  27950. if (this.renderOverlay) {
  27951. var currentMode = engine.getAlphaMode();
  27952. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27953. scene.getOutlineRenderer().render(subMesh, batch, true);
  27954. engine.setAlphaMode(currentMode);
  27955. }
  27956. this.onAfterRenderObservable.notifyObservers(this);
  27957. return this;
  27958. };
  27959. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27960. if (isInstance && effectiveMaterial) {
  27961. effectiveMaterial.bindOnlyWorldMatrix(world);
  27962. }
  27963. };
  27964. /**
  27965. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27966. */
  27967. Mesh.prototype.getEmittedParticleSystems = function () {
  27968. var results = new Array();
  27969. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27970. var particleSystem = this.getScene().particleSystems[index];
  27971. if (particleSystem.emitter === this) {
  27972. results.push(particleSystem);
  27973. }
  27974. }
  27975. return results;
  27976. };
  27977. /**
  27978. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27979. */
  27980. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27981. var results = new Array();
  27982. var descendants = this.getDescendants();
  27983. descendants.push(this);
  27984. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27985. var particleSystem = this.getScene().particleSystems[index];
  27986. var emitter = particleSystem.emitter;
  27987. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27988. results.push(particleSystem);
  27989. }
  27990. }
  27991. return results;
  27992. };
  27993. Mesh.prototype._checkDelayState = function () {
  27994. var scene = this.getScene();
  27995. if (this._geometry) {
  27996. this._geometry.load(scene);
  27997. }
  27998. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28000. this._queueLoad(scene);
  28001. }
  28002. return this;
  28003. };
  28004. Mesh.prototype._queueLoad = function (scene) {
  28005. var _this = this;
  28006. scene._addPendingData(this);
  28007. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28008. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28009. if (data instanceof ArrayBuffer) {
  28010. _this._delayLoadingFunction(data, _this);
  28011. }
  28012. else {
  28013. _this._delayLoadingFunction(JSON.parse(data), _this);
  28014. }
  28015. _this.instances.forEach(function (instance) {
  28016. instance._syncSubMeshes();
  28017. });
  28018. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28019. scene._removePendingData(_this);
  28020. }, function () { }, scene.database, getBinaryData);
  28021. return this;
  28022. };
  28023. /**
  28024. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28025. */
  28026. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28027. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28028. return false;
  28029. }
  28030. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28031. return false;
  28032. }
  28033. this._checkDelayState();
  28034. return true;
  28035. };
  28036. /**
  28037. * Sets the mesh material by the material or multiMaterial `id` property.
  28038. * The material `id` is a string identifying the material or the multiMaterial.
  28039. * This method returns the Mesh.
  28040. */
  28041. Mesh.prototype.setMaterialByID = function (id) {
  28042. var materials = this.getScene().materials;
  28043. var index;
  28044. for (index = materials.length - 1; index > -1; index--) {
  28045. if (materials[index].id === id) {
  28046. this.material = materials[index];
  28047. return this;
  28048. }
  28049. }
  28050. // Multi
  28051. var multiMaterials = this.getScene().multiMaterials;
  28052. for (index = multiMaterials.length - 1; index > -1; index--) {
  28053. if (multiMaterials[index].id === id) {
  28054. this.material = multiMaterials[index];
  28055. return this;
  28056. }
  28057. }
  28058. return this;
  28059. };
  28060. /**
  28061. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28062. */
  28063. Mesh.prototype.getAnimatables = function () {
  28064. var results = new Array();
  28065. if (this.material) {
  28066. results.push(this.material);
  28067. }
  28068. if (this.skeleton) {
  28069. results.push(this.skeleton);
  28070. }
  28071. return results;
  28072. };
  28073. /**
  28074. * Modifies the mesh geometry according to the passed transformation matrix.
  28075. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28076. * The mesh normals are modified accordingly the same transformation.
  28077. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28078. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28079. * Returns the Mesh.
  28080. */
  28081. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28082. // Position
  28083. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28084. return this;
  28085. }
  28086. var submeshes = this.subMeshes.splice(0);
  28087. this._resetPointsArrayCache();
  28088. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28089. var temp = new Array();
  28090. var index;
  28091. for (index = 0; index < data.length; index += 3) {
  28092. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28093. }
  28094. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28095. // Normals
  28096. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28097. return this;
  28098. }
  28099. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28100. temp = [];
  28101. for (index = 0; index < data.length; index += 3) {
  28102. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28103. }
  28104. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28105. // flip faces?
  28106. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28107. this.flipFaces();
  28108. }
  28109. // Restore submeshes
  28110. this.releaseSubMeshes();
  28111. this.subMeshes = submeshes;
  28112. return this;
  28113. };
  28114. /**
  28115. * Modifies the mesh geometry according to its own current World Matrix.
  28116. * The mesh World Matrix is then reset.
  28117. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28118. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28119. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28120. * Returns the Mesh.
  28121. */
  28122. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28123. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28124. this.scaling.copyFromFloats(1, 1, 1);
  28125. this.position.copyFromFloats(0, 0, 0);
  28126. this.rotation.copyFromFloats(0, 0, 0);
  28127. //only if quaternion is already set
  28128. if (this.rotationQuaternion) {
  28129. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28130. }
  28131. this._worldMatrix = BABYLON.Matrix.Identity();
  28132. return this;
  28133. };
  28134. Object.defineProperty(Mesh.prototype, "_positions", {
  28135. // Cache
  28136. get: function () {
  28137. if (this._geometry) {
  28138. return this._geometry._positions;
  28139. }
  28140. return null;
  28141. },
  28142. enumerable: true,
  28143. configurable: true
  28144. });
  28145. Mesh.prototype._resetPointsArrayCache = function () {
  28146. if (this._geometry) {
  28147. this._geometry._resetPointsArrayCache();
  28148. }
  28149. return this;
  28150. };
  28151. Mesh.prototype._generatePointsArray = function () {
  28152. if (this._geometry) {
  28153. return this._geometry._generatePointsArray();
  28154. }
  28155. return false;
  28156. };
  28157. /**
  28158. * Returns a new Mesh object generated from the current mesh properties.
  28159. * This method must not get confused with createInstance().
  28160. * The parameter `name` is a string, the name given to the new mesh.
  28161. * The optional parameter `newParent` can be any Node object (default `null`).
  28162. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28163. * 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.
  28164. */
  28165. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28166. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28167. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28168. };
  28169. /**
  28170. * Disposes the Mesh.
  28171. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28172. * Returns nothing.
  28173. */
  28174. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28175. var _this = this;
  28176. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28177. this.morphTargetManager = null;
  28178. if (this._geometry) {
  28179. this._geometry.releaseForMesh(this, true);
  28180. }
  28181. // Sources
  28182. var meshes = this.getScene().meshes;
  28183. meshes.forEach(function (abstractMesh) {
  28184. var mesh = abstractMesh;
  28185. if (mesh._source && mesh._source === _this) {
  28186. mesh._source = null;
  28187. }
  28188. });
  28189. this._source = null;
  28190. // Instances
  28191. if (this._instancesBuffer) {
  28192. this._instancesBuffer.dispose();
  28193. this._instancesBuffer = null;
  28194. }
  28195. while (this.instances.length) {
  28196. this.instances[0].dispose();
  28197. }
  28198. // Effect layers.
  28199. var effectLayers = this.getScene().effectLayers;
  28200. for (var i = 0; i < effectLayers.length; i++) {
  28201. var effectLayer = effectLayers[i];
  28202. if (effectLayer) {
  28203. effectLayer._disposeMesh(this);
  28204. }
  28205. }
  28206. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28207. };
  28208. /**
  28209. * Modifies the mesh geometry according to a displacement map.
  28210. * 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.
  28211. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28212. * This method returns nothing.
  28213. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28214. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28215. * 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.
  28216. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28217. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28218. *
  28219. * Returns the Mesh.
  28220. */
  28221. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28222. var _this = this;
  28223. var scene = this.getScene();
  28224. var onload = function (img) {
  28225. // Getting height map data
  28226. var canvas = document.createElement("canvas");
  28227. var context = canvas.getContext("2d");
  28228. var heightMapWidth = img.width;
  28229. var heightMapHeight = img.height;
  28230. canvas.width = heightMapWidth;
  28231. canvas.height = heightMapHeight;
  28232. context.drawImage(img, 0, 0);
  28233. // Create VertexData from map data
  28234. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28235. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28236. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28237. //execute success callback, if set
  28238. if (onSuccess) {
  28239. onSuccess(_this);
  28240. }
  28241. };
  28242. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28243. return this;
  28244. };
  28245. /**
  28246. * Modifies the mesh geometry according to a displacementMap buffer.
  28247. * 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.
  28248. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28249. * This method returns nothing.
  28250. * 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.
  28251. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28252. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28253. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28254. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28255. *
  28256. * Returns the Mesh.
  28257. */
  28258. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28259. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28260. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28261. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28262. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28263. return this;
  28264. }
  28265. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28266. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28267. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28268. var position = BABYLON.Vector3.Zero();
  28269. var normal = BABYLON.Vector3.Zero();
  28270. var uv = BABYLON.Vector2.Zero();
  28271. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28272. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28273. for (var index = 0; index < positions.length; index += 3) {
  28274. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28275. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28276. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28277. // Compute height
  28278. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28279. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28280. var pos = (u + v * heightMapWidth) * 4;
  28281. var r = buffer[pos] / 255.0;
  28282. var g = buffer[pos + 1] / 255.0;
  28283. var b = buffer[pos + 2] / 255.0;
  28284. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28285. normal.normalize();
  28286. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28287. position = position.add(normal);
  28288. position.toArray(positions, index);
  28289. }
  28290. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28291. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28292. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28293. return this;
  28294. };
  28295. /**
  28296. * Modify the mesh to get a flat shading rendering.
  28297. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28298. * This method returns the Mesh.
  28299. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28300. */
  28301. Mesh.prototype.convertToFlatShadedMesh = function () {
  28302. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28303. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28304. var kinds = this.getVerticesDataKinds();
  28305. var vbs = {};
  28306. var data = {};
  28307. var newdata = {};
  28308. var updatableNormals = false;
  28309. var kindIndex;
  28310. var kind;
  28311. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28312. kind = kinds[kindIndex];
  28313. var vertexBuffer = this.getVertexBuffer(kind);
  28314. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28315. updatableNormals = vertexBuffer.isUpdatable();
  28316. kinds.splice(kindIndex, 1);
  28317. kindIndex--;
  28318. continue;
  28319. }
  28320. vbs[kind] = vertexBuffer;
  28321. data[kind] = vbs[kind].getData();
  28322. newdata[kind] = [];
  28323. }
  28324. // Save previous submeshes
  28325. var previousSubmeshes = this.subMeshes.slice(0);
  28326. var indices = this.getIndices();
  28327. var totalIndices = this.getTotalIndices();
  28328. // Generating unique vertices per face
  28329. var index;
  28330. for (index = 0; index < totalIndices; index++) {
  28331. var vertexIndex = indices[index];
  28332. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28333. kind = kinds[kindIndex];
  28334. var stride = vbs[kind].getStrideSize();
  28335. for (var offset = 0; offset < stride; offset++) {
  28336. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28337. }
  28338. }
  28339. }
  28340. // Updating faces & normal
  28341. var normals = [];
  28342. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28343. for (index = 0; index < totalIndices; index += 3) {
  28344. indices[index] = index;
  28345. indices[index + 1] = index + 1;
  28346. indices[index + 2] = index + 2;
  28347. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28348. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28349. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28350. var p1p2 = p1.subtract(p2);
  28351. var p3p2 = p3.subtract(p2);
  28352. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28353. // Store same normals for every vertex
  28354. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28355. normals.push(normal.x);
  28356. normals.push(normal.y);
  28357. normals.push(normal.z);
  28358. }
  28359. }
  28360. this.setIndices(indices);
  28361. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28362. // Updating vertex buffers
  28363. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28364. kind = kinds[kindIndex];
  28365. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28366. }
  28367. // Updating submeshes
  28368. this.releaseSubMeshes();
  28369. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28370. var previousOne = previousSubmeshes[submeshIndex];
  28371. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28372. }
  28373. this.synchronizeInstances();
  28374. return this;
  28375. };
  28376. /**
  28377. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28378. * In other words, more vertices, no more indices and a single bigger VBO.
  28379. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28380. * Returns the Mesh.
  28381. */
  28382. Mesh.prototype.convertToUnIndexedMesh = function () {
  28383. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28384. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28385. var kinds = this.getVerticesDataKinds();
  28386. var vbs = {};
  28387. var data = {};
  28388. var newdata = {};
  28389. var kindIndex;
  28390. var kind;
  28391. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28392. kind = kinds[kindIndex];
  28393. var vertexBuffer = this.getVertexBuffer(kind);
  28394. vbs[kind] = vertexBuffer;
  28395. data[kind] = vbs[kind].getData();
  28396. newdata[kind] = [];
  28397. }
  28398. // Save previous submeshes
  28399. var previousSubmeshes = this.subMeshes.slice(0);
  28400. var indices = this.getIndices();
  28401. var totalIndices = this.getTotalIndices();
  28402. // Generating unique vertices per face
  28403. var index;
  28404. for (index = 0; index < totalIndices; index++) {
  28405. var vertexIndex = indices[index];
  28406. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28407. kind = kinds[kindIndex];
  28408. var stride = vbs[kind].getStrideSize();
  28409. for (var offset = 0; offset < stride; offset++) {
  28410. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28411. }
  28412. }
  28413. }
  28414. // Updating indices
  28415. for (index = 0; index < totalIndices; index += 3) {
  28416. indices[index] = index;
  28417. indices[index + 1] = index + 1;
  28418. indices[index + 2] = index + 2;
  28419. }
  28420. this.setIndices(indices);
  28421. // Updating vertex buffers
  28422. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28423. kind = kinds[kindIndex];
  28424. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28425. }
  28426. // Updating submeshes
  28427. this.releaseSubMeshes();
  28428. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28429. var previousOne = previousSubmeshes[submeshIndex];
  28430. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28431. }
  28432. this._unIndexed = true;
  28433. this.synchronizeInstances();
  28434. return this;
  28435. };
  28436. /**
  28437. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28438. * This method returns the Mesh.
  28439. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28440. */
  28441. Mesh.prototype.flipFaces = function (flipNormals) {
  28442. if (flipNormals === void 0) { flipNormals = false; }
  28443. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28444. var i;
  28445. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28446. for (i = 0; i < vertex_data.normals.length; i++) {
  28447. vertex_data.normals[i] *= -1;
  28448. }
  28449. }
  28450. if (vertex_data.indices) {
  28451. var temp;
  28452. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28453. // reassign indices
  28454. temp = vertex_data.indices[i + 1];
  28455. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28456. vertex_data.indices[i + 2] = temp;
  28457. }
  28458. }
  28459. vertex_data.applyToMesh(this);
  28460. return this;
  28461. };
  28462. // Instances
  28463. /**
  28464. * Creates a new InstancedMesh object from the mesh model.
  28465. * An instance shares the same properties and the same material than its model.
  28466. * Only these properties of each instance can then be set individually :
  28467. * - position
  28468. * - rotation
  28469. * - rotationQuaternion
  28470. * - setPivotMatrix
  28471. * - scaling
  28472. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28473. * Warning : this method is not supported for Line mesh and LineSystem
  28474. */
  28475. Mesh.prototype.createInstance = function (name) {
  28476. return new BABYLON.InstancedMesh(name, this);
  28477. };
  28478. /**
  28479. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28480. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28481. * This method returns the Mesh.
  28482. */
  28483. Mesh.prototype.synchronizeInstances = function () {
  28484. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28485. var instance = this.instances[instanceIndex];
  28486. instance._syncSubMeshes();
  28487. }
  28488. return this;
  28489. };
  28490. /**
  28491. * Simplify the mesh according to the given array of settings.
  28492. * Function will return immediately and will simplify async. It returns the Mesh.
  28493. * @param settings a collection of simplification settings.
  28494. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28495. * @param type the type of simplification to run.
  28496. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28497. */
  28498. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28499. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28500. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28501. this.getScene().simplificationQueue.addTask({
  28502. settings: settings,
  28503. parallelProcessing: parallelProcessing,
  28504. mesh: this,
  28505. simplificationType: simplificationType,
  28506. successCallback: successCallback
  28507. });
  28508. return this;
  28509. };
  28510. /**
  28511. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28512. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28513. * This should be used together with the simplification to avoid disappearing triangles.
  28514. * Returns the Mesh.
  28515. * @param successCallback an optional success callback to be called after the optimization finished.
  28516. */
  28517. Mesh.prototype.optimizeIndices = function (successCallback) {
  28518. var _this = this;
  28519. var indices = this.getIndices();
  28520. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28521. if (!positions || !indices) {
  28522. return this;
  28523. }
  28524. var vectorPositions = new Array();
  28525. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28526. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28527. }
  28528. var dupes = new Array();
  28529. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28530. var realPos = vectorPositions.length - 1 - iteration;
  28531. var testedPosition = vectorPositions[realPos];
  28532. for (var j = 0; j < realPos; ++j) {
  28533. var againstPosition = vectorPositions[j];
  28534. if (testedPosition.equals(againstPosition)) {
  28535. dupes[realPos] = j;
  28536. break;
  28537. }
  28538. }
  28539. }, function () {
  28540. for (var i = 0; i < indices.length; ++i) {
  28541. indices[i] = dupes[indices[i]] || indices[i];
  28542. }
  28543. //indices are now reordered
  28544. var originalSubMeshes = _this.subMeshes.slice(0);
  28545. _this.setIndices(indices);
  28546. _this.subMeshes = originalSubMeshes;
  28547. if (successCallback) {
  28548. successCallback(_this);
  28549. }
  28550. });
  28551. return this;
  28552. };
  28553. Mesh.prototype.serialize = function (serializationObject) {
  28554. serializationObject.name = this.name;
  28555. serializationObject.id = this.id;
  28556. serializationObject.type = this.getClassName();
  28557. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28558. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28559. }
  28560. serializationObject.position = this.position.asArray();
  28561. if (this.rotationQuaternion) {
  28562. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28563. }
  28564. else if (this.rotation) {
  28565. serializationObject.rotation = this.rotation.asArray();
  28566. }
  28567. serializationObject.scaling = this.scaling.asArray();
  28568. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28569. serializationObject.isEnabled = this.isEnabled(false);
  28570. serializationObject.isVisible = this.isVisible;
  28571. serializationObject.infiniteDistance = this.infiniteDistance;
  28572. serializationObject.pickable = this.isPickable;
  28573. serializationObject.receiveShadows = this.receiveShadows;
  28574. serializationObject.billboardMode = this.billboardMode;
  28575. serializationObject.visibility = this.visibility;
  28576. serializationObject.checkCollisions = this.checkCollisions;
  28577. serializationObject.isBlocker = this.isBlocker;
  28578. // Parent
  28579. if (this.parent) {
  28580. serializationObject.parentId = this.parent.id;
  28581. }
  28582. // Geometry
  28583. serializationObject.isUnIndexed = this.isUnIndexed;
  28584. var geometry = this._geometry;
  28585. if (geometry) {
  28586. var geometryId = geometry.id;
  28587. serializationObject.geometryId = geometryId;
  28588. // SubMeshes
  28589. serializationObject.subMeshes = [];
  28590. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28591. var subMesh = this.subMeshes[subIndex];
  28592. serializationObject.subMeshes.push({
  28593. materialIndex: subMesh.materialIndex,
  28594. verticesStart: subMesh.verticesStart,
  28595. verticesCount: subMesh.verticesCount,
  28596. indexStart: subMesh.indexStart,
  28597. indexCount: subMesh.indexCount
  28598. });
  28599. }
  28600. }
  28601. // Material
  28602. if (this.material) {
  28603. serializationObject.materialId = this.material.id;
  28604. }
  28605. else {
  28606. this.material = null;
  28607. }
  28608. // Morph targets
  28609. if (this.morphTargetManager) {
  28610. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28611. }
  28612. // Skeleton
  28613. if (this.skeleton) {
  28614. serializationObject.skeletonId = this.skeleton.id;
  28615. }
  28616. // Physics
  28617. //TODO implement correct serialization for physics impostors.
  28618. var impostor = this.getPhysicsImpostor();
  28619. if (impostor) {
  28620. serializationObject.physicsMass = impostor.getParam("mass");
  28621. serializationObject.physicsFriction = impostor.getParam("friction");
  28622. serializationObject.physicsRestitution = impostor.getParam("mass");
  28623. serializationObject.physicsImpostor = impostor.type;
  28624. }
  28625. // Metadata
  28626. if (this.metadata) {
  28627. serializationObject.metadata = this.metadata;
  28628. }
  28629. // Instances
  28630. serializationObject.instances = [];
  28631. for (var index = 0; index < this.instances.length; index++) {
  28632. var instance = this.instances[index];
  28633. var serializationInstance = {
  28634. name: instance.name,
  28635. id: instance.id,
  28636. position: instance.position.asArray(),
  28637. scaling: instance.scaling.asArray()
  28638. };
  28639. if (instance.rotationQuaternion) {
  28640. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28641. }
  28642. else if (instance.rotation) {
  28643. serializationInstance.rotation = instance.rotation.asArray();
  28644. }
  28645. serializationObject.instances.push(serializationInstance);
  28646. // Animations
  28647. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28648. serializationInstance.ranges = instance.serializeAnimationRanges();
  28649. }
  28650. //
  28651. // Animations
  28652. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28653. serializationObject.ranges = this.serializeAnimationRanges();
  28654. // Layer mask
  28655. serializationObject.layerMask = this.layerMask;
  28656. // Alpha
  28657. serializationObject.alphaIndex = this.alphaIndex;
  28658. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28659. // Overlay
  28660. serializationObject.overlayAlpha = this.overlayAlpha;
  28661. serializationObject.overlayColor = this.overlayColor.asArray();
  28662. serializationObject.renderOverlay = this.renderOverlay;
  28663. // Fog
  28664. serializationObject.applyFog = this.applyFog;
  28665. // Action Manager
  28666. if (this.actionManager) {
  28667. serializationObject.actions = this.actionManager.serialize(this.name);
  28668. }
  28669. };
  28670. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28671. if (!this.geometry) {
  28672. return;
  28673. }
  28674. this._markSubMeshesAsAttributesDirty();
  28675. var morphTargetManager = this._morphTargetManager;
  28676. if (morphTargetManager && morphTargetManager.vertexCount) {
  28677. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28678. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28679. this.morphTargetManager = null;
  28680. return;
  28681. }
  28682. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28683. var morphTarget = morphTargetManager.getActiveTarget(index);
  28684. var positions = morphTarget.getPositions();
  28685. if (!positions) {
  28686. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28687. return;
  28688. }
  28689. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28690. var normals = morphTarget.getNormals();
  28691. if (normals) {
  28692. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28693. }
  28694. var tangents = morphTarget.getTangents();
  28695. if (tangents) {
  28696. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28697. }
  28698. }
  28699. }
  28700. else {
  28701. var index = 0;
  28702. // Positions
  28703. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28704. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28705. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28706. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28707. }
  28708. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28709. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28710. }
  28711. index++;
  28712. }
  28713. }
  28714. };
  28715. // Statics
  28716. /**
  28717. * Returns a new Mesh object parsed from the source provided.
  28718. * The parameter `parsedMesh` is the source.
  28719. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28720. */
  28721. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28722. var mesh;
  28723. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28724. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28725. }
  28726. else {
  28727. mesh = new Mesh(parsedMesh.name, scene);
  28728. }
  28729. mesh.id = parsedMesh.id;
  28730. if (BABYLON.Tags) {
  28731. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28732. }
  28733. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28734. if (parsedMesh.metadata !== undefined) {
  28735. mesh.metadata = parsedMesh.metadata;
  28736. }
  28737. if (parsedMesh.rotationQuaternion) {
  28738. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28739. }
  28740. else if (parsedMesh.rotation) {
  28741. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28742. }
  28743. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28744. if (parsedMesh.localMatrix) {
  28745. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28746. }
  28747. else if (parsedMesh.pivotMatrix) {
  28748. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28749. }
  28750. mesh.setEnabled(parsedMesh.isEnabled);
  28751. mesh.isVisible = parsedMesh.isVisible;
  28752. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28753. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28754. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28755. if (parsedMesh.applyFog !== undefined) {
  28756. mesh.applyFog = parsedMesh.applyFog;
  28757. }
  28758. if (parsedMesh.pickable !== undefined) {
  28759. mesh.isPickable = parsedMesh.pickable;
  28760. }
  28761. if (parsedMesh.alphaIndex !== undefined) {
  28762. mesh.alphaIndex = parsedMesh.alphaIndex;
  28763. }
  28764. mesh.receiveShadows = parsedMesh.receiveShadows;
  28765. mesh.billboardMode = parsedMesh.billboardMode;
  28766. if (parsedMesh.visibility !== undefined) {
  28767. mesh.visibility = parsedMesh.visibility;
  28768. }
  28769. mesh.checkCollisions = parsedMesh.checkCollisions;
  28770. if (parsedMesh.isBlocker !== undefined) {
  28771. mesh.isBlocker = parsedMesh.isBlocker;
  28772. }
  28773. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28774. // freezeWorldMatrix
  28775. if (parsedMesh.freezeWorldMatrix) {
  28776. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28777. }
  28778. // Parent
  28779. if (parsedMesh.parentId) {
  28780. mesh._waitingParentId = parsedMesh.parentId;
  28781. }
  28782. // Actions
  28783. if (parsedMesh.actions !== undefined) {
  28784. mesh._waitingActions = parsedMesh.actions;
  28785. }
  28786. // Overlay
  28787. if (parsedMesh.overlayAlpha !== undefined) {
  28788. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28789. }
  28790. if (parsedMesh.overlayColor !== undefined) {
  28791. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28792. }
  28793. if (parsedMesh.renderOverlay !== undefined) {
  28794. mesh.renderOverlay = parsedMesh.renderOverlay;
  28795. }
  28796. // Geometry
  28797. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28798. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28799. if (parsedMesh.delayLoadingFile) {
  28800. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28801. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28802. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28803. if (parsedMesh._binaryInfo) {
  28804. mesh._binaryInfo = parsedMesh._binaryInfo;
  28805. }
  28806. mesh._delayInfo = [];
  28807. if (parsedMesh.hasUVs) {
  28808. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28809. }
  28810. if (parsedMesh.hasUVs2) {
  28811. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28812. }
  28813. if (parsedMesh.hasUVs3) {
  28814. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28815. }
  28816. if (parsedMesh.hasUVs4) {
  28817. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28818. }
  28819. if (parsedMesh.hasUVs5) {
  28820. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28821. }
  28822. if (parsedMesh.hasUVs6) {
  28823. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28824. }
  28825. if (parsedMesh.hasColors) {
  28826. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28827. }
  28828. if (parsedMesh.hasMatricesIndices) {
  28829. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28830. }
  28831. if (parsedMesh.hasMatricesWeights) {
  28832. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28833. }
  28834. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28835. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28836. mesh._checkDelayState();
  28837. }
  28838. }
  28839. else {
  28840. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28841. }
  28842. // Material
  28843. if (parsedMesh.materialId) {
  28844. mesh.setMaterialByID(parsedMesh.materialId);
  28845. }
  28846. else {
  28847. mesh.material = null;
  28848. }
  28849. // Morph targets
  28850. if (parsedMesh.morphTargetManagerId > -1) {
  28851. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28852. }
  28853. // Skeleton
  28854. if (parsedMesh.skeletonId > -1) {
  28855. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28856. if (parsedMesh.numBoneInfluencers) {
  28857. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28858. }
  28859. }
  28860. // Animations
  28861. if (parsedMesh.animations) {
  28862. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28863. var parsedAnimation = parsedMesh.animations[animationIndex];
  28864. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28865. }
  28866. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28867. }
  28868. if (parsedMesh.autoAnimate) {
  28869. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28870. }
  28871. // Layer Mask
  28872. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28873. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28874. }
  28875. else {
  28876. mesh.layerMask = 0x0FFFFFFF;
  28877. }
  28878. // Physics
  28879. if (parsedMesh.physicsImpostor) {
  28880. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28881. mass: parsedMesh.physicsMass,
  28882. friction: parsedMesh.physicsFriction,
  28883. restitution: parsedMesh.physicsRestitution
  28884. }, scene);
  28885. }
  28886. // Instances
  28887. if (parsedMesh.instances) {
  28888. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28889. var parsedInstance = parsedMesh.instances[index];
  28890. var instance = mesh.createInstance(parsedInstance.name);
  28891. if (parsedInstance.id) {
  28892. instance.id = parsedInstance.id;
  28893. }
  28894. if (BABYLON.Tags) {
  28895. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28896. }
  28897. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28898. if (parsedInstance.parentId) {
  28899. instance._waitingParentId = parsedInstance.parentId;
  28900. }
  28901. if (parsedInstance.rotationQuaternion) {
  28902. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28903. }
  28904. else if (parsedInstance.rotation) {
  28905. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28906. }
  28907. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28908. instance.checkCollisions = mesh.checkCollisions;
  28909. if (parsedMesh.animations) {
  28910. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28911. parsedAnimation = parsedMesh.animations[animationIndex];
  28912. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28913. }
  28914. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28915. }
  28916. }
  28917. }
  28918. return mesh;
  28919. };
  28920. /**
  28921. * Creates a ribbon mesh.
  28922. * Please consider using the same method from the MeshBuilder class instead.
  28923. * 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.
  28924. *
  28925. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28926. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28927. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28928. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28929. * 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.
  28930. * 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.
  28931. * 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
  28932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28935. */
  28936. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28937. if (closeArray === void 0) { closeArray = false; }
  28938. if (updatable === void 0) { updatable = false; }
  28939. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28940. pathArray: pathArray,
  28941. closeArray: closeArray,
  28942. closePath: closePath,
  28943. offset: offset,
  28944. updatable: updatable,
  28945. sideOrientation: sideOrientation,
  28946. instance: instance
  28947. }, scene);
  28948. };
  28949. /**
  28950. * Creates a plane polygonal mesh. By default, this is a disc.
  28951. * Please consider using the same method from the MeshBuilder class instead.
  28952. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28953. * 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.
  28954. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28955. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28957. */
  28958. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28959. if (scene === void 0) { scene = null; }
  28960. var options = {
  28961. radius: radius,
  28962. tessellation: tessellation,
  28963. sideOrientation: sideOrientation,
  28964. updatable: updatable
  28965. };
  28966. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28967. };
  28968. /**
  28969. * Creates a box mesh.
  28970. * Please consider using the same method from the MeshBuilder class instead.
  28971. * The parameter `size` sets the size (float) of each box side (default 1).
  28972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28973. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28975. */
  28976. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28977. if (scene === void 0) { scene = null; }
  28978. var options = {
  28979. size: size,
  28980. sideOrientation: sideOrientation,
  28981. updatable: updatable
  28982. };
  28983. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28984. };
  28985. /**
  28986. * Creates a sphere mesh.
  28987. * Please consider using the same method from the MeshBuilder class instead.
  28988. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28989. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28993. */
  28994. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28995. var options = {
  28996. segments: segments,
  28997. diameterX: diameter,
  28998. diameterY: diameter,
  28999. diameterZ: diameter,
  29000. sideOrientation: sideOrientation,
  29001. updatable: updatable
  29002. };
  29003. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29004. };
  29005. /**
  29006. * Creates a cylinder or a cone mesh.
  29007. * Please consider using the same method from the MeshBuilder class instead.
  29008. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29009. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29010. * 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.
  29011. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29012. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29016. */
  29017. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29018. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29019. if (scene !== undefined) {
  29020. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29021. updatable = scene;
  29022. }
  29023. scene = subdivisions;
  29024. subdivisions = 1;
  29025. }
  29026. var options = {
  29027. height: height,
  29028. diameterTop: diameterTop,
  29029. diameterBottom: diameterBottom,
  29030. tessellation: tessellation,
  29031. subdivisions: subdivisions,
  29032. sideOrientation: sideOrientation,
  29033. updatable: updatable
  29034. };
  29035. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29036. };
  29037. // Torus (Code from SharpDX.org)
  29038. /**
  29039. * Creates a torus mesh.
  29040. * Please consider using the same method from the MeshBuilder class instead.
  29041. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29042. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29043. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29044. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29045. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29047. */
  29048. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29049. var options = {
  29050. diameter: diameter,
  29051. thickness: thickness,
  29052. tessellation: tessellation,
  29053. sideOrientation: sideOrientation,
  29054. updatable: updatable
  29055. };
  29056. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29057. };
  29058. /**
  29059. * Creates a torus knot mesh.
  29060. * Please consider using the same method from the MeshBuilder class instead.
  29061. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29062. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29063. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29064. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29065. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29066. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29067. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29068. */
  29069. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29070. var options = {
  29071. radius: radius,
  29072. tube: tube,
  29073. radialSegments: radialSegments,
  29074. tubularSegments: tubularSegments,
  29075. p: p,
  29076. q: q,
  29077. sideOrientation: sideOrientation,
  29078. updatable: updatable
  29079. };
  29080. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29081. };
  29082. /**
  29083. * Creates a line mesh.
  29084. * Please consider using the same method from the MeshBuilder class instead.
  29085. * 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.
  29086. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29087. * The parameter `points` is an array successive Vector3.
  29088. * 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
  29089. * When updating an instance, remember that only point positions can change, not the number of points.
  29090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29091. */
  29092. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29093. if (scene === void 0) { scene = null; }
  29094. if (updatable === void 0) { updatable = false; }
  29095. if (instance === void 0) { instance = null; }
  29096. var options = {
  29097. points: points,
  29098. updatable: updatable,
  29099. instance: instance
  29100. };
  29101. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29102. };
  29103. /**
  29104. * Creates a dashed line mesh.
  29105. * Please consider using the same method from the MeshBuilder class instead.
  29106. * 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.
  29107. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29108. * The parameter `points` is an array successive Vector3.
  29109. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29110. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29111. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29112. * 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
  29113. * When updating an instance, remember that only point positions can change, not the number of points.
  29114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29115. */
  29116. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29117. if (scene === void 0) { scene = null; }
  29118. var options = {
  29119. points: points,
  29120. dashSize: dashSize,
  29121. gapSize: gapSize,
  29122. dashNb: dashNb,
  29123. updatable: updatable,
  29124. instance: instance
  29125. };
  29126. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29127. };
  29128. /**
  29129. * Creates a polygon mesh.
  29130. * Please consider using the same method from the MeshBuilder class instead.
  29131. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29132. * 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.
  29133. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29134. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29135. * Remember you can only change the shape positions, not their number when updating a polygon.
  29136. */
  29137. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29138. var options = {
  29139. shape: shape,
  29140. holes: holes,
  29141. updatable: updatable,
  29142. sideOrientation: sideOrientation
  29143. };
  29144. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29145. };
  29146. /**
  29147. * Creates an extruded polygon mesh, with depth in the Y direction.
  29148. * Please consider using the same method from the MeshBuilder class instead.
  29149. */
  29150. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29151. var options = {
  29152. shape: shape,
  29153. holes: holes,
  29154. depth: depth,
  29155. updatable: updatable,
  29156. sideOrientation: sideOrientation
  29157. };
  29158. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29159. };
  29160. /**
  29161. * Creates an extruded shape mesh.
  29162. * 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.
  29163. * Please consider using the same method from the MeshBuilder class instead.
  29164. *
  29165. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29166. * 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
  29167. * extruded along the Z axis.
  29168. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29169. * 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.
  29170. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29171. * 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
  29172. * 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
  29173. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29174. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29175. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29177. */
  29178. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29179. if (scene === void 0) { scene = null; }
  29180. var options = {
  29181. shape: shape,
  29182. path: path,
  29183. scale: scale,
  29184. rotation: rotation,
  29185. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29186. sideOrientation: sideOrientation,
  29187. instance: instance,
  29188. updatable: updatable
  29189. };
  29190. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29191. };
  29192. /**
  29193. * Creates an custom extruded shape mesh.
  29194. * 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.
  29195. * Please consider using the same method from the MeshBuilder class instead.
  29196. *
  29197. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29198. * 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
  29199. * extruded along the Z axis.
  29200. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29201. * 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
  29202. * and the distance of this point from the begining of the path :
  29203. * ```javascript
  29204. * var rotationFunction = function(i, distance) {
  29205. * // do things
  29206. * return rotationValue; }
  29207. * ```
  29208. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29209. * 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
  29210. * and the distance of this point from the begining of the path :
  29211. * ```javascript
  29212. * var scaleFunction = function(i, distance) {
  29213. * // do things
  29214. * return scaleValue;}
  29215. * ```
  29216. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29217. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29218. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29219. * 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
  29220. * 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
  29221. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29222. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29223. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29224. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29225. */
  29226. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29227. var options = {
  29228. shape: shape,
  29229. path: path,
  29230. scaleFunction: scaleFunction,
  29231. rotationFunction: rotationFunction,
  29232. ribbonCloseArray: ribbonCloseArray,
  29233. ribbonClosePath: ribbonClosePath,
  29234. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29235. sideOrientation: sideOrientation,
  29236. instance: instance,
  29237. updatable: updatable
  29238. };
  29239. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29240. };
  29241. /**
  29242. * Creates lathe mesh.
  29243. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29244. * Please consider using the same method from the MeshBuilder class instead.
  29245. * 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
  29246. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29247. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29248. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29249. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29250. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29252. */
  29253. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29254. var options = {
  29255. shape: shape,
  29256. radius: radius,
  29257. tessellation: tessellation,
  29258. sideOrientation: sideOrientation,
  29259. updatable: updatable
  29260. };
  29261. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29262. };
  29263. /**
  29264. * Creates a plane mesh.
  29265. * Please consider using the same method from the MeshBuilder class instead.
  29266. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29268. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29270. */
  29271. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29272. var options = {
  29273. size: size,
  29274. width: size,
  29275. height: size,
  29276. sideOrientation: sideOrientation,
  29277. updatable: updatable
  29278. };
  29279. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29280. };
  29281. /**
  29282. * Creates a ground mesh.
  29283. * Please consider using the same method from the MeshBuilder class instead.
  29284. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29285. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  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.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29289. var options = {
  29290. width: width,
  29291. height: height,
  29292. subdivisions: subdivisions,
  29293. updatable: updatable
  29294. };
  29295. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29296. };
  29297. /**
  29298. * Creates a tiled ground mesh.
  29299. * Please consider using the same method from the MeshBuilder class instead.
  29300. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29301. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29302. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29303. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29304. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29305. * numbers of subdivisions on the ground width and height of each tile.
  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. */
  29308. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29309. var options = {
  29310. xmin: xmin,
  29311. zmin: zmin,
  29312. xmax: xmax,
  29313. zmax: zmax,
  29314. subdivisions: subdivisions,
  29315. precision: precision,
  29316. updatable: updatable
  29317. };
  29318. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29319. };
  29320. /**
  29321. * Creates a ground mesh from a height map.
  29322. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29323. * Please consider using the same method from the MeshBuilder class instead.
  29324. * The parameter `url` sets the URL of the height map image resource.
  29325. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29326. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29327. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29328. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29329. * 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).
  29330. * This function is passed the newly built mesh :
  29331. * ```javascript
  29332. * function(mesh) { // do things
  29333. * return; }
  29334. * ```
  29335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29336. */
  29337. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29338. var options = {
  29339. width: width,
  29340. height: height,
  29341. subdivisions: subdivisions,
  29342. minHeight: minHeight,
  29343. maxHeight: maxHeight,
  29344. updatable: updatable,
  29345. onReady: onReady
  29346. };
  29347. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29348. };
  29349. /**
  29350. * Creates a tube mesh.
  29351. * 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.
  29352. * Please consider using the same method from the MeshBuilder class instead.
  29353. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29354. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29355. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29356. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29357. * 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.
  29358. * It must return a radius value (positive float) :
  29359. * ```javascript
  29360. * var radiusFunction = function(i, distance) {
  29361. * // do things
  29362. * return radius; }
  29363. * ```
  29364. * 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
  29365. * 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
  29366. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29367. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29369. */
  29370. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29371. var options = {
  29372. path: path,
  29373. radius: radius,
  29374. tessellation: tessellation,
  29375. radiusFunction: radiusFunction,
  29376. arc: 1,
  29377. cap: cap,
  29378. updatable: updatable,
  29379. sideOrientation: sideOrientation,
  29380. instance: instance
  29381. };
  29382. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29383. };
  29384. /**
  29385. * Creates a polyhedron mesh.
  29386. * Please consider using the same method from the MeshBuilder class instead.
  29387. * 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
  29388. * to choose the wanted type.
  29389. * The parameter `size` (positive float, default 1) sets the polygon size.
  29390. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29391. * 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`.
  29392. * 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
  29393. * 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)`).
  29394. * 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
  29395. * 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.
  29396. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29397. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29398. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29399. */
  29400. Mesh.CreatePolyhedron = function (name, options, scene) {
  29401. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29402. };
  29403. /**
  29404. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29405. * Please consider using the same method from the MeshBuilder class instead.
  29406. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29407. * 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`).
  29408. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29409. * 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.
  29410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29411. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29413. */
  29414. Mesh.CreateIcoSphere = function (name, options, scene) {
  29415. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29416. };
  29417. /**
  29418. * Creates a decal mesh.
  29419. * Please consider using the same method from the MeshBuilder class instead.
  29420. * 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.
  29421. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29422. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29423. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29424. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29425. */
  29426. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29427. var options = {
  29428. position: position,
  29429. normal: normal,
  29430. size: size,
  29431. angle: angle
  29432. };
  29433. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29434. };
  29435. // Skeletons
  29436. /**
  29437. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29438. */
  29439. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29440. if (!this._sourcePositions) {
  29441. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29442. if (!source) {
  29443. return this._sourcePositions;
  29444. }
  29445. this._sourcePositions = new Float32Array(source);
  29446. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29447. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29448. }
  29449. }
  29450. return this._sourcePositions;
  29451. };
  29452. /**
  29453. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29454. */
  29455. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29456. if (!this._sourceNormals) {
  29457. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29458. if (!source) {
  29459. return this._sourceNormals;
  29460. }
  29461. this._sourceNormals = new Float32Array(source);
  29462. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29463. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29464. }
  29465. }
  29466. return this._sourceNormals;
  29467. };
  29468. /**
  29469. * Updates the vertex buffer by applying transformation from the bones.
  29470. * Returns the Mesh.
  29471. *
  29472. * @param {skeleton} skeleton to apply
  29473. */
  29474. Mesh.prototype.applySkeleton = function (skeleton) {
  29475. if (!this.geometry) {
  29476. return this;
  29477. }
  29478. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29479. return this;
  29480. }
  29481. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29482. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29483. return this;
  29484. }
  29485. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29486. return this;
  29487. }
  29488. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29489. return this;
  29490. }
  29491. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29492. return this;
  29493. }
  29494. if (!this._sourcePositions) {
  29495. var submeshes = this.subMeshes.slice();
  29496. this.setPositionsForCPUSkinning();
  29497. this.subMeshes = submeshes;
  29498. }
  29499. if (!this._sourceNormals) {
  29500. this.setNormalsForCPUSkinning();
  29501. }
  29502. // positionsData checks for not being Float32Array will only pass at most once
  29503. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29504. if (!positionsData) {
  29505. return this;
  29506. }
  29507. if (!(positionsData instanceof Float32Array)) {
  29508. positionsData = new Float32Array(positionsData);
  29509. }
  29510. // normalsData checks for not being Float32Array will only pass at most once
  29511. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29512. if (!normalsData) {
  29513. return this;
  29514. }
  29515. if (!(normalsData instanceof Float32Array)) {
  29516. normalsData = new Float32Array(normalsData);
  29517. }
  29518. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29519. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29520. if (!matricesWeightsData || !matricesIndicesData) {
  29521. return this;
  29522. }
  29523. var needExtras = this.numBoneInfluencers > 4;
  29524. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29525. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29526. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29527. var tempVector3 = BABYLON.Vector3.Zero();
  29528. var finalMatrix = new BABYLON.Matrix();
  29529. var tempMatrix = new BABYLON.Matrix();
  29530. var matWeightIdx = 0;
  29531. var inf;
  29532. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29533. var weight;
  29534. for (inf = 0; inf < 4; inf++) {
  29535. weight = matricesWeightsData[matWeightIdx + inf];
  29536. if (weight > 0) {
  29537. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29538. finalMatrix.addToSelf(tempMatrix);
  29539. }
  29540. else
  29541. break;
  29542. }
  29543. if (needExtras) {
  29544. for (inf = 0; inf < 4; inf++) {
  29545. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29546. if (weight > 0) {
  29547. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29548. finalMatrix.addToSelf(tempMatrix);
  29549. }
  29550. else
  29551. break;
  29552. }
  29553. }
  29554. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29555. tempVector3.toArray(positionsData, index);
  29556. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29557. tempVector3.toArray(normalsData, index);
  29558. finalMatrix.reset();
  29559. }
  29560. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29561. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29562. return this;
  29563. };
  29564. // Tools
  29565. /**
  29566. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29567. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29568. */
  29569. Mesh.MinMax = function (meshes) {
  29570. var minVector = null;
  29571. var maxVector = null;
  29572. meshes.forEach(function (mesh, index, array) {
  29573. var boundingInfo = mesh.getBoundingInfo();
  29574. var boundingBox = boundingInfo.boundingBox;
  29575. if (!minVector || !maxVector) {
  29576. minVector = boundingBox.minimumWorld;
  29577. maxVector = boundingBox.maximumWorld;
  29578. }
  29579. else {
  29580. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29581. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29582. }
  29583. });
  29584. if (!minVector || !maxVector) {
  29585. return {
  29586. min: BABYLON.Vector3.Zero(),
  29587. max: BABYLON.Vector3.Zero()
  29588. };
  29589. }
  29590. return {
  29591. min: minVector,
  29592. max: maxVector
  29593. };
  29594. };
  29595. /**
  29596. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29597. */
  29598. Mesh.Center = function (meshesOrMinMaxVector) {
  29599. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29600. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29601. };
  29602. /**
  29603. * Merge the array of meshes into a single mesh for performance reasons.
  29604. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29605. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29606. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29607. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29608. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29609. */
  29610. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29611. if (disposeSource === void 0) { disposeSource = true; }
  29612. var index;
  29613. if (!allow32BitsIndices) {
  29614. var totalVertices = 0;
  29615. // Counting vertices
  29616. for (index = 0; index < meshes.length; index++) {
  29617. if (meshes[index]) {
  29618. totalVertices += meshes[index].getTotalVertices();
  29619. if (totalVertices > 65536) {
  29620. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29621. return null;
  29622. }
  29623. }
  29624. }
  29625. }
  29626. // Merge
  29627. var vertexData = null;
  29628. var otherVertexData;
  29629. var indiceArray = new Array();
  29630. var source = null;
  29631. for (index = 0; index < meshes.length; index++) {
  29632. if (meshes[index]) {
  29633. meshes[index].computeWorldMatrix(true);
  29634. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29635. otherVertexData.transform(meshes[index].getWorldMatrix());
  29636. if (vertexData) {
  29637. vertexData.merge(otherVertexData);
  29638. }
  29639. else {
  29640. vertexData = otherVertexData;
  29641. source = meshes[index];
  29642. }
  29643. if (subdivideWithSubMeshes) {
  29644. indiceArray.push(meshes[index].getTotalIndices());
  29645. }
  29646. }
  29647. }
  29648. source = source;
  29649. if (!meshSubclass) {
  29650. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29651. }
  29652. vertexData.applyToMesh(meshSubclass);
  29653. // Setting properties
  29654. meshSubclass.material = source.material;
  29655. meshSubclass.checkCollisions = source.checkCollisions;
  29656. // Cleaning
  29657. if (disposeSource) {
  29658. for (index = 0; index < meshes.length; index++) {
  29659. if (meshes[index]) {
  29660. meshes[index].dispose();
  29661. }
  29662. }
  29663. }
  29664. // Subdivide
  29665. if (subdivideWithSubMeshes) {
  29666. //-- Suppresions du submesh global
  29667. meshSubclass.releaseSubMeshes();
  29668. index = 0;
  29669. var offset = 0;
  29670. //-- aplique la subdivision en fonction du tableau d'indices
  29671. while (index < indiceArray.length) {
  29672. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29673. offset += indiceArray[index];
  29674. index++;
  29675. }
  29676. }
  29677. return meshSubclass;
  29678. };
  29679. // Consts
  29680. Mesh._FRONTSIDE = 0;
  29681. Mesh._BACKSIDE = 1;
  29682. Mesh._DOUBLESIDE = 2;
  29683. Mesh._DEFAULTSIDE = 0;
  29684. Mesh._NO_CAP = 0;
  29685. Mesh._CAP_START = 1;
  29686. Mesh._CAP_END = 2;
  29687. Mesh._CAP_ALL = 3;
  29688. return Mesh;
  29689. }(BABYLON.AbstractMesh));
  29690. BABYLON.Mesh = Mesh;
  29691. })(BABYLON || (BABYLON = {}));
  29692. //# sourceMappingURL=babylon.mesh.js.map
  29693. var BABYLON;
  29694. (function (BABYLON) {
  29695. var BaseSubMesh = /** @class */ (function () {
  29696. function BaseSubMesh() {
  29697. }
  29698. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29699. get: function () {
  29700. return this._materialEffect;
  29701. },
  29702. enumerable: true,
  29703. configurable: true
  29704. });
  29705. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29706. if (defines === void 0) { defines = null; }
  29707. if (this._materialEffect === effect) {
  29708. if (!effect) {
  29709. this._materialDefines = null;
  29710. }
  29711. return;
  29712. }
  29713. this._materialDefines = defines;
  29714. this._materialEffect = effect;
  29715. };
  29716. return BaseSubMesh;
  29717. }());
  29718. BABYLON.BaseSubMesh = BaseSubMesh;
  29719. var SubMesh = /** @class */ (function (_super) {
  29720. __extends(SubMesh, _super);
  29721. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29722. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29723. var _this = _super.call(this) || this;
  29724. _this.materialIndex = materialIndex;
  29725. _this.verticesStart = verticesStart;
  29726. _this.verticesCount = verticesCount;
  29727. _this.indexStart = indexStart;
  29728. _this.indexCount = indexCount;
  29729. _this._renderId = 0;
  29730. _this._mesh = mesh;
  29731. _this._renderingMesh = renderingMesh || mesh;
  29732. mesh.subMeshes.push(_this);
  29733. _this._trianglePlanes = [];
  29734. _this._id = mesh.subMeshes.length - 1;
  29735. if (createBoundingBox) {
  29736. _this.refreshBoundingInfo();
  29737. mesh.computeWorldMatrix(true);
  29738. }
  29739. return _this;
  29740. }
  29741. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29742. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29743. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29744. };
  29745. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29746. get: function () {
  29747. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29748. },
  29749. enumerable: true,
  29750. configurable: true
  29751. });
  29752. /**
  29753. * Returns the submesh BoudingInfo object.
  29754. */
  29755. SubMesh.prototype.getBoundingInfo = function () {
  29756. if (this.IsGlobal) {
  29757. return this._mesh.getBoundingInfo();
  29758. }
  29759. return this._boundingInfo;
  29760. };
  29761. /**
  29762. * Sets the submesh BoundingInfo.
  29763. * Return the SubMesh.
  29764. */
  29765. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29766. this._boundingInfo = boundingInfo;
  29767. return this;
  29768. };
  29769. /**
  29770. * Returns the mesh of the current submesh.
  29771. */
  29772. SubMesh.prototype.getMesh = function () {
  29773. return this._mesh;
  29774. };
  29775. /**
  29776. * Returns the rendering mesh of the submesh.
  29777. */
  29778. SubMesh.prototype.getRenderingMesh = function () {
  29779. return this._renderingMesh;
  29780. };
  29781. /**
  29782. * Returns the submesh material.
  29783. */
  29784. SubMesh.prototype.getMaterial = function () {
  29785. var rootMaterial = this._renderingMesh.material;
  29786. if (rootMaterial === null || rootMaterial === undefined) {
  29787. return this._mesh.getScene().defaultMaterial;
  29788. }
  29789. else if (rootMaterial.getSubMaterial) {
  29790. var multiMaterial = rootMaterial;
  29791. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29792. if (this._currentMaterial !== effectiveMaterial) {
  29793. this._currentMaterial = effectiveMaterial;
  29794. this._materialDefines = null;
  29795. }
  29796. return effectiveMaterial;
  29797. }
  29798. return rootMaterial;
  29799. };
  29800. // Methods
  29801. /**
  29802. * Sets a new updated BoundingInfo object to the submesh.
  29803. * Returns the SubMesh.
  29804. */
  29805. SubMesh.prototype.refreshBoundingInfo = function () {
  29806. this._lastColliderWorldVertices = null;
  29807. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29808. return this;
  29809. }
  29810. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29811. if (!data) {
  29812. this._boundingInfo = this._mesh.getBoundingInfo();
  29813. return this;
  29814. }
  29815. var indices = this._renderingMesh.getIndices();
  29816. var extend;
  29817. //is this the only submesh?
  29818. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29819. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29820. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29821. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29822. }
  29823. else {
  29824. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29825. }
  29826. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29827. return this;
  29828. };
  29829. SubMesh.prototype._checkCollision = function (collider) {
  29830. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29831. return boundingInfo._checkCollision(collider);
  29832. };
  29833. /**
  29834. * Updates the submesh BoundingInfo.
  29835. * Returns the Submesh.
  29836. */
  29837. SubMesh.prototype.updateBoundingInfo = function (world) {
  29838. var boundingInfo = this.getBoundingInfo();
  29839. if (!boundingInfo) {
  29840. this.refreshBoundingInfo();
  29841. boundingInfo = this.getBoundingInfo();
  29842. }
  29843. boundingInfo.update(world);
  29844. return this;
  29845. };
  29846. /**
  29847. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29848. * Boolean returned.
  29849. */
  29850. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29851. var boundingInfo = this.getBoundingInfo();
  29852. if (!boundingInfo) {
  29853. return false;
  29854. }
  29855. return boundingInfo.isInFrustum(frustumPlanes);
  29856. };
  29857. /**
  29858. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29859. * Boolean returned.
  29860. */
  29861. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29862. var boundingInfo = this.getBoundingInfo();
  29863. if (!boundingInfo) {
  29864. return false;
  29865. }
  29866. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29867. };
  29868. /**
  29869. * Renders the submesh.
  29870. * Returns it.
  29871. */
  29872. SubMesh.prototype.render = function (enableAlphaMode) {
  29873. this._renderingMesh.render(this, enableAlphaMode);
  29874. return this;
  29875. };
  29876. /**
  29877. * Returns a new Index Buffer.
  29878. * Type returned : WebGLBuffer.
  29879. */
  29880. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29881. if (!this._linesIndexBuffer) {
  29882. var linesIndices = [];
  29883. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29884. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29885. }
  29886. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29887. this.linesIndexCount = linesIndices.length;
  29888. }
  29889. return this._linesIndexBuffer;
  29890. };
  29891. /**
  29892. * True is the passed Ray intersects the submesh bounding box.
  29893. * Boolean returned.
  29894. */
  29895. SubMesh.prototype.canIntersects = function (ray) {
  29896. var boundingInfo = this.getBoundingInfo();
  29897. if (!boundingInfo) {
  29898. return false;
  29899. }
  29900. return ray.intersectsBox(boundingInfo.boundingBox);
  29901. };
  29902. /**
  29903. * Returns an object IntersectionInfo.
  29904. */
  29905. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29906. var intersectInfo = null;
  29907. // LineMesh first as it's also a Mesh...
  29908. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29909. var lineMesh = this._mesh;
  29910. // Line test
  29911. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29912. var p0 = positions[indices[index]];
  29913. var p1 = positions[indices[index + 1]];
  29914. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29915. if (length < 0) {
  29916. continue;
  29917. }
  29918. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29919. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29920. if (fastCheck) {
  29921. break;
  29922. }
  29923. }
  29924. }
  29925. }
  29926. else {
  29927. // Triangles test
  29928. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29929. var p0 = positions[indices[index]];
  29930. var p1 = positions[indices[index + 1]];
  29931. var p2 = positions[indices[index + 2]];
  29932. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29933. if (currentIntersectInfo) {
  29934. if (currentIntersectInfo.distance < 0) {
  29935. continue;
  29936. }
  29937. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29938. intersectInfo = currentIntersectInfo;
  29939. intersectInfo.faceId = index / 3;
  29940. if (fastCheck) {
  29941. break;
  29942. }
  29943. }
  29944. }
  29945. }
  29946. }
  29947. return intersectInfo;
  29948. };
  29949. SubMesh.prototype._rebuild = function () {
  29950. if (this._linesIndexBuffer) {
  29951. this._linesIndexBuffer = null;
  29952. }
  29953. };
  29954. // Clone
  29955. /**
  29956. * Creates a new Submesh from the passed Mesh.
  29957. */
  29958. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29959. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29960. if (!this.IsGlobal) {
  29961. var boundingInfo = this.getBoundingInfo();
  29962. if (!boundingInfo) {
  29963. return result;
  29964. }
  29965. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29966. }
  29967. return result;
  29968. };
  29969. // Dispose
  29970. /**
  29971. * Disposes the Submesh.
  29972. * Returns nothing.
  29973. */
  29974. SubMesh.prototype.dispose = function () {
  29975. if (this._linesIndexBuffer) {
  29976. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29977. this._linesIndexBuffer = null;
  29978. }
  29979. // Remove from mesh
  29980. var index = this._mesh.subMeshes.indexOf(this);
  29981. this._mesh.subMeshes.splice(index, 1);
  29982. };
  29983. // Statics
  29984. /**
  29985. * Creates a new Submesh from the passed parameters :
  29986. * - materialIndex (integer) : the index of the main mesh material.
  29987. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29988. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29989. * - mesh (Mesh) : the main mesh to create the submesh from.
  29990. * - renderingMesh (optional Mesh) : rendering mesh.
  29991. */
  29992. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29993. var minVertexIndex = Number.MAX_VALUE;
  29994. var maxVertexIndex = -Number.MAX_VALUE;
  29995. renderingMesh = (renderingMesh || mesh);
  29996. var indices = renderingMesh.getIndices();
  29997. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29998. var vertexIndex = indices[index];
  29999. if (vertexIndex < minVertexIndex)
  30000. minVertexIndex = vertexIndex;
  30001. if (vertexIndex > maxVertexIndex)
  30002. maxVertexIndex = vertexIndex;
  30003. }
  30004. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30005. };
  30006. return SubMesh;
  30007. }(BaseSubMesh));
  30008. BABYLON.SubMesh = SubMesh;
  30009. })(BABYLON || (BABYLON = {}));
  30010. //# sourceMappingURL=babylon.subMesh.js.map
  30011. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30012. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30013. s = arguments[i];
  30014. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30015. t[p] = s[p];
  30016. }
  30017. return t;
  30018. };
  30019. var BABYLON;
  30020. (function (BABYLON) {
  30021. /**
  30022. * Manages the defines for the Material.
  30023. */
  30024. var MaterialDefines = /** @class */ (function () {
  30025. function MaterialDefines() {
  30026. this._isDirty = true;
  30027. this._areLightsDirty = true;
  30028. this._areAttributesDirty = true;
  30029. this._areTexturesDirty = true;
  30030. this._areFresnelDirty = true;
  30031. this._areMiscDirty = true;
  30032. this._areImageProcessingDirty = true;
  30033. this._normals = false;
  30034. this._uvs = false;
  30035. this._needNormals = false;
  30036. this._needUVs = false;
  30037. }
  30038. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30039. /**
  30040. * Specifies if the material needs to be re-calculated.
  30041. */
  30042. get: function () {
  30043. return this._isDirty;
  30044. },
  30045. enumerable: true,
  30046. configurable: true
  30047. });
  30048. /**
  30049. * Marks the material to indicate that it has been re-calculated.
  30050. */
  30051. MaterialDefines.prototype.markAsProcessed = function () {
  30052. this._isDirty = false;
  30053. this._areAttributesDirty = false;
  30054. this._areTexturesDirty = false;
  30055. this._areFresnelDirty = false;
  30056. this._areLightsDirty = false;
  30057. this._areMiscDirty = false;
  30058. this._areImageProcessingDirty = false;
  30059. };
  30060. /**
  30061. * Marks the material to indicate that it needs to be re-calculated.
  30062. */
  30063. MaterialDefines.prototype.markAsUnprocessed = function () {
  30064. this._isDirty = true;
  30065. };
  30066. /**
  30067. * Marks the material to indicate all of its defines need to be re-calculated.
  30068. */
  30069. MaterialDefines.prototype.markAllAsDirty = function () {
  30070. this._areTexturesDirty = true;
  30071. this._areAttributesDirty = true;
  30072. this._areLightsDirty = true;
  30073. this._areFresnelDirty = true;
  30074. this._areMiscDirty = true;
  30075. this._areImageProcessingDirty = true;
  30076. this._isDirty = true;
  30077. };
  30078. /**
  30079. * Marks the material to indicate that image processing needs to be re-calculated.
  30080. */
  30081. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30082. this._areImageProcessingDirty = true;
  30083. this._isDirty = true;
  30084. };
  30085. /**
  30086. * Marks the material to indicate the lights need to be re-calculated.
  30087. */
  30088. MaterialDefines.prototype.markAsLightDirty = function () {
  30089. this._areLightsDirty = true;
  30090. this._isDirty = true;
  30091. };
  30092. /**
  30093. * Marks the attribute state as changed.
  30094. */
  30095. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30096. this._areAttributesDirty = true;
  30097. this._isDirty = true;
  30098. };
  30099. /**
  30100. * Marks the texture state as changed.
  30101. */
  30102. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30103. this._areTexturesDirty = true;
  30104. this._isDirty = true;
  30105. };
  30106. /**
  30107. * Marks the fresnel state as changed.
  30108. */
  30109. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30110. this._areFresnelDirty = true;
  30111. this._isDirty = true;
  30112. };
  30113. /**
  30114. * Marks the misc state as changed.
  30115. */
  30116. MaterialDefines.prototype.markAsMiscDirty = function () {
  30117. this._areMiscDirty = true;
  30118. this._isDirty = true;
  30119. };
  30120. /**
  30121. * Rebuilds the material defines.
  30122. */
  30123. MaterialDefines.prototype.rebuild = function () {
  30124. if (this._keys) {
  30125. delete this._keys;
  30126. }
  30127. this._keys = [];
  30128. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30129. var key = _a[_i];
  30130. if (key[0] === "_") {
  30131. continue;
  30132. }
  30133. this._keys.push(key);
  30134. }
  30135. };
  30136. /**
  30137. * Specifies if two material defines are equal.
  30138. * @param other - A material define instance to compare to.
  30139. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30140. */
  30141. MaterialDefines.prototype.isEqual = function (other) {
  30142. if (this._keys.length !== other._keys.length) {
  30143. return false;
  30144. }
  30145. for (var index = 0; index < this._keys.length; index++) {
  30146. var prop = this._keys[index];
  30147. if (this[prop] !== other[prop]) {
  30148. return false;
  30149. }
  30150. }
  30151. return true;
  30152. };
  30153. /**
  30154. * Clones this instance's defines to another instance.
  30155. * @param other - material defines to clone values to.
  30156. */
  30157. MaterialDefines.prototype.cloneTo = function (other) {
  30158. if (this._keys.length !== other._keys.length) {
  30159. other._keys = this._keys.slice(0);
  30160. }
  30161. for (var index = 0; index < this._keys.length; index++) {
  30162. var prop = this._keys[index];
  30163. other[prop] = this[prop];
  30164. }
  30165. };
  30166. /**
  30167. * Resets the material define values.
  30168. */
  30169. MaterialDefines.prototype.reset = function () {
  30170. for (var index = 0; index < this._keys.length; index++) {
  30171. var prop = this._keys[index];
  30172. if (typeof (this[prop]) === "number") {
  30173. this[prop] = 0;
  30174. }
  30175. else {
  30176. this[prop] = false;
  30177. }
  30178. }
  30179. };
  30180. /**
  30181. * Converts the material define values to a string.
  30182. * @returns - String of material define information.
  30183. */
  30184. MaterialDefines.prototype.toString = function () {
  30185. var result = "";
  30186. for (var index = 0; index < this._keys.length; index++) {
  30187. var prop = this._keys[index];
  30188. var value = this[prop];
  30189. if (typeof (value) === "number") {
  30190. result += "#define " + prop + " " + this[prop] + "\n";
  30191. }
  30192. else if (value) {
  30193. result += "#define " + prop + "\n";
  30194. }
  30195. }
  30196. return result;
  30197. };
  30198. return MaterialDefines;
  30199. }());
  30200. BABYLON.MaterialDefines = MaterialDefines;
  30201. /**
  30202. * This offers the main features of a material in BJS.
  30203. */
  30204. var Material = /** @class */ (function () {
  30205. /**
  30206. * Creates a material instance.
  30207. * @param name - The name of the material.
  30208. * @param scene - The BJS scene to reference.
  30209. * @param doNotAdd - Specifies if the material should be added to the scene.
  30210. */
  30211. function Material(name, scene, doNotAdd) {
  30212. /**
  30213. * Specifies if the ready state should be checked on each call.
  30214. */
  30215. this.checkReadyOnEveryCall = false;
  30216. /**
  30217. * Specifies if the ready state should be checked once.
  30218. */
  30219. this.checkReadyOnlyOnce = false;
  30220. /**
  30221. * The state of the material.
  30222. */
  30223. this.state = "";
  30224. /**
  30225. * The alpha value of the material.
  30226. */
  30227. this._alpha = 1.0;
  30228. /**
  30229. * Specifies if back face culling is enabled.
  30230. */
  30231. this._backFaceCulling = true;
  30232. /**
  30233. * Specifies if the material should be serialized.
  30234. */
  30235. this.doNotSerialize = false;
  30236. /**
  30237. * Specifies if the effect should be stored on sub meshes.
  30238. */
  30239. this.storeEffectOnSubMeshes = false;
  30240. /**
  30241. * An event triggered when the material is disposed.
  30242. * @type {BABYLON.Observable}
  30243. */
  30244. this.onDisposeObservable = new BABYLON.Observable();
  30245. /**
  30246. * An event triggered when the material is bound.
  30247. * @type {BABYLON.Observable}
  30248. */
  30249. this.onBindObservable = new BABYLON.Observable();
  30250. /**
  30251. * An event triggered when the material is unbound.
  30252. * @type {BABYLON.Observable}
  30253. */
  30254. this.onUnBindObservable = new BABYLON.Observable();
  30255. /**
  30256. * Stores the value of the alpha mode.
  30257. */
  30258. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30259. /**
  30260. * Stores the state of the need depth pre-pass value.
  30261. */
  30262. this._needDepthPrePass = false;
  30263. /**
  30264. * Specifies if depth writing should be disabled.
  30265. */
  30266. this.disableDepthWrite = false;
  30267. /**
  30268. * Specifies if depth writing should be forced.
  30269. */
  30270. this.forceDepthWrite = false;
  30271. /**
  30272. * Specifies if there should be a separate pass for culling.
  30273. */
  30274. this.separateCullingPass = false;
  30275. /**
  30276. * Stores the state specifing if fog should be enabled.
  30277. */
  30278. this._fogEnabled = true;
  30279. /**
  30280. * Stores the size of points.
  30281. */
  30282. this.pointSize = 1.0;
  30283. /**
  30284. * Stores the z offset value.
  30285. */
  30286. this.zOffset = 0;
  30287. /**
  30288. * Specifies if the material was previously ready.
  30289. */
  30290. this._wasPreviouslyReady = false;
  30291. /**
  30292. * Stores the fill mode state.
  30293. */
  30294. this._fillMode = Material.TriangleFillMode;
  30295. this.name = name;
  30296. this.id = name || BABYLON.Tools.RandomId();
  30297. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30298. if (this._scene.useRightHandedSystem) {
  30299. this.sideOrientation = Material.ClockWiseSideOrientation;
  30300. }
  30301. else {
  30302. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30303. }
  30304. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30305. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30306. if (!doNotAdd) {
  30307. this._scene.materials.push(this);
  30308. }
  30309. }
  30310. Object.defineProperty(Material, "TriangleFillMode", {
  30311. /**
  30312. * Returns the triangle fill mode.
  30313. */
  30314. get: function () {
  30315. return Material._TriangleFillMode;
  30316. },
  30317. enumerable: true,
  30318. configurable: true
  30319. });
  30320. Object.defineProperty(Material, "WireFrameFillMode", {
  30321. /**
  30322. * Returns the wireframe mode.
  30323. */
  30324. get: function () {
  30325. return Material._WireFrameFillMode;
  30326. },
  30327. enumerable: true,
  30328. configurable: true
  30329. });
  30330. Object.defineProperty(Material, "PointFillMode", {
  30331. /**
  30332. * Returns the point fill mode.
  30333. */
  30334. get: function () {
  30335. return Material._PointFillMode;
  30336. },
  30337. enumerable: true,
  30338. configurable: true
  30339. });
  30340. Object.defineProperty(Material, "PointListDrawMode", {
  30341. /**
  30342. * Returns the point list draw mode.
  30343. */
  30344. get: function () {
  30345. return Material._PointListDrawMode;
  30346. },
  30347. enumerable: true,
  30348. configurable: true
  30349. });
  30350. Object.defineProperty(Material, "LineListDrawMode", {
  30351. /**
  30352. * Returns the line list draw mode.
  30353. */
  30354. get: function () {
  30355. return Material._LineListDrawMode;
  30356. },
  30357. enumerable: true,
  30358. configurable: true
  30359. });
  30360. Object.defineProperty(Material, "LineLoopDrawMode", {
  30361. /**
  30362. * Returns the line loop draw mode.
  30363. */
  30364. get: function () {
  30365. return Material._LineLoopDrawMode;
  30366. },
  30367. enumerable: true,
  30368. configurable: true
  30369. });
  30370. Object.defineProperty(Material, "LineStripDrawMode", {
  30371. /**
  30372. * Returns the line strip draw mode.
  30373. */
  30374. get: function () {
  30375. return Material._LineStripDrawMode;
  30376. },
  30377. enumerable: true,
  30378. configurable: true
  30379. });
  30380. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30381. /**
  30382. * Returns the triangle strip draw mode.
  30383. */
  30384. get: function () {
  30385. return Material._TriangleStripDrawMode;
  30386. },
  30387. enumerable: true,
  30388. configurable: true
  30389. });
  30390. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30391. /**
  30392. * Returns the triangle fan draw mode.
  30393. */
  30394. get: function () {
  30395. return Material._TriangleFanDrawMode;
  30396. },
  30397. enumerable: true,
  30398. configurable: true
  30399. });
  30400. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30401. /**
  30402. * Returns the clock-wise side orientation.
  30403. */
  30404. get: function () {
  30405. return Material._ClockWiseSideOrientation;
  30406. },
  30407. enumerable: true,
  30408. configurable: true
  30409. });
  30410. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30411. /**
  30412. * Returns the counter clock-wise side orientation.
  30413. */
  30414. get: function () {
  30415. return Material._CounterClockWiseSideOrientation;
  30416. },
  30417. enumerable: true,
  30418. configurable: true
  30419. });
  30420. Object.defineProperty(Material, "TextureDirtyFlag", {
  30421. /**
  30422. * Returns the dirty texture flag value.
  30423. */
  30424. get: function () {
  30425. return Material._TextureDirtyFlag;
  30426. },
  30427. enumerable: true,
  30428. configurable: true
  30429. });
  30430. Object.defineProperty(Material, "LightDirtyFlag", {
  30431. /**
  30432. * Returns the dirty light flag value.
  30433. */
  30434. get: function () {
  30435. return Material._LightDirtyFlag;
  30436. },
  30437. enumerable: true,
  30438. configurable: true
  30439. });
  30440. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30441. /**
  30442. * Returns the dirty fresnel flag value.
  30443. */
  30444. get: function () {
  30445. return Material._FresnelDirtyFlag;
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30451. /**
  30452. * Returns the dirty attributes flag value.
  30453. */
  30454. get: function () {
  30455. return Material._AttributesDirtyFlag;
  30456. },
  30457. enumerable: true,
  30458. configurable: true
  30459. });
  30460. Object.defineProperty(Material, "MiscDirtyFlag", {
  30461. /**
  30462. * Returns the dirty misc flag value.
  30463. */
  30464. get: function () {
  30465. return Material._MiscDirtyFlag;
  30466. },
  30467. enumerable: true,
  30468. configurable: true
  30469. });
  30470. Object.defineProperty(Material.prototype, "alpha", {
  30471. /**
  30472. * Gets the alpha value of the material.
  30473. */
  30474. get: function () {
  30475. return this._alpha;
  30476. },
  30477. /**
  30478. * Sets the alpha value of the material.
  30479. */
  30480. set: function (value) {
  30481. if (this._alpha === value) {
  30482. return;
  30483. }
  30484. this._alpha = value;
  30485. this.markAsDirty(Material.MiscDirtyFlag);
  30486. },
  30487. enumerable: true,
  30488. configurable: true
  30489. });
  30490. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30491. /**
  30492. * Gets the back-face culling state.
  30493. */
  30494. get: function () {
  30495. return this._backFaceCulling;
  30496. },
  30497. /**
  30498. * Sets the back-face culling state.
  30499. */
  30500. set: function (value) {
  30501. if (this._backFaceCulling === value) {
  30502. return;
  30503. }
  30504. this._backFaceCulling = value;
  30505. this.markAsDirty(Material.TextureDirtyFlag);
  30506. },
  30507. enumerable: true,
  30508. configurable: true
  30509. });
  30510. Object.defineProperty(Material.prototype, "onDispose", {
  30511. /**
  30512. * Called during a dispose event.
  30513. */
  30514. set: function (callback) {
  30515. if (this._onDisposeObserver) {
  30516. this.onDisposeObservable.remove(this._onDisposeObserver);
  30517. }
  30518. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30519. },
  30520. enumerable: true,
  30521. configurable: true
  30522. });
  30523. Object.defineProperty(Material.prototype, "onBind", {
  30524. /**
  30525. * Called during a bind event.
  30526. */
  30527. set: function (callback) {
  30528. if (this._onBindObserver) {
  30529. this.onBindObservable.remove(this._onBindObserver);
  30530. }
  30531. this._onBindObserver = this.onBindObservable.add(callback);
  30532. },
  30533. enumerable: true,
  30534. configurable: true
  30535. });
  30536. Object.defineProperty(Material.prototype, "alphaMode", {
  30537. /**
  30538. * Gets the value of the alpha mode.
  30539. */
  30540. get: function () {
  30541. return this._alphaMode;
  30542. },
  30543. /**
  30544. * Sets the value of the alpha mode.
  30545. */
  30546. set: function (value) {
  30547. if (this._alphaMode === value) {
  30548. return;
  30549. }
  30550. this._alphaMode = value;
  30551. this.markAsDirty(Material.TextureDirtyFlag);
  30552. },
  30553. enumerable: true,
  30554. configurable: true
  30555. });
  30556. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30557. /**
  30558. * Gets the depth pre-pass value.
  30559. */
  30560. get: function () {
  30561. return this._needDepthPrePass;
  30562. },
  30563. /**
  30564. * Sets the need depth pre-pass value.
  30565. */
  30566. set: function (value) {
  30567. if (this._needDepthPrePass === value) {
  30568. return;
  30569. }
  30570. this._needDepthPrePass = value;
  30571. if (this._needDepthPrePass) {
  30572. this.checkReadyOnEveryCall = true;
  30573. }
  30574. },
  30575. enumerable: true,
  30576. configurable: true
  30577. });
  30578. Object.defineProperty(Material.prototype, "fogEnabled", {
  30579. /**
  30580. * Gets the value of the fog enabled state.
  30581. */
  30582. get: function () {
  30583. return this._fogEnabled;
  30584. },
  30585. /**
  30586. * Sets the state for enabling fog.
  30587. */
  30588. set: function (value) {
  30589. if (this._fogEnabled === value) {
  30590. return;
  30591. }
  30592. this._fogEnabled = value;
  30593. this.markAsDirty(Material.MiscDirtyFlag);
  30594. },
  30595. enumerable: true,
  30596. configurable: true
  30597. });
  30598. Object.defineProperty(Material.prototype, "wireframe", {
  30599. /**
  30600. * Gets a value specifying if wireframe mode is enabled.
  30601. */
  30602. get: function () {
  30603. return this._fillMode === Material.WireFrameFillMode;
  30604. },
  30605. /**
  30606. * Sets the state of wireframe mode.
  30607. */
  30608. set: function (value) {
  30609. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30610. },
  30611. enumerable: true,
  30612. configurable: true
  30613. });
  30614. Object.defineProperty(Material.prototype, "pointsCloud", {
  30615. /**
  30616. * Gets the value specifying if point clouds are enabled.
  30617. */
  30618. get: function () {
  30619. return this._fillMode === Material.PointFillMode;
  30620. },
  30621. /**
  30622. * Sets the state of point cloud mode.
  30623. */
  30624. set: function (value) {
  30625. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30626. },
  30627. enumerable: true,
  30628. configurable: true
  30629. });
  30630. Object.defineProperty(Material.prototype, "fillMode", {
  30631. /**
  30632. * Gets the material fill mode.
  30633. */
  30634. get: function () {
  30635. return this._fillMode;
  30636. },
  30637. /**
  30638. * Sets the material fill mode.
  30639. */
  30640. set: function (value) {
  30641. if (this._fillMode === value) {
  30642. return;
  30643. }
  30644. this._fillMode = value;
  30645. this.markAsDirty(Material.MiscDirtyFlag);
  30646. },
  30647. enumerable: true,
  30648. configurable: true
  30649. });
  30650. /**
  30651. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30652. * subclasses should override adding information pertainent to themselves.
  30653. * @returns - String with material information.
  30654. */
  30655. Material.prototype.toString = function (fullDetails) {
  30656. var ret = "Name: " + this.name;
  30657. if (fullDetails) {
  30658. }
  30659. return ret;
  30660. };
  30661. /**
  30662. * Gets the class name of the material.
  30663. * @returns - String with the class name of the material.
  30664. */
  30665. Material.prototype.getClassName = function () {
  30666. return "Material";
  30667. };
  30668. Object.defineProperty(Material.prototype, "isFrozen", {
  30669. /**
  30670. * Specifies if updates for the material been locked.
  30671. */
  30672. get: function () {
  30673. return this.checkReadyOnlyOnce;
  30674. },
  30675. enumerable: true,
  30676. configurable: true
  30677. });
  30678. /**
  30679. * Locks updates for the material.
  30680. */
  30681. Material.prototype.freeze = function () {
  30682. this.checkReadyOnlyOnce = true;
  30683. };
  30684. /**
  30685. * Unlocks updates for the material.
  30686. */
  30687. Material.prototype.unfreeze = function () {
  30688. this.checkReadyOnlyOnce = false;
  30689. };
  30690. /**
  30691. * Specifies if the material is ready to be used.
  30692. * @param mesh - BJS mesh.
  30693. * @param useInstances - Specifies if instances should be used.
  30694. * @returns - Boolean indicating if the material is ready to be used.
  30695. */
  30696. Material.prototype.isReady = function (mesh, useInstances) {
  30697. return true;
  30698. };
  30699. /**
  30700. * Specifies that the submesh is ready to be used.
  30701. * @param mesh - BJS mesh.
  30702. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30703. * @param useInstances - Specifies that instances should be used.
  30704. * @returns - boolean indicating that the submesh is ready or not.
  30705. */
  30706. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30707. return false;
  30708. };
  30709. /**
  30710. * Returns the material effect.
  30711. * @returns - Nullable material effect.
  30712. */
  30713. Material.prototype.getEffect = function () {
  30714. return this._effect;
  30715. };
  30716. /**
  30717. * Returns the BJS scene.
  30718. * @returns - BJS Scene.
  30719. */
  30720. Material.prototype.getScene = function () {
  30721. return this._scene;
  30722. };
  30723. /**
  30724. * Specifies if the material will require alpha blending
  30725. * @returns - Boolean specifying if alpha blending is needed.
  30726. */
  30727. Material.prototype.needAlphaBlending = function () {
  30728. return (this.alpha < 1.0);
  30729. };
  30730. /**
  30731. * Specifies if the mesh will require alpha blending.
  30732. * @param mesh - BJS mesh.
  30733. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30734. */
  30735. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30736. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30737. };
  30738. /**
  30739. * Specifies if this material should be rendered in alpha test mode.
  30740. * @returns - Boolean specifying if an alpha test is needed.
  30741. */
  30742. Material.prototype.needAlphaTesting = function () {
  30743. return false;
  30744. };
  30745. /**
  30746. * Gets the texture used for the alpha test.
  30747. * @returns - Nullable alpha test texture.
  30748. */
  30749. Material.prototype.getAlphaTestTexture = function () {
  30750. return null;
  30751. };
  30752. /**
  30753. * Marks the material to indicate that it needs to be re-calculated.
  30754. */
  30755. Material.prototype.markDirty = function () {
  30756. this._wasPreviouslyReady = false;
  30757. };
  30758. Material.prototype._preBind = function (effect, overrideOrientation) {
  30759. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30760. var engine = this._scene.getEngine();
  30761. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30762. var reverse = orientation === Material.ClockWiseSideOrientation;
  30763. engine.enableEffect(effect ? effect : this._effect);
  30764. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30765. return reverse;
  30766. };
  30767. /**
  30768. * Binds the material to the mesh.
  30769. * @param world - World transformation matrix.
  30770. * @param mesh - Mesh to bind the material to.
  30771. */
  30772. Material.prototype.bind = function (world, mesh) {
  30773. };
  30774. /**
  30775. * Binds the submesh to the material.
  30776. * @param world - World transformation matrix.
  30777. * @param mesh - Mesh containing the submesh.
  30778. * @param subMesh - Submesh to bind the material to.
  30779. */
  30780. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30781. };
  30782. /**
  30783. * Binds the world matrix to the material.
  30784. * @param world - World transformation matrix.
  30785. */
  30786. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30787. };
  30788. /**
  30789. * Binds the scene's uniform buffer to the effect.
  30790. * @param effect - Effect to bind to the scene uniform buffer.
  30791. * @param sceneUbo - Scene uniform buffer.
  30792. */
  30793. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30794. sceneUbo.bindToEffect(effect, "Scene");
  30795. };
  30796. /**
  30797. * Binds the view matrix to the effect.
  30798. * @param effect - Effect to bind the view matrix to.
  30799. */
  30800. Material.prototype.bindView = function (effect) {
  30801. if (!this._useUBO) {
  30802. effect.setMatrix("view", this.getScene().getViewMatrix());
  30803. }
  30804. else {
  30805. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30806. }
  30807. };
  30808. /**
  30809. * Binds the view projection matrix to the effect.
  30810. * @param effect - Effect to bind the view projection matrix to.
  30811. */
  30812. Material.prototype.bindViewProjection = function (effect) {
  30813. if (!this._useUBO) {
  30814. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30815. }
  30816. else {
  30817. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30818. }
  30819. };
  30820. /**
  30821. * Specifies if material alpha testing should be turned on for the mesh.
  30822. * @param mesh - BJS mesh.
  30823. */
  30824. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30825. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30826. };
  30827. /**
  30828. * Processes to execute after binding the material to a mesh.
  30829. * @param mesh - BJS mesh.
  30830. */
  30831. Material.prototype._afterBind = function (mesh) {
  30832. this._scene._cachedMaterial = this;
  30833. if (mesh) {
  30834. this._scene._cachedVisibility = mesh.visibility;
  30835. }
  30836. else {
  30837. this._scene._cachedVisibility = 1;
  30838. }
  30839. if (mesh) {
  30840. this.onBindObservable.notifyObservers(mesh);
  30841. }
  30842. if (this.disableDepthWrite) {
  30843. var engine = this._scene.getEngine();
  30844. this._cachedDepthWriteState = engine.getDepthWrite();
  30845. engine.setDepthWrite(false);
  30846. }
  30847. };
  30848. /**
  30849. * Unbinds the material from the mesh.
  30850. */
  30851. Material.prototype.unbind = function () {
  30852. this.onUnBindObservable.notifyObservers(this);
  30853. if (this.disableDepthWrite) {
  30854. var engine = this._scene.getEngine();
  30855. engine.setDepthWrite(this._cachedDepthWriteState);
  30856. }
  30857. };
  30858. /**
  30859. * Gets the active textures from the material.
  30860. * @returns - Array of textures.
  30861. */
  30862. Material.prototype.getActiveTextures = function () {
  30863. return [];
  30864. };
  30865. /**
  30866. * Specifies if the material uses a texture.
  30867. * @param texture - Texture to check against the material.
  30868. * @returns - Boolean specifying if the material uses the texture.
  30869. */
  30870. Material.prototype.hasTexture = function (texture) {
  30871. return false;
  30872. };
  30873. /**
  30874. * Makes a duplicate of the material, and gives it a new name.
  30875. * @param name - Name to call the duplicated material.
  30876. * @returns - Nullable cloned material
  30877. */
  30878. Material.prototype.clone = function (name) {
  30879. return null;
  30880. };
  30881. /**
  30882. * Gets the meshes bound to the material.
  30883. * @returns - Array of meshes bound to the material.
  30884. */
  30885. Material.prototype.getBindedMeshes = function () {
  30886. var result = new Array();
  30887. for (var index = 0; index < this._scene.meshes.length; index++) {
  30888. var mesh = this._scene.meshes[index];
  30889. if (mesh.material === this) {
  30890. result.push(mesh);
  30891. }
  30892. }
  30893. return result;
  30894. };
  30895. /**
  30896. * Force shader compilation
  30897. * @param mesh - BJS mesh.
  30898. * @param onCompiled - function to execute once the material is compiled.
  30899. * @param options - options to pass to this function.
  30900. */
  30901. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30902. var _this = this;
  30903. var localOptions = __assign({ clipPlane: false }, options);
  30904. var subMesh = new BABYLON.BaseSubMesh();
  30905. var scene = this.getScene();
  30906. var checkReady = function () {
  30907. if (!_this._scene || !_this._scene.getEngine()) {
  30908. return;
  30909. }
  30910. if (subMesh._materialDefines) {
  30911. subMesh._materialDefines._renderId = -1;
  30912. }
  30913. var clipPlaneState = scene.clipPlane;
  30914. if (localOptions.clipPlane) {
  30915. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30916. }
  30917. if (_this.storeEffectOnSubMeshes) {
  30918. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30919. if (onCompiled) {
  30920. onCompiled(_this);
  30921. }
  30922. }
  30923. else {
  30924. setTimeout(checkReady, 16);
  30925. }
  30926. }
  30927. else {
  30928. if (_this.isReady(mesh)) {
  30929. if (onCompiled) {
  30930. onCompiled(_this);
  30931. }
  30932. }
  30933. else {
  30934. setTimeout(checkReady, 16);
  30935. }
  30936. }
  30937. if (localOptions.clipPlane) {
  30938. scene.clipPlane = clipPlaneState;
  30939. }
  30940. };
  30941. checkReady();
  30942. };
  30943. /**
  30944. * Force shader compilation.
  30945. * @param mesh The mesh that will use this material
  30946. * @param options Additional options for compiling the shaders
  30947. * @returns A promise that resolves when the compilation completes
  30948. */
  30949. Material.prototype.forceCompilationAsync = function (mesh, options) {
  30950. var _this = this;
  30951. return new Promise(function (resolve) {
  30952. _this.forceCompilation(mesh, function () {
  30953. resolve();
  30954. }, options);
  30955. });
  30956. };
  30957. /**
  30958. * Marks a define in the material to indicate that it needs to be re-computed.
  30959. * @param flag - Material define flag.
  30960. */
  30961. Material.prototype.markAsDirty = function (flag) {
  30962. if (flag & Material.TextureDirtyFlag) {
  30963. this._markAllSubMeshesAsTexturesDirty();
  30964. }
  30965. if (flag & Material.LightDirtyFlag) {
  30966. this._markAllSubMeshesAsLightsDirty();
  30967. }
  30968. if (flag & Material.FresnelDirtyFlag) {
  30969. this._markAllSubMeshesAsFresnelDirty();
  30970. }
  30971. if (flag & Material.AttributesDirtyFlag) {
  30972. this._markAllSubMeshesAsAttributesDirty();
  30973. }
  30974. if (flag & Material.MiscDirtyFlag) {
  30975. this._markAllSubMeshesAsMiscDirty();
  30976. }
  30977. this.getScene().resetCachedMaterial();
  30978. };
  30979. /**
  30980. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30981. * @param func - function which checks material defines against the submeshes.
  30982. */
  30983. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30984. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30985. var mesh = _a[_i];
  30986. if (!mesh.subMeshes) {
  30987. continue;
  30988. }
  30989. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30990. var subMesh = _c[_b];
  30991. if (subMesh.getMaterial() !== this) {
  30992. continue;
  30993. }
  30994. if (!subMesh._materialDefines) {
  30995. continue;
  30996. }
  30997. func(subMesh._materialDefines);
  30998. }
  30999. }
  31000. };
  31001. /**
  31002. * Indicates that image processing needs to be re-calculated for all submeshes.
  31003. */
  31004. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31005. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31006. };
  31007. /**
  31008. * Indicates that textures need to be re-calculated for all submeshes.
  31009. */
  31010. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31011. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31012. };
  31013. /**
  31014. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31015. */
  31016. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31017. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31018. };
  31019. /**
  31020. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31021. */
  31022. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31023. this._markAllSubMeshesAsDirty(function (defines) {
  31024. defines.markAsFresnelDirty();
  31025. defines.markAsMiscDirty();
  31026. });
  31027. };
  31028. /**
  31029. * Indicates that lights need to be re-calculated for all submeshes.
  31030. */
  31031. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31032. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31033. };
  31034. /**
  31035. * Indicates that attributes need to be re-calculated for all submeshes.
  31036. */
  31037. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31038. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31039. };
  31040. /**
  31041. * Indicates that misc needs to be re-calculated for all submeshes.
  31042. */
  31043. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31044. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31045. };
  31046. /**
  31047. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31048. */
  31049. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31050. this._markAllSubMeshesAsDirty(function (defines) {
  31051. defines.markAsTexturesDirty();
  31052. defines.markAsMiscDirty();
  31053. });
  31054. };
  31055. /**
  31056. * Disposes the material.
  31057. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31058. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31059. */
  31060. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31061. // Animations
  31062. this.getScene().stopAnimation(this);
  31063. // Remove from scene
  31064. var index = this._scene.materials.indexOf(this);
  31065. if (index >= 0) {
  31066. this._scene.materials.splice(index, 1);
  31067. }
  31068. // Remove from meshes
  31069. for (index = 0; index < this._scene.meshes.length; index++) {
  31070. var mesh = this._scene.meshes[index];
  31071. if (mesh.material === this) {
  31072. mesh.material = null;
  31073. if (mesh.geometry) {
  31074. var geometry = (mesh.geometry);
  31075. if (this.storeEffectOnSubMeshes) {
  31076. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31077. var subMesh = _a[_i];
  31078. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31079. if (forceDisposeEffect && subMesh._materialEffect) {
  31080. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31081. }
  31082. }
  31083. }
  31084. else {
  31085. geometry._releaseVertexArrayObject(this._effect);
  31086. }
  31087. }
  31088. }
  31089. }
  31090. this._uniformBuffer.dispose();
  31091. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31092. if (forceDisposeEffect && this._effect) {
  31093. if (!this.storeEffectOnSubMeshes) {
  31094. this._scene.getEngine()._releaseEffect(this._effect);
  31095. }
  31096. this._effect = null;
  31097. }
  31098. // Callback
  31099. this.onDisposeObservable.notifyObservers(this);
  31100. this.onDisposeObservable.clear();
  31101. this.onBindObservable.clear();
  31102. this.onUnBindObservable.clear();
  31103. };
  31104. /**
  31105. * Serializes this material.
  31106. * @returns - serialized material object.
  31107. */
  31108. Material.prototype.serialize = function () {
  31109. return BABYLON.SerializationHelper.Serialize(this);
  31110. };
  31111. /**
  31112. * Creates a MultiMaterial from parse MultiMaterial data.
  31113. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31114. * @param scene - BJS scene.
  31115. * @returns - MultiMaterial.
  31116. */
  31117. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31118. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31119. multiMaterial.id = parsedMultiMaterial.id;
  31120. if (BABYLON.Tags) {
  31121. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31122. }
  31123. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31124. var subMatId = parsedMultiMaterial.materials[matIndex];
  31125. if (subMatId) {
  31126. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31127. }
  31128. else {
  31129. multiMaterial.subMaterials.push(null);
  31130. }
  31131. }
  31132. return multiMaterial;
  31133. };
  31134. /**
  31135. * Creates a material from parsed material data.
  31136. * @param parsedMaterial - Parsed material data.
  31137. * @param scene - BJS scene.
  31138. * @param rootUrl - Root URL containing the material information.
  31139. * @returns - Parsed material.
  31140. */
  31141. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31142. if (!parsedMaterial.customType) {
  31143. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31144. }
  31145. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31146. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31147. if (!BABYLON.LegacyPBRMaterial) {
  31148. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31149. return;
  31150. }
  31151. }
  31152. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31153. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31154. ;
  31155. };
  31156. // Triangle views
  31157. Material._TriangleFillMode = 0;
  31158. Material._WireFrameFillMode = 1;
  31159. Material._PointFillMode = 2;
  31160. // Draw modes
  31161. Material._PointListDrawMode = 3;
  31162. Material._LineListDrawMode = 4;
  31163. Material._LineLoopDrawMode = 5;
  31164. Material._LineStripDrawMode = 6;
  31165. Material._TriangleStripDrawMode = 7;
  31166. Material._TriangleFanDrawMode = 8;
  31167. /**
  31168. * Stores the clock-wise side orientation.
  31169. */
  31170. Material._ClockWiseSideOrientation = 0;
  31171. /**
  31172. * Stores the counter clock-wise side orientation.
  31173. */
  31174. Material._CounterClockWiseSideOrientation = 1;
  31175. /**
  31176. * The dirty texture flag value.
  31177. */
  31178. Material._TextureDirtyFlag = 1;
  31179. /**
  31180. * The dirty light flag value.
  31181. */
  31182. Material._LightDirtyFlag = 2;
  31183. /**
  31184. * The dirty fresnel flag value.
  31185. */
  31186. Material._FresnelDirtyFlag = 4;
  31187. /**
  31188. * The dirty attribute flag value.
  31189. */
  31190. Material._AttributesDirtyFlag = 8;
  31191. /**
  31192. * The dirty misc flag value.
  31193. */
  31194. Material._MiscDirtyFlag = 16;
  31195. __decorate([
  31196. BABYLON.serialize()
  31197. ], Material.prototype, "id", void 0);
  31198. __decorate([
  31199. BABYLON.serialize()
  31200. ], Material.prototype, "name", void 0);
  31201. __decorate([
  31202. BABYLON.serialize()
  31203. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31204. __decorate([
  31205. BABYLON.serialize()
  31206. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31207. __decorate([
  31208. BABYLON.serialize()
  31209. ], Material.prototype, "state", void 0);
  31210. __decorate([
  31211. BABYLON.serialize("alpha")
  31212. ], Material.prototype, "_alpha", void 0);
  31213. __decorate([
  31214. BABYLON.serialize("backFaceCulling")
  31215. ], Material.prototype, "_backFaceCulling", void 0);
  31216. __decorate([
  31217. BABYLON.serialize()
  31218. ], Material.prototype, "sideOrientation", void 0);
  31219. __decorate([
  31220. BABYLON.serialize("alphaMode")
  31221. ], Material.prototype, "_alphaMode", void 0);
  31222. __decorate([
  31223. BABYLON.serialize()
  31224. ], Material.prototype, "_needDepthPrePass", void 0);
  31225. __decorate([
  31226. BABYLON.serialize()
  31227. ], Material.prototype, "disableDepthWrite", void 0);
  31228. __decorate([
  31229. BABYLON.serialize()
  31230. ], Material.prototype, "forceDepthWrite", void 0);
  31231. __decorate([
  31232. BABYLON.serialize()
  31233. ], Material.prototype, "separateCullingPass", void 0);
  31234. __decorate([
  31235. BABYLON.serialize("fogEnabled")
  31236. ], Material.prototype, "_fogEnabled", void 0);
  31237. __decorate([
  31238. BABYLON.serialize()
  31239. ], Material.prototype, "pointSize", void 0);
  31240. __decorate([
  31241. BABYLON.serialize()
  31242. ], Material.prototype, "zOffset", void 0);
  31243. __decorate([
  31244. BABYLON.serialize()
  31245. ], Material.prototype, "wireframe", null);
  31246. __decorate([
  31247. BABYLON.serialize()
  31248. ], Material.prototype, "pointsCloud", null);
  31249. __decorate([
  31250. BABYLON.serialize()
  31251. ], Material.prototype, "fillMode", null);
  31252. return Material;
  31253. }());
  31254. BABYLON.Material = Material;
  31255. })(BABYLON || (BABYLON = {}));
  31256. //# sourceMappingURL=babylon.material.js.map
  31257. var BABYLON;
  31258. (function (BABYLON) {
  31259. var UniformBuffer = /** @class */ (function () {
  31260. /**
  31261. * Uniform buffer objects.
  31262. *
  31263. * Handles blocks of uniform on the GPU.
  31264. *
  31265. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31266. *
  31267. * For more information, please refer to :
  31268. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31269. */
  31270. function UniformBuffer(engine, data, dynamic) {
  31271. this._engine = engine;
  31272. this._noUBO = !engine.supportsUniformBuffers;
  31273. this._dynamic = dynamic;
  31274. this._data = data || [];
  31275. this._uniformLocations = {};
  31276. this._uniformSizes = {};
  31277. this._uniformLocationPointer = 0;
  31278. this._needSync = false;
  31279. if (this._noUBO) {
  31280. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31281. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31282. this.updateFloat = this._updateFloatForEffect;
  31283. this.updateFloat2 = this._updateFloat2ForEffect;
  31284. this.updateFloat3 = this._updateFloat3ForEffect;
  31285. this.updateFloat4 = this._updateFloat4ForEffect;
  31286. this.updateMatrix = this._updateMatrixForEffect;
  31287. this.updateVector3 = this._updateVector3ForEffect;
  31288. this.updateVector4 = this._updateVector4ForEffect;
  31289. this.updateColor3 = this._updateColor3ForEffect;
  31290. this.updateColor4 = this._updateColor4ForEffect;
  31291. }
  31292. else {
  31293. this._engine._uniformBuffers.push(this);
  31294. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31295. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31296. this.updateFloat = this._updateFloatForUniform;
  31297. this.updateFloat2 = this._updateFloat2ForUniform;
  31298. this.updateFloat3 = this._updateFloat3ForUniform;
  31299. this.updateFloat4 = this._updateFloat4ForUniform;
  31300. this.updateMatrix = this._updateMatrixForUniform;
  31301. this.updateVector3 = this._updateVector3ForUniform;
  31302. this.updateVector4 = this._updateVector4ForUniform;
  31303. this.updateColor3 = this._updateColor3ForUniform;
  31304. this.updateColor4 = this._updateColor4ForUniform;
  31305. }
  31306. }
  31307. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31308. // Properties
  31309. /**
  31310. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31311. * or just falling back on setUniformXXX calls.
  31312. */
  31313. get: function () {
  31314. return !this._noUBO;
  31315. },
  31316. enumerable: true,
  31317. configurable: true
  31318. });
  31319. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31320. /**
  31321. * Indicates if the WebGL underlying uniform buffer is in sync
  31322. * with the javascript cache data.
  31323. */
  31324. get: function () {
  31325. return !this._needSync;
  31326. },
  31327. enumerable: true,
  31328. configurable: true
  31329. });
  31330. /**
  31331. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31332. * Also, a dynamic UniformBuffer will disable cache verification and always
  31333. * update the underlying WebGL uniform buffer to the GPU.
  31334. */
  31335. UniformBuffer.prototype.isDynamic = function () {
  31336. return this._dynamic !== undefined;
  31337. };
  31338. /**
  31339. * The data cache on JS side.
  31340. */
  31341. UniformBuffer.prototype.getData = function () {
  31342. return this._bufferData;
  31343. };
  31344. /**
  31345. * The underlying WebGL Uniform buffer.
  31346. */
  31347. UniformBuffer.prototype.getBuffer = function () {
  31348. return this._buffer;
  31349. };
  31350. /**
  31351. * std140 layout specifies how to align data within an UBO structure.
  31352. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31353. * for specs.
  31354. */
  31355. UniformBuffer.prototype._fillAlignment = function (size) {
  31356. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31357. // and 4x4 matrices
  31358. // TODO : change if other types are used
  31359. var alignment;
  31360. if (size <= 2) {
  31361. alignment = size;
  31362. }
  31363. else {
  31364. alignment = 4;
  31365. }
  31366. if ((this._uniformLocationPointer % alignment) !== 0) {
  31367. var oldPointer = this._uniformLocationPointer;
  31368. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31369. var diff = this._uniformLocationPointer - oldPointer;
  31370. for (var i = 0; i < diff; i++) {
  31371. this._data.push(0);
  31372. }
  31373. }
  31374. };
  31375. /**
  31376. * Adds an uniform in the buffer.
  31377. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31378. * for the layout to be correct !
  31379. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31380. * @param {number|number[]} size Data size, or data directly.
  31381. */
  31382. UniformBuffer.prototype.addUniform = function (name, size) {
  31383. if (this._noUBO) {
  31384. return;
  31385. }
  31386. if (this._uniformLocations[name] !== undefined) {
  31387. // Already existing uniform
  31388. return;
  31389. }
  31390. // This function must be called in the order of the shader layout !
  31391. // size can be the size of the uniform, or data directly
  31392. var data;
  31393. if (size instanceof Array) {
  31394. data = size;
  31395. size = data.length;
  31396. }
  31397. else {
  31398. size = size;
  31399. data = [];
  31400. // Fill with zeros
  31401. for (var i = 0; i < size; i++) {
  31402. data.push(0);
  31403. }
  31404. }
  31405. this._fillAlignment(size);
  31406. this._uniformSizes[name] = size;
  31407. this._uniformLocations[name] = this._uniformLocationPointer;
  31408. this._uniformLocationPointer += size;
  31409. for (var i = 0; i < size; i++) {
  31410. this._data.push(data[i]);
  31411. }
  31412. this._needSync = true;
  31413. };
  31414. /**
  31415. * Wrapper for addUniform.
  31416. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31417. * @param {Matrix} mat A 4x4 matrix.
  31418. */
  31419. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31420. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31421. };
  31422. /**
  31423. * Wrapper for addUniform.
  31424. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31425. * @param {number} x
  31426. * @param {number} y
  31427. */
  31428. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31429. var temp = [x, y];
  31430. this.addUniform(name, temp);
  31431. };
  31432. /**
  31433. * Wrapper for addUniform.
  31434. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31435. * @param {number} x
  31436. * @param {number} y
  31437. * @param {number} z
  31438. */
  31439. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31440. var temp = [x, y, z];
  31441. this.addUniform(name, temp);
  31442. };
  31443. /**
  31444. * Wrapper for addUniform.
  31445. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31446. * @param {Color3} color
  31447. */
  31448. UniformBuffer.prototype.addColor3 = function (name, color) {
  31449. var temp = new Array();
  31450. color.toArray(temp);
  31451. this.addUniform(name, temp);
  31452. };
  31453. /**
  31454. * Wrapper for addUniform.
  31455. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31456. * @param {Color3} color
  31457. * @param {number} alpha
  31458. */
  31459. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31460. var temp = new Array();
  31461. color.toArray(temp);
  31462. temp.push(alpha);
  31463. this.addUniform(name, temp);
  31464. };
  31465. /**
  31466. * Wrapper for addUniform.
  31467. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31468. * @param {Vector3} vector
  31469. */
  31470. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31471. var temp = new Array();
  31472. vector.toArray(temp);
  31473. this.addUniform(name, temp);
  31474. };
  31475. /**
  31476. * Wrapper for addUniform.
  31477. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31478. */
  31479. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31480. this.addUniform(name, 12);
  31481. };
  31482. /**
  31483. * Wrapper for addUniform.
  31484. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31485. */
  31486. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31487. this.addUniform(name, 8);
  31488. };
  31489. /**
  31490. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31491. */
  31492. UniformBuffer.prototype.create = function () {
  31493. if (this._noUBO) {
  31494. return;
  31495. }
  31496. if (this._buffer) {
  31497. return; // nothing to do
  31498. }
  31499. // See spec, alignment must be filled as a vec4
  31500. this._fillAlignment(4);
  31501. this._bufferData = new Float32Array(this._data);
  31502. this._rebuild();
  31503. this._needSync = true;
  31504. };
  31505. UniformBuffer.prototype._rebuild = function () {
  31506. if (this._noUBO) {
  31507. return;
  31508. }
  31509. if (this._dynamic) {
  31510. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31511. }
  31512. else {
  31513. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31514. }
  31515. };
  31516. /**
  31517. * Updates the WebGL Uniform Buffer on the GPU.
  31518. * If the `dynamic` flag is set to true, no cache comparison is done.
  31519. * Otherwise, the buffer will be updated only if the cache differs.
  31520. */
  31521. UniformBuffer.prototype.update = function () {
  31522. if (!this._buffer) {
  31523. this.create();
  31524. return;
  31525. }
  31526. if (!this._dynamic && !this._needSync) {
  31527. return;
  31528. }
  31529. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31530. this._needSync = false;
  31531. };
  31532. /**
  31533. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31534. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31535. * @param {number[]|Float32Array} data Flattened data
  31536. * @param {number} size Size of the data.
  31537. */
  31538. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31539. var location = this._uniformLocations[uniformName];
  31540. if (location === undefined) {
  31541. if (this._buffer) {
  31542. // Cannot add an uniform if the buffer is already created
  31543. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31544. return;
  31545. }
  31546. this.addUniform(uniformName, size);
  31547. location = this._uniformLocations[uniformName];
  31548. }
  31549. if (!this._buffer) {
  31550. this.create();
  31551. }
  31552. if (!this._dynamic) {
  31553. // Cache for static uniform buffers
  31554. var changed = false;
  31555. for (var i = 0; i < size; i++) {
  31556. if (this._bufferData[location + i] !== data[i]) {
  31557. changed = true;
  31558. this._bufferData[location + i] = data[i];
  31559. }
  31560. }
  31561. this._needSync = this._needSync || changed;
  31562. }
  31563. else {
  31564. // No cache for dynamic
  31565. for (var i = 0; i < size; i++) {
  31566. this._bufferData[location + i] = data[i];
  31567. }
  31568. }
  31569. };
  31570. // Update methods
  31571. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31572. // To match std140, matrix must be realigned
  31573. for (var i = 0; i < 3; i++) {
  31574. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31575. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31576. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31577. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31578. }
  31579. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31580. };
  31581. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31582. this._currentEffect.setMatrix3x3(name, matrix);
  31583. };
  31584. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31585. this._currentEffect.setMatrix2x2(name, matrix);
  31586. };
  31587. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31588. // To match std140, matrix must be realigned
  31589. for (var i = 0; i < 2; i++) {
  31590. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31591. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31592. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31593. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31594. }
  31595. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31596. };
  31597. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31598. this._currentEffect.setFloat(name, x);
  31599. };
  31600. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31601. UniformBuffer._tempBuffer[0] = x;
  31602. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31603. };
  31604. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31605. if (suffix === void 0) { suffix = ""; }
  31606. this._currentEffect.setFloat2(name + suffix, x, y);
  31607. };
  31608. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31609. if (suffix === void 0) { suffix = ""; }
  31610. UniformBuffer._tempBuffer[0] = x;
  31611. UniformBuffer._tempBuffer[1] = y;
  31612. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31613. };
  31614. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31615. if (suffix === void 0) { suffix = ""; }
  31616. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31617. };
  31618. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31619. if (suffix === void 0) { suffix = ""; }
  31620. UniformBuffer._tempBuffer[0] = x;
  31621. UniformBuffer._tempBuffer[1] = y;
  31622. UniformBuffer._tempBuffer[2] = z;
  31623. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31624. };
  31625. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31626. if (suffix === void 0) { suffix = ""; }
  31627. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31628. };
  31629. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31630. if (suffix === void 0) { suffix = ""; }
  31631. UniformBuffer._tempBuffer[0] = x;
  31632. UniformBuffer._tempBuffer[1] = y;
  31633. UniformBuffer._tempBuffer[2] = z;
  31634. UniformBuffer._tempBuffer[3] = w;
  31635. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31636. };
  31637. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31638. this._currentEffect.setMatrix(name, mat);
  31639. };
  31640. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31641. this.updateUniform(name, mat.toArray(), 16);
  31642. };
  31643. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31644. this._currentEffect.setVector3(name, vector);
  31645. };
  31646. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31647. vector.toArray(UniformBuffer._tempBuffer);
  31648. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31649. };
  31650. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31651. this._currentEffect.setVector4(name, vector);
  31652. };
  31653. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31654. vector.toArray(UniformBuffer._tempBuffer);
  31655. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31656. };
  31657. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31658. if (suffix === void 0) { suffix = ""; }
  31659. this._currentEffect.setColor3(name + suffix, color);
  31660. };
  31661. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31662. if (suffix === void 0) { suffix = ""; }
  31663. color.toArray(UniformBuffer._tempBuffer);
  31664. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31665. };
  31666. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31667. if (suffix === void 0) { suffix = ""; }
  31668. this._currentEffect.setColor4(name + suffix, color, alpha);
  31669. };
  31670. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31671. if (suffix === void 0) { suffix = ""; }
  31672. color.toArray(UniformBuffer._tempBuffer);
  31673. UniformBuffer._tempBuffer[3] = alpha;
  31674. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31675. };
  31676. /**
  31677. * Sets a sampler uniform on the effect.
  31678. * @param {string} name Name of the sampler.
  31679. * @param {Texture} texture
  31680. */
  31681. UniformBuffer.prototype.setTexture = function (name, texture) {
  31682. this._currentEffect.setTexture(name, texture);
  31683. };
  31684. /**
  31685. * Directly updates the value of the uniform in the cache AND on the GPU.
  31686. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31687. * @param {number[]|Float32Array} data Flattened data
  31688. */
  31689. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31690. this.updateUniform(uniformName, data, data.length);
  31691. this.update();
  31692. };
  31693. /**
  31694. * Binds this uniform buffer to an effect.
  31695. * @param {Effect} effect
  31696. * @param {string} name Name of the uniform block in the shader.
  31697. */
  31698. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31699. this._currentEffect = effect;
  31700. if (this._noUBO || !this._buffer) {
  31701. return;
  31702. }
  31703. effect.bindUniformBuffer(this._buffer, name);
  31704. };
  31705. /**
  31706. * Disposes the uniform buffer.
  31707. */
  31708. UniformBuffer.prototype.dispose = function () {
  31709. if (this._noUBO) {
  31710. return;
  31711. }
  31712. var index = this._engine._uniformBuffers.indexOf(this);
  31713. if (index !== -1) {
  31714. this._engine._uniformBuffers.splice(index, 1);
  31715. }
  31716. if (!this._buffer) {
  31717. return;
  31718. }
  31719. if (this._engine._releaseBuffer(this._buffer)) {
  31720. this._buffer = null;
  31721. }
  31722. };
  31723. // Pool for avoiding memory leaks
  31724. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31725. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31726. return UniformBuffer;
  31727. }());
  31728. BABYLON.UniformBuffer = UniformBuffer;
  31729. })(BABYLON || (BABYLON = {}));
  31730. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31731. var BABYLON;
  31732. (function (BABYLON) {
  31733. var VertexData = /** @class */ (function () {
  31734. function VertexData() {
  31735. }
  31736. VertexData.prototype.set = function (data, kind) {
  31737. switch (kind) {
  31738. case BABYLON.VertexBuffer.PositionKind:
  31739. this.positions = data;
  31740. break;
  31741. case BABYLON.VertexBuffer.NormalKind:
  31742. this.normals = data;
  31743. break;
  31744. case BABYLON.VertexBuffer.TangentKind:
  31745. this.tangents = data;
  31746. break;
  31747. case BABYLON.VertexBuffer.UVKind:
  31748. this.uvs = data;
  31749. break;
  31750. case BABYLON.VertexBuffer.UV2Kind:
  31751. this.uvs2 = data;
  31752. break;
  31753. case BABYLON.VertexBuffer.UV3Kind:
  31754. this.uvs3 = data;
  31755. break;
  31756. case BABYLON.VertexBuffer.UV4Kind:
  31757. this.uvs4 = data;
  31758. break;
  31759. case BABYLON.VertexBuffer.UV5Kind:
  31760. this.uvs5 = data;
  31761. break;
  31762. case BABYLON.VertexBuffer.UV6Kind:
  31763. this.uvs6 = data;
  31764. break;
  31765. case BABYLON.VertexBuffer.ColorKind:
  31766. this.colors = data;
  31767. break;
  31768. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31769. this.matricesIndices = data;
  31770. break;
  31771. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31772. this.matricesWeights = data;
  31773. break;
  31774. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31775. this.matricesIndicesExtra = data;
  31776. break;
  31777. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31778. this.matricesWeightsExtra = data;
  31779. break;
  31780. }
  31781. };
  31782. /**
  31783. * Associates the vertexData to the passed Mesh.
  31784. * Sets it as updatable or not (default `false`).
  31785. * Returns the VertexData.
  31786. */
  31787. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31788. this._applyTo(mesh, updatable);
  31789. return this;
  31790. };
  31791. /**
  31792. * Associates the vertexData to the passed Geometry.
  31793. * Sets it as updatable or not (default `false`).
  31794. * Returns the VertexData.
  31795. */
  31796. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31797. this._applyTo(geometry, updatable);
  31798. return this;
  31799. };
  31800. /**
  31801. * Updates the associated mesh.
  31802. * Returns the VertexData.
  31803. */
  31804. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31805. this._update(mesh);
  31806. return this;
  31807. };
  31808. /**
  31809. * Updates the associated geometry.
  31810. * Returns the VertexData.
  31811. */
  31812. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31813. this._update(geometry);
  31814. return this;
  31815. };
  31816. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31817. if (updatable === void 0) { updatable = false; }
  31818. if (this.positions) {
  31819. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31820. }
  31821. if (this.normals) {
  31822. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31823. }
  31824. if (this.tangents) {
  31825. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31826. }
  31827. if (this.uvs) {
  31828. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31829. }
  31830. if (this.uvs2) {
  31831. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31832. }
  31833. if (this.uvs3) {
  31834. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31835. }
  31836. if (this.uvs4) {
  31837. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31838. }
  31839. if (this.uvs5) {
  31840. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31841. }
  31842. if (this.uvs6) {
  31843. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31844. }
  31845. if (this.colors) {
  31846. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31847. }
  31848. if (this.matricesIndices) {
  31849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31850. }
  31851. if (this.matricesWeights) {
  31852. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31853. }
  31854. if (this.matricesIndicesExtra) {
  31855. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31856. }
  31857. if (this.matricesWeightsExtra) {
  31858. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31859. }
  31860. if (this.indices) {
  31861. meshOrGeometry.setIndices(this.indices, null, updatable);
  31862. }
  31863. return this;
  31864. };
  31865. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31866. if (this.positions) {
  31867. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31868. }
  31869. if (this.normals) {
  31870. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31871. }
  31872. if (this.tangents) {
  31873. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31874. }
  31875. if (this.uvs) {
  31876. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31877. }
  31878. if (this.uvs2) {
  31879. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31880. }
  31881. if (this.uvs3) {
  31882. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31883. }
  31884. if (this.uvs4) {
  31885. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31886. }
  31887. if (this.uvs5) {
  31888. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31889. }
  31890. if (this.uvs6) {
  31891. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31892. }
  31893. if (this.colors) {
  31894. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31895. }
  31896. if (this.matricesIndices) {
  31897. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31898. }
  31899. if (this.matricesWeights) {
  31900. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31901. }
  31902. if (this.matricesIndicesExtra) {
  31903. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31904. }
  31905. if (this.matricesWeightsExtra) {
  31906. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31907. }
  31908. if (this.indices) {
  31909. meshOrGeometry.setIndices(this.indices, null);
  31910. }
  31911. return this;
  31912. };
  31913. /**
  31914. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31915. * Returns the VertexData.
  31916. */
  31917. VertexData.prototype.transform = function (matrix) {
  31918. var transformed = BABYLON.Vector3.Zero();
  31919. var index;
  31920. if (this.positions) {
  31921. var position = BABYLON.Vector3.Zero();
  31922. for (index = 0; index < this.positions.length; index += 3) {
  31923. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31924. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31925. this.positions[index] = transformed.x;
  31926. this.positions[index + 1] = transformed.y;
  31927. this.positions[index + 2] = transformed.z;
  31928. }
  31929. }
  31930. if (this.normals) {
  31931. var normal = BABYLON.Vector3.Zero();
  31932. for (index = 0; index < this.normals.length; index += 3) {
  31933. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31934. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31935. this.normals[index] = transformed.x;
  31936. this.normals[index + 1] = transformed.y;
  31937. this.normals[index + 2] = transformed.z;
  31938. }
  31939. }
  31940. if (this.tangents) {
  31941. var tangent = BABYLON.Vector4.Zero();
  31942. var tangentTransformed = BABYLON.Vector4.Zero();
  31943. for (index = 0; index < this.tangents.length; index += 4) {
  31944. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31945. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31946. this.tangents[index] = tangentTransformed.x;
  31947. this.tangents[index + 1] = tangentTransformed.y;
  31948. this.tangents[index + 2] = tangentTransformed.z;
  31949. this.tangents[index + 3] = tangentTransformed.w;
  31950. }
  31951. }
  31952. return this;
  31953. };
  31954. /**
  31955. * Merges the passed VertexData into the current one.
  31956. * Returns the modified VertexData.
  31957. */
  31958. VertexData.prototype.merge = function (other) {
  31959. this._validate();
  31960. other._validate();
  31961. if (!this.normals !== !other.normals ||
  31962. !this.tangents !== !other.tangents ||
  31963. !this.uvs !== !other.uvs ||
  31964. !this.uvs2 !== !other.uvs2 ||
  31965. !this.uvs3 !== !other.uvs3 ||
  31966. !this.uvs4 !== !other.uvs4 ||
  31967. !this.uvs5 !== !other.uvs5 ||
  31968. !this.uvs6 !== !other.uvs6 ||
  31969. !this.colors !== !other.colors ||
  31970. !this.matricesIndices !== !other.matricesIndices ||
  31971. !this.matricesWeights !== !other.matricesWeights ||
  31972. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  31973. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  31974. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  31975. }
  31976. if (other.indices) {
  31977. if (!this.indices) {
  31978. this.indices = [];
  31979. }
  31980. var offset = this.positions ? this.positions.length / 3 : 0;
  31981. for (var index = 0; index < other.indices.length; index++) {
  31982. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31983. this.indices.push(other.indices[index] + offset);
  31984. }
  31985. }
  31986. this.positions = this._mergeElement(this.positions, other.positions);
  31987. this.normals = this._mergeElement(this.normals, other.normals);
  31988. this.tangents = this._mergeElement(this.tangents, other.tangents);
  31989. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31990. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31991. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31992. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31993. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31994. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31995. this.colors = this._mergeElement(this.colors, other.colors);
  31996. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31997. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31998. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31999. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32000. return this;
  32001. };
  32002. VertexData.prototype._mergeElement = function (source, other) {
  32003. if (!source) {
  32004. return other;
  32005. }
  32006. if (!other) {
  32007. return source;
  32008. }
  32009. var len = other.length + source.length;
  32010. var isSrcTypedArray = source instanceof Float32Array;
  32011. var isOthTypedArray = other instanceof Float32Array;
  32012. // use non-loop method when the source is Float32Array
  32013. if (isSrcTypedArray) {
  32014. var ret32 = new Float32Array(len);
  32015. ret32.set(source);
  32016. ret32.set(other, source.length);
  32017. return ret32;
  32018. // source is number[], when other is also use concat
  32019. }
  32020. else if (!isOthTypedArray) {
  32021. return source.concat(other);
  32022. // source is a number[], but other is a Float32Array, loop required
  32023. }
  32024. else {
  32025. var ret = source.slice(0); // copy source to a separate array
  32026. for (var i = 0, len = other.length; i < len; i++) {
  32027. ret.push(other[i]);
  32028. }
  32029. return ret;
  32030. }
  32031. };
  32032. VertexData.prototype._validate = function () {
  32033. if (!this.positions) {
  32034. throw new Error("Positions are required");
  32035. }
  32036. var getElementCount = function (kind, values) {
  32037. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32038. if ((values.length % stride) !== 0) {
  32039. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32040. }
  32041. return values.length / stride;
  32042. };
  32043. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32044. var validateElementCount = function (kind, values) {
  32045. var elementCount = getElementCount(kind, values);
  32046. if (elementCount !== positionsElementCount) {
  32047. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32048. }
  32049. };
  32050. if (this.normals)
  32051. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32052. if (this.tangents)
  32053. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32054. if (this.uvs)
  32055. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32056. if (this.uvs2)
  32057. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32058. if (this.uvs3)
  32059. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32060. if (this.uvs4)
  32061. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32062. if (this.uvs5)
  32063. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32064. if (this.uvs6)
  32065. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32066. if (this.colors)
  32067. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32068. if (this.matricesIndices)
  32069. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32070. if (this.matricesWeights)
  32071. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32072. if (this.matricesIndicesExtra)
  32073. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32074. if (this.matricesWeightsExtra)
  32075. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32076. };
  32077. /**
  32078. * Serializes the VertexData.
  32079. * Returns a serialized object.
  32080. */
  32081. VertexData.prototype.serialize = function () {
  32082. var serializationObject = this.serialize();
  32083. if (this.positions) {
  32084. serializationObject.positions = this.positions;
  32085. }
  32086. if (this.normals) {
  32087. serializationObject.normals = this.normals;
  32088. }
  32089. if (this.tangents) {
  32090. serializationObject.tangents = this.tangents;
  32091. }
  32092. if (this.uvs) {
  32093. serializationObject.uvs = this.uvs;
  32094. }
  32095. if (this.uvs2) {
  32096. serializationObject.uvs2 = this.uvs2;
  32097. }
  32098. if (this.uvs3) {
  32099. serializationObject.uvs3 = this.uvs3;
  32100. }
  32101. if (this.uvs4) {
  32102. serializationObject.uvs4 = this.uvs4;
  32103. }
  32104. if (this.uvs5) {
  32105. serializationObject.uvs5 = this.uvs5;
  32106. }
  32107. if (this.uvs6) {
  32108. serializationObject.uvs6 = this.uvs6;
  32109. }
  32110. if (this.colors) {
  32111. serializationObject.colors = this.colors;
  32112. }
  32113. if (this.matricesIndices) {
  32114. serializationObject.matricesIndices = this.matricesIndices;
  32115. serializationObject.matricesIndices._isExpanded = true;
  32116. }
  32117. if (this.matricesWeights) {
  32118. serializationObject.matricesWeights = this.matricesWeights;
  32119. }
  32120. if (this.matricesIndicesExtra) {
  32121. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32122. serializationObject.matricesIndicesExtra._isExpanded = true;
  32123. }
  32124. if (this.matricesWeightsExtra) {
  32125. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32126. }
  32127. serializationObject.indices = this.indices;
  32128. return serializationObject;
  32129. };
  32130. // Statics
  32131. /**
  32132. * Returns the object VertexData associated to the passed mesh.
  32133. */
  32134. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32135. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32136. };
  32137. /**
  32138. * Returns the object VertexData associated to the passed geometry.
  32139. */
  32140. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32141. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32142. };
  32143. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32144. var result = new VertexData();
  32145. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32146. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32147. }
  32148. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32149. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32150. }
  32151. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32152. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32153. }
  32154. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32155. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32156. }
  32157. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32158. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32159. }
  32160. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32161. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32162. }
  32163. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32164. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32165. }
  32166. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32167. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32168. }
  32169. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32170. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32171. }
  32172. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32173. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32174. }
  32175. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32176. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32177. }
  32178. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32179. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32180. }
  32181. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32182. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32183. }
  32184. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32185. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32186. }
  32187. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32188. return result;
  32189. };
  32190. /**
  32191. * Creates the vertexData of the Ribbon.
  32192. */
  32193. VertexData.CreateRibbon = function (options) {
  32194. var pathArray = options.pathArray;
  32195. var closeArray = options.closeArray || false;
  32196. var closePath = options.closePath || false;
  32197. var invertUV = options.invertUV || false;
  32198. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32199. var offset = options.offset || defaultOffset;
  32200. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32201. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32202. var customUV = options.uvs;
  32203. var customColors = options.colors;
  32204. var positions = [];
  32205. var indices = [];
  32206. var normals = [];
  32207. var uvs = [];
  32208. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32209. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32210. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32211. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32212. var minlg; // minimal length among all paths from pathArray
  32213. var lg = []; // array of path lengths : nb of vertex per path
  32214. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32215. var p; // path iterator
  32216. var i; // point iterator
  32217. var j; // point iterator
  32218. // if single path in pathArray
  32219. if (pathArray.length < 2) {
  32220. var ar1 = [];
  32221. var ar2 = [];
  32222. for (i = 0; i < pathArray[0].length - offset; i++) {
  32223. ar1.push(pathArray[0][i]);
  32224. ar2.push(pathArray[0][i + offset]);
  32225. }
  32226. pathArray = [ar1, ar2];
  32227. }
  32228. // positions and horizontal distances (u)
  32229. var idc = 0;
  32230. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32231. var path;
  32232. var l;
  32233. minlg = pathArray[0].length;
  32234. var vectlg;
  32235. var dist;
  32236. for (p = 0; p < pathArray.length; p++) {
  32237. uTotalDistance[p] = 0;
  32238. us[p] = [0];
  32239. path = pathArray[p];
  32240. l = path.length;
  32241. minlg = (minlg < l) ? minlg : l;
  32242. j = 0;
  32243. while (j < l) {
  32244. positions.push(path[j].x, path[j].y, path[j].z);
  32245. if (j > 0) {
  32246. vectlg = path[j].subtract(path[j - 1]).length();
  32247. dist = vectlg + uTotalDistance[p];
  32248. us[p].push(dist);
  32249. uTotalDistance[p] = dist;
  32250. }
  32251. j++;
  32252. }
  32253. if (closePath) {
  32254. j--;
  32255. positions.push(path[0].x, path[0].y, path[0].z);
  32256. vectlg = path[j].subtract(path[0]).length();
  32257. dist = vectlg + uTotalDistance[p];
  32258. us[p].push(dist);
  32259. uTotalDistance[p] = dist;
  32260. }
  32261. lg[p] = l + closePathCorr;
  32262. idx[p] = idc;
  32263. idc += (l + closePathCorr);
  32264. }
  32265. // vertical distances (v)
  32266. var path1;
  32267. var path2;
  32268. var vertex1 = null;
  32269. var vertex2 = null;
  32270. for (i = 0; i < minlg + closePathCorr; i++) {
  32271. vTotalDistance[i] = 0;
  32272. vs[i] = [0];
  32273. for (p = 0; p < pathArray.length - 1; p++) {
  32274. path1 = pathArray[p];
  32275. path2 = pathArray[p + 1];
  32276. if (i === minlg) {
  32277. vertex1 = path1[0];
  32278. vertex2 = path2[0];
  32279. }
  32280. else {
  32281. vertex1 = path1[i];
  32282. vertex2 = path2[i];
  32283. }
  32284. vectlg = vertex2.subtract(vertex1).length();
  32285. dist = vectlg + vTotalDistance[i];
  32286. vs[i].push(dist);
  32287. vTotalDistance[i] = dist;
  32288. }
  32289. if (closeArray && vertex2 && vertex1) {
  32290. path1 = pathArray[p];
  32291. path2 = pathArray[0];
  32292. if (i === minlg) {
  32293. vertex2 = path2[0];
  32294. }
  32295. vectlg = vertex2.subtract(vertex1).length();
  32296. dist = vectlg + vTotalDistance[i];
  32297. vTotalDistance[i] = dist;
  32298. }
  32299. }
  32300. // uvs
  32301. var u;
  32302. var v;
  32303. if (customUV) {
  32304. for (p = 0; p < customUV.length; p++) {
  32305. uvs.push(customUV[p].x, customUV[p].y);
  32306. }
  32307. }
  32308. else {
  32309. for (p = 0; p < pathArray.length; p++) {
  32310. for (i = 0; i < minlg + closePathCorr; i++) {
  32311. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32312. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32313. if (invertUV) {
  32314. uvs.push(v, u);
  32315. }
  32316. else {
  32317. uvs.push(u, v);
  32318. }
  32319. }
  32320. }
  32321. }
  32322. // indices
  32323. p = 0; // path index
  32324. var pi = 0; // positions array index
  32325. var l1 = lg[p] - 1; // path1 length
  32326. var l2 = lg[p + 1] - 1; // path2 length
  32327. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32328. var shft = idx[1] - idx[0]; // shift
  32329. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32330. while (pi <= min && p < path1nb) {
  32331. // 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
  32332. indices.push(pi, pi + shft, pi + 1);
  32333. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32334. pi += 1;
  32335. if (pi === min) {
  32336. p++;
  32337. if (p === lg.length - 1) {
  32338. shft = idx[0] - idx[p];
  32339. l1 = lg[p] - 1;
  32340. l2 = lg[0] - 1;
  32341. }
  32342. else {
  32343. shft = idx[p + 1] - idx[p];
  32344. l1 = lg[p] - 1;
  32345. l2 = lg[p + 1] - 1;
  32346. }
  32347. pi = idx[p];
  32348. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32349. }
  32350. }
  32351. // normals
  32352. VertexData.ComputeNormals(positions, indices, normals);
  32353. if (closePath) {
  32354. var indexFirst = 0;
  32355. var indexLast = 0;
  32356. for (p = 0; p < pathArray.length; p++) {
  32357. indexFirst = idx[p] * 3;
  32358. if (p + 1 < pathArray.length) {
  32359. indexLast = (idx[p + 1] - 1) * 3;
  32360. }
  32361. else {
  32362. indexLast = normals.length - 3;
  32363. }
  32364. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32365. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32366. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32367. normals[indexLast] = normals[indexFirst];
  32368. normals[indexLast + 1] = normals[indexFirst + 1];
  32369. normals[indexLast + 2] = normals[indexFirst + 2];
  32370. }
  32371. }
  32372. // sides
  32373. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32374. // Colors
  32375. var colors = null;
  32376. if (customColors) {
  32377. colors = new Float32Array(customColors.length * 4);
  32378. for (var c = 0; c < customColors.length; c++) {
  32379. colors[c * 4] = customColors[c].r;
  32380. colors[c * 4 + 1] = customColors[c].g;
  32381. colors[c * 4 + 2] = customColors[c].b;
  32382. colors[c * 4 + 3] = customColors[c].a;
  32383. }
  32384. }
  32385. // Result
  32386. var vertexData = new VertexData();
  32387. var positions32 = new Float32Array(positions);
  32388. var normals32 = new Float32Array(normals);
  32389. var uvs32 = new Float32Array(uvs);
  32390. vertexData.indices = indices;
  32391. vertexData.positions = positions32;
  32392. vertexData.normals = normals32;
  32393. vertexData.uvs = uvs32;
  32394. if (colors) {
  32395. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32396. }
  32397. if (closePath) {
  32398. vertexData._idx = idx;
  32399. }
  32400. return vertexData;
  32401. };
  32402. /**
  32403. * Creates the VertexData of the Box.
  32404. */
  32405. VertexData.CreateBox = function (options) {
  32406. var normalsSource = [
  32407. new BABYLON.Vector3(0, 0, 1),
  32408. new BABYLON.Vector3(0, 0, -1),
  32409. new BABYLON.Vector3(1, 0, 0),
  32410. new BABYLON.Vector3(-1, 0, 0),
  32411. new BABYLON.Vector3(0, 1, 0),
  32412. new BABYLON.Vector3(0, -1, 0)
  32413. ];
  32414. var indices = [];
  32415. var positions = [];
  32416. var normals = [];
  32417. var uvs = [];
  32418. var width = options.width || options.size || 1;
  32419. var height = options.height || options.size || 1;
  32420. var depth = options.depth || options.size || 1;
  32421. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32422. var faceUV = options.faceUV || new Array(6);
  32423. var faceColors = options.faceColors;
  32424. var colors = [];
  32425. // default face colors and UV if undefined
  32426. for (var f = 0; f < 6; f++) {
  32427. if (faceUV[f] === undefined) {
  32428. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32429. }
  32430. if (faceColors && faceColors[f] === undefined) {
  32431. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32432. }
  32433. }
  32434. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32435. // Create each face in turn.
  32436. for (var index = 0; index < normalsSource.length; index++) {
  32437. var normal = normalsSource[index];
  32438. // Get two vectors perpendicular to the face normal and to each other.
  32439. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32440. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32441. // Six indices (two triangles) per face.
  32442. var verticesLength = positions.length / 3;
  32443. indices.push(verticesLength);
  32444. indices.push(verticesLength + 1);
  32445. indices.push(verticesLength + 2);
  32446. indices.push(verticesLength);
  32447. indices.push(verticesLength + 2);
  32448. indices.push(verticesLength + 3);
  32449. // Four vertices per face.
  32450. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32451. positions.push(vertex.x, vertex.y, vertex.z);
  32452. normals.push(normal.x, normal.y, normal.z);
  32453. uvs.push(faceUV[index].z, faceUV[index].w);
  32454. if (faceColors) {
  32455. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32456. }
  32457. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32458. positions.push(vertex.x, vertex.y, vertex.z);
  32459. normals.push(normal.x, normal.y, normal.z);
  32460. uvs.push(faceUV[index].x, faceUV[index].w);
  32461. if (faceColors) {
  32462. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32463. }
  32464. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32465. positions.push(vertex.x, vertex.y, vertex.z);
  32466. normals.push(normal.x, normal.y, normal.z);
  32467. uvs.push(faceUV[index].x, faceUV[index].y);
  32468. if (faceColors) {
  32469. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32470. }
  32471. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32472. positions.push(vertex.x, vertex.y, vertex.z);
  32473. normals.push(normal.x, normal.y, normal.z);
  32474. uvs.push(faceUV[index].z, faceUV[index].y);
  32475. if (faceColors) {
  32476. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32477. }
  32478. }
  32479. // sides
  32480. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32481. // Result
  32482. var vertexData = new VertexData();
  32483. vertexData.indices = indices;
  32484. vertexData.positions = positions;
  32485. vertexData.normals = normals;
  32486. vertexData.uvs = uvs;
  32487. if (faceColors) {
  32488. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32489. vertexData.colors = totalColors;
  32490. }
  32491. return vertexData;
  32492. };
  32493. /**
  32494. * Creates the VertexData of the Sphere.
  32495. */
  32496. VertexData.CreateSphere = function (options) {
  32497. var segments = options.segments || 32;
  32498. var diameterX = options.diameterX || options.diameter || 1;
  32499. var diameterY = options.diameterY || options.diameter || 1;
  32500. var diameterZ = options.diameterZ || options.diameter || 1;
  32501. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32502. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32503. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32504. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32505. var totalZRotationSteps = 2 + segments;
  32506. var totalYRotationSteps = 2 * totalZRotationSteps;
  32507. var indices = [];
  32508. var positions = [];
  32509. var normals = [];
  32510. var uvs = [];
  32511. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32512. var normalizedZ = zRotationStep / totalZRotationSteps;
  32513. var angleZ = normalizedZ * Math.PI * slice;
  32514. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32515. var normalizedY = yRotationStep / totalYRotationSteps;
  32516. var angleY = normalizedY * Math.PI * 2 * arc;
  32517. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32518. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32519. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32520. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32521. var vertex = complete.multiply(radius);
  32522. var normal = complete.divide(radius).normalize();
  32523. positions.push(vertex.x, vertex.y, vertex.z);
  32524. normals.push(normal.x, normal.y, normal.z);
  32525. uvs.push(normalizedY, normalizedZ);
  32526. }
  32527. if (zRotationStep > 0) {
  32528. var verticesCount = positions.length / 3;
  32529. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32530. indices.push((firstIndex));
  32531. indices.push((firstIndex + 1));
  32532. indices.push(firstIndex + totalYRotationSteps + 1);
  32533. indices.push((firstIndex + totalYRotationSteps + 1));
  32534. indices.push((firstIndex + 1));
  32535. indices.push((firstIndex + totalYRotationSteps + 2));
  32536. }
  32537. }
  32538. }
  32539. // Sides
  32540. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32541. // Result
  32542. var vertexData = new VertexData();
  32543. vertexData.indices = indices;
  32544. vertexData.positions = positions;
  32545. vertexData.normals = normals;
  32546. vertexData.uvs = uvs;
  32547. return vertexData;
  32548. };
  32549. /**
  32550. * Creates the VertexData of the Cylinder or Cone.
  32551. */
  32552. VertexData.CreateCylinder = function (options) {
  32553. var height = options.height || 2;
  32554. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32555. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32556. var tessellation = options.tessellation || 24;
  32557. var subdivisions = options.subdivisions || 1;
  32558. var hasRings = options.hasRings ? true : false;
  32559. var enclose = options.enclose ? true : false;
  32560. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32561. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32562. var faceUV = options.faceUV || new Array(3);
  32563. var faceColors = options.faceColors;
  32564. // default face colors and UV if undefined
  32565. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32566. var ringNb = (hasRings) ? subdivisions : 1;
  32567. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32568. var f;
  32569. for (f = 0; f < surfaceNb; f++) {
  32570. if (faceColors && faceColors[f] === undefined) {
  32571. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32572. }
  32573. }
  32574. for (f = 0; f < surfaceNb; f++) {
  32575. if (faceUV && faceUV[f] === undefined) {
  32576. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32577. }
  32578. }
  32579. var indices = new Array();
  32580. var positions = new Array();
  32581. var normals = new Array();
  32582. var uvs = new Array();
  32583. var colors = new Array();
  32584. var angle_step = Math.PI * 2 * arc / tessellation;
  32585. var angle;
  32586. var h;
  32587. var radius;
  32588. var tan = (diameterBottom - diameterTop) / 2 / height;
  32589. var ringVertex = BABYLON.Vector3.Zero();
  32590. var ringNormal = BABYLON.Vector3.Zero();
  32591. var ringFirstVertex = BABYLON.Vector3.Zero();
  32592. var ringFirstNormal = BABYLON.Vector3.Zero();
  32593. var quadNormal = BABYLON.Vector3.Zero();
  32594. var Y = BABYLON.Axis.Y;
  32595. // positions, normals, uvs
  32596. var i;
  32597. var j;
  32598. var r;
  32599. var ringIdx = 1;
  32600. var s = 1; // surface index
  32601. var cs = 0;
  32602. var v = 0;
  32603. for (i = 0; i <= subdivisions; i++) {
  32604. h = i / subdivisions;
  32605. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32606. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32607. for (r = 0; r < ringIdx; r++) {
  32608. if (hasRings) {
  32609. s += r;
  32610. }
  32611. if (enclose) {
  32612. s += 2 * r;
  32613. }
  32614. for (j = 0; j <= tessellation; j++) {
  32615. angle = j * angle_step;
  32616. // position
  32617. ringVertex.x = Math.cos(-angle) * radius;
  32618. ringVertex.y = -height / 2 + h * height;
  32619. ringVertex.z = Math.sin(-angle) * radius;
  32620. // normal
  32621. if (diameterTop === 0 && i === subdivisions) {
  32622. // if no top cap, reuse former normals
  32623. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32624. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32625. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32626. }
  32627. else {
  32628. ringNormal.x = ringVertex.x;
  32629. ringNormal.z = ringVertex.z;
  32630. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32631. ringNormal.normalize();
  32632. }
  32633. // keep first ring vertex values for enclose
  32634. if (j === 0) {
  32635. ringFirstVertex.copyFrom(ringVertex);
  32636. ringFirstNormal.copyFrom(ringNormal);
  32637. }
  32638. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32639. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32640. if (hasRings) {
  32641. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32642. }
  32643. else {
  32644. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32645. }
  32646. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32647. if (faceColors) {
  32648. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32649. }
  32650. }
  32651. // if enclose, add four vertices and their dedicated normals
  32652. if (arc !== 1 && enclose) {
  32653. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32654. positions.push(0, ringVertex.y, 0);
  32655. positions.push(0, ringVertex.y, 0);
  32656. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32657. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32658. quadNormal.normalize();
  32659. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32660. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32661. quadNormal.normalize();
  32662. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32663. if (hasRings) {
  32664. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32665. }
  32666. else {
  32667. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32668. }
  32669. uvs.push(faceUV[s + 1].x, v);
  32670. uvs.push(faceUV[s + 1].z, v);
  32671. if (hasRings) {
  32672. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32673. }
  32674. else {
  32675. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32676. }
  32677. uvs.push(faceUV[s + 2].x, v);
  32678. uvs.push(faceUV[s + 2].z, v);
  32679. if (faceColors) {
  32680. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32681. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32682. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32683. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32684. }
  32685. }
  32686. if (cs !== s) {
  32687. cs = s;
  32688. }
  32689. }
  32690. }
  32691. // indices
  32692. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32693. var s;
  32694. i = 0;
  32695. for (s = 0; s < subdivisions; s++) {
  32696. var i0 = 0;
  32697. var i1 = 0;
  32698. var i2 = 0;
  32699. var i3 = 0;
  32700. for (j = 0; j < tessellation; j++) {
  32701. i0 = i * (e + 1) + j;
  32702. i1 = (i + 1) * (e + 1) + j;
  32703. i2 = i * (e + 1) + (j + 1);
  32704. i3 = (i + 1) * (e + 1) + (j + 1);
  32705. indices.push(i0, i1, i2);
  32706. indices.push(i3, i2, i1);
  32707. }
  32708. if (arc !== 1 && enclose) {
  32709. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32710. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32711. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32712. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32713. }
  32714. i = (hasRings) ? (i + 2) : (i + 1);
  32715. }
  32716. // Caps
  32717. var createCylinderCap = function (isTop) {
  32718. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32719. if (radius === 0) {
  32720. return;
  32721. }
  32722. // Cap positions, normals & uvs
  32723. var angle;
  32724. var circleVector;
  32725. var i;
  32726. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32727. var c = null;
  32728. if (faceColors) {
  32729. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32730. }
  32731. // cap center
  32732. var vbase = positions.length / 3;
  32733. var offset = isTop ? height / 2 : -height / 2;
  32734. var center = new BABYLON.Vector3(0, offset, 0);
  32735. positions.push(center.x, center.y, center.z);
  32736. normals.push(0, isTop ? 1 : -1, 0);
  32737. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32738. if (c) {
  32739. colors.push(c.r, c.g, c.b, c.a);
  32740. }
  32741. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32742. for (i = 0; i <= tessellation; i++) {
  32743. angle = Math.PI * 2 * i * arc / tessellation;
  32744. var cos = Math.cos(-angle);
  32745. var sin = Math.sin(-angle);
  32746. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32747. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32748. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32749. normals.push(0, isTop ? 1 : -1, 0);
  32750. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32751. if (c) {
  32752. colors.push(c.r, c.g, c.b, c.a);
  32753. }
  32754. }
  32755. // Cap indices
  32756. for (i = 0; i < tessellation; i++) {
  32757. if (!isTop) {
  32758. indices.push(vbase);
  32759. indices.push(vbase + (i + 1));
  32760. indices.push(vbase + (i + 2));
  32761. }
  32762. else {
  32763. indices.push(vbase);
  32764. indices.push(vbase + (i + 2));
  32765. indices.push(vbase + (i + 1));
  32766. }
  32767. }
  32768. };
  32769. // add caps to geometry
  32770. createCylinderCap(false);
  32771. createCylinderCap(true);
  32772. // Sides
  32773. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32774. var vertexData = new VertexData();
  32775. vertexData.indices = indices;
  32776. vertexData.positions = positions;
  32777. vertexData.normals = normals;
  32778. vertexData.uvs = uvs;
  32779. if (faceColors) {
  32780. vertexData.colors = colors;
  32781. }
  32782. return vertexData;
  32783. };
  32784. /**
  32785. * Creates the VertexData of the Torus.
  32786. */
  32787. VertexData.CreateTorus = function (options) {
  32788. var indices = [];
  32789. var positions = [];
  32790. var normals = [];
  32791. var uvs = [];
  32792. var diameter = options.diameter || 1;
  32793. var thickness = options.thickness || 0.5;
  32794. var tessellation = options.tessellation || 16;
  32795. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32796. var stride = tessellation + 1;
  32797. for (var i = 0; i <= tessellation; i++) {
  32798. var u = i / tessellation;
  32799. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32800. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32801. for (var j = 0; j <= tessellation; j++) {
  32802. var v = 1 - j / tessellation;
  32803. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32804. var dx = Math.cos(innerAngle);
  32805. var dy = Math.sin(innerAngle);
  32806. // Create a vertex.
  32807. var normal = new BABYLON.Vector3(dx, dy, 0);
  32808. var position = normal.scale(thickness / 2);
  32809. var textureCoordinate = new BABYLON.Vector2(u, v);
  32810. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32811. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32812. positions.push(position.x, position.y, position.z);
  32813. normals.push(normal.x, normal.y, normal.z);
  32814. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32815. // And create indices for two triangles.
  32816. var nextI = (i + 1) % stride;
  32817. var nextJ = (j + 1) % stride;
  32818. indices.push(i * stride + j);
  32819. indices.push(i * stride + nextJ);
  32820. indices.push(nextI * stride + j);
  32821. indices.push(i * stride + nextJ);
  32822. indices.push(nextI * stride + nextJ);
  32823. indices.push(nextI * stride + j);
  32824. }
  32825. }
  32826. // Sides
  32827. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32828. // Result
  32829. var vertexData = new VertexData();
  32830. vertexData.indices = indices;
  32831. vertexData.positions = positions;
  32832. vertexData.normals = normals;
  32833. vertexData.uvs = uvs;
  32834. return vertexData;
  32835. };
  32836. /**
  32837. * Creates the VertexData of the LineSystem.
  32838. */
  32839. VertexData.CreateLineSystem = function (options) {
  32840. var indices = [];
  32841. var positions = [];
  32842. var lines = options.lines;
  32843. var colors = options.colors;
  32844. var vertexColors = [];
  32845. var idx = 0;
  32846. for (var l = 0; l < lines.length; l++) {
  32847. var points = lines[l];
  32848. for (var index = 0; index < points.length; index++) {
  32849. positions.push(points[index].x, points[index].y, points[index].z);
  32850. if (colors) {
  32851. var color = colors[l];
  32852. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32853. }
  32854. if (index > 0) {
  32855. indices.push(idx - 1);
  32856. indices.push(idx);
  32857. }
  32858. idx++;
  32859. }
  32860. }
  32861. var vertexData = new VertexData();
  32862. vertexData.indices = indices;
  32863. vertexData.positions = positions;
  32864. if (colors) {
  32865. vertexData.colors = vertexColors;
  32866. }
  32867. return vertexData;
  32868. };
  32869. /**
  32870. * Create the VertexData of the DashedLines.
  32871. */
  32872. VertexData.CreateDashedLines = function (options) {
  32873. var dashSize = options.dashSize || 3;
  32874. var gapSize = options.gapSize || 1;
  32875. var dashNb = options.dashNb || 200;
  32876. var points = options.points;
  32877. var positions = new Array();
  32878. var indices = new Array();
  32879. var curvect = BABYLON.Vector3.Zero();
  32880. var lg = 0;
  32881. var nb = 0;
  32882. var shft = 0;
  32883. var dashshft = 0;
  32884. var curshft = 0;
  32885. var idx = 0;
  32886. var i = 0;
  32887. for (i = 0; i < points.length - 1; i++) {
  32888. points[i + 1].subtractToRef(points[i], curvect);
  32889. lg += curvect.length();
  32890. }
  32891. shft = lg / dashNb;
  32892. dashshft = dashSize * shft / (dashSize + gapSize);
  32893. for (i = 0; i < points.length - 1; i++) {
  32894. points[i + 1].subtractToRef(points[i], curvect);
  32895. nb = Math.floor(curvect.length() / shft);
  32896. curvect.normalize();
  32897. for (var j = 0; j < nb; j++) {
  32898. curshft = shft * j;
  32899. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32900. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32901. indices.push(idx, idx + 1);
  32902. idx += 2;
  32903. }
  32904. }
  32905. // Result
  32906. var vertexData = new VertexData();
  32907. vertexData.positions = positions;
  32908. vertexData.indices = indices;
  32909. return vertexData;
  32910. };
  32911. /**
  32912. * Creates the VertexData of the Ground.
  32913. */
  32914. VertexData.CreateGround = function (options) {
  32915. var indices = [];
  32916. var positions = [];
  32917. var normals = [];
  32918. var uvs = [];
  32919. var row, col;
  32920. var width = options.width || 1;
  32921. var height = options.height || 1;
  32922. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32923. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32924. for (row = 0; row <= subdivisionsY; row++) {
  32925. for (col = 0; col <= subdivisionsX; col++) {
  32926. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32927. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32928. positions.push(position.x, position.y, position.z);
  32929. normals.push(normal.x, normal.y, normal.z);
  32930. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32931. }
  32932. }
  32933. for (row = 0; row < subdivisionsY; row++) {
  32934. for (col = 0; col < subdivisionsX; col++) {
  32935. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32936. indices.push(col + 1 + row * (subdivisionsX + 1));
  32937. indices.push(col + row * (subdivisionsX + 1));
  32938. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32939. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32940. indices.push(col + row * (subdivisionsX + 1));
  32941. }
  32942. }
  32943. // Result
  32944. var vertexData = new VertexData();
  32945. vertexData.indices = indices;
  32946. vertexData.positions = positions;
  32947. vertexData.normals = normals;
  32948. vertexData.uvs = uvs;
  32949. return vertexData;
  32950. };
  32951. /**
  32952. * Creates the VertexData of the TiledGround.
  32953. */
  32954. VertexData.CreateTiledGround = function (options) {
  32955. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32956. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32957. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32958. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32959. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32960. var precision = options.precision || { w: 1, h: 1 };
  32961. var indices = new Array();
  32962. var positions = new Array();
  32963. var normals = new Array();
  32964. var uvs = new Array();
  32965. var row, col, tileRow, tileCol;
  32966. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32967. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32968. precision.w = (precision.w < 1) ? 1 : precision.w;
  32969. precision.h = (precision.h < 1) ? 1 : precision.h;
  32970. var tileSize = {
  32971. 'w': (xmax - xmin) / subdivisions.w,
  32972. 'h': (zmax - zmin) / subdivisions.h
  32973. };
  32974. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32975. // Indices
  32976. var base = positions.length / 3;
  32977. var rowLength = precision.w + 1;
  32978. for (row = 0; row < precision.h; row++) {
  32979. for (col = 0; col < precision.w; col++) {
  32980. var square = [
  32981. base + col + row * rowLength,
  32982. base + (col + 1) + row * rowLength,
  32983. base + (col + 1) + (row + 1) * rowLength,
  32984. base + col + (row + 1) * rowLength
  32985. ];
  32986. indices.push(square[1]);
  32987. indices.push(square[2]);
  32988. indices.push(square[3]);
  32989. indices.push(square[0]);
  32990. indices.push(square[1]);
  32991. indices.push(square[3]);
  32992. }
  32993. }
  32994. // Position, normals and uvs
  32995. var position = BABYLON.Vector3.Zero();
  32996. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32997. for (row = 0; row <= precision.h; row++) {
  32998. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32999. for (col = 0; col <= precision.w; col++) {
  33000. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33001. position.y = 0;
  33002. positions.push(position.x, position.y, position.z);
  33003. normals.push(normal.x, normal.y, normal.z);
  33004. uvs.push(col / precision.w, row / precision.h);
  33005. }
  33006. }
  33007. }
  33008. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33009. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33010. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33011. }
  33012. }
  33013. // Result
  33014. var vertexData = new VertexData();
  33015. vertexData.indices = indices;
  33016. vertexData.positions = positions;
  33017. vertexData.normals = normals;
  33018. vertexData.uvs = uvs;
  33019. return vertexData;
  33020. };
  33021. /**
  33022. * Creates the VertexData of the Ground designed from a heightmap.
  33023. */
  33024. VertexData.CreateGroundFromHeightMap = function (options) {
  33025. var indices = [];
  33026. var positions = [];
  33027. var normals = [];
  33028. var uvs = [];
  33029. var row, col;
  33030. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33031. // Vertices
  33032. for (row = 0; row <= options.subdivisions; row++) {
  33033. for (col = 0; col <= options.subdivisions; col++) {
  33034. 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));
  33035. // Compute height
  33036. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33037. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33038. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33039. var r = options.buffer[pos] / 255.0;
  33040. var g = options.buffer[pos + 1] / 255.0;
  33041. var b = options.buffer[pos + 2] / 255.0;
  33042. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33043. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33044. // Add vertex
  33045. positions.push(position.x, position.y, position.z);
  33046. normals.push(0, 0, 0);
  33047. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33048. }
  33049. }
  33050. // Indices
  33051. for (row = 0; row < options.subdivisions; row++) {
  33052. for (col = 0; col < options.subdivisions; col++) {
  33053. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33054. indices.push(col + 1 + row * (options.subdivisions + 1));
  33055. indices.push(col + row * (options.subdivisions + 1));
  33056. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33057. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33058. indices.push(col + row * (options.subdivisions + 1));
  33059. }
  33060. }
  33061. // Normals
  33062. VertexData.ComputeNormals(positions, indices, normals);
  33063. // Result
  33064. var vertexData = new VertexData();
  33065. vertexData.indices = indices;
  33066. vertexData.positions = positions;
  33067. vertexData.normals = normals;
  33068. vertexData.uvs = uvs;
  33069. return vertexData;
  33070. };
  33071. /**
  33072. * Creates the VertexData of the Plane.
  33073. */
  33074. VertexData.CreatePlane = function (options) {
  33075. var indices = [];
  33076. var positions = [];
  33077. var normals = [];
  33078. var uvs = [];
  33079. var width = options.width || options.size || 1;
  33080. var height = options.height || options.size || 1;
  33081. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33082. // Vertices
  33083. var halfWidth = width / 2.0;
  33084. var halfHeight = height / 2.0;
  33085. positions.push(-halfWidth, -halfHeight, 0);
  33086. normals.push(0, 0, -1.0);
  33087. uvs.push(0.0, 0.0);
  33088. positions.push(halfWidth, -halfHeight, 0);
  33089. normals.push(0, 0, -1.0);
  33090. uvs.push(1.0, 0.0);
  33091. positions.push(halfWidth, halfHeight, 0);
  33092. normals.push(0, 0, -1.0);
  33093. uvs.push(1.0, 1.0);
  33094. positions.push(-halfWidth, halfHeight, 0);
  33095. normals.push(0, 0, -1.0);
  33096. uvs.push(0.0, 1.0);
  33097. // Indices
  33098. indices.push(0);
  33099. indices.push(1);
  33100. indices.push(2);
  33101. indices.push(0);
  33102. indices.push(2);
  33103. indices.push(3);
  33104. // Sides
  33105. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33106. // Result
  33107. var vertexData = new VertexData();
  33108. vertexData.indices = indices;
  33109. vertexData.positions = positions;
  33110. vertexData.normals = normals;
  33111. vertexData.uvs = uvs;
  33112. return vertexData;
  33113. };
  33114. /**
  33115. * Creates the VertexData of the Disc or regular Polygon.
  33116. */
  33117. VertexData.CreateDisc = function (options) {
  33118. var positions = new Array();
  33119. var indices = new Array();
  33120. var normals = new Array();
  33121. var uvs = new Array();
  33122. var radius = options.radius || 0.5;
  33123. var tessellation = options.tessellation || 64;
  33124. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33125. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33126. // positions and uvs
  33127. positions.push(0, 0, 0); // disc center first
  33128. uvs.push(0.5, 0.5);
  33129. var theta = Math.PI * 2 * arc;
  33130. var step = theta / tessellation;
  33131. for (var a = 0; a < theta; a += step) {
  33132. var x = Math.cos(a);
  33133. var y = Math.sin(a);
  33134. var u = (x + 1) / 2;
  33135. var v = (1 - y) / 2;
  33136. positions.push(radius * x, radius * y, 0);
  33137. uvs.push(u, v);
  33138. }
  33139. if (arc === 1) {
  33140. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33141. uvs.push(uvs[2], uvs[3]);
  33142. }
  33143. //indices
  33144. var vertexNb = positions.length / 3;
  33145. for (var i = 1; i < vertexNb - 1; i++) {
  33146. indices.push(i + 1, 0, i);
  33147. }
  33148. // result
  33149. VertexData.ComputeNormals(positions, indices, normals);
  33150. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33151. var vertexData = new VertexData();
  33152. vertexData.indices = indices;
  33153. vertexData.positions = positions;
  33154. vertexData.normals = normals;
  33155. vertexData.uvs = uvs;
  33156. return vertexData;
  33157. };
  33158. /**
  33159. * Re-creates the VertexData of the Polygon for sideOrientation.
  33160. */
  33161. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33162. var faceUV = fUV || new Array(3);
  33163. var faceColors = fColors;
  33164. var colors = [];
  33165. // default face colors and UV if undefined
  33166. for (var f = 0; f < 3; f++) {
  33167. if (faceUV[f] === undefined) {
  33168. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33169. }
  33170. if (faceColors && faceColors[f] === undefined) {
  33171. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33172. }
  33173. }
  33174. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33175. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33176. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33177. var indices = polygon.getIndices();
  33178. // set face colours and textures
  33179. var idx = 0;
  33180. var face = 0;
  33181. for (var index = 0; index < normals.length; index += 3) {
  33182. //Edge Face no. 1
  33183. if (Math.abs(normals[index + 1]) < 0.001) {
  33184. face = 1;
  33185. }
  33186. //Top Face no. 0
  33187. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33188. face = 0;
  33189. }
  33190. //Bottom Face no. 2
  33191. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33192. face = 2;
  33193. }
  33194. idx = index / 3;
  33195. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33196. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33197. if (faceColors) {
  33198. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33199. }
  33200. }
  33201. // sides
  33202. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33203. // Result
  33204. var vertexData = new VertexData();
  33205. vertexData.indices = indices;
  33206. vertexData.positions = positions;
  33207. vertexData.normals = normals;
  33208. vertexData.uvs = uvs;
  33209. if (faceColors) {
  33210. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33211. vertexData.colors = totalColors;
  33212. }
  33213. return vertexData;
  33214. };
  33215. /**
  33216. * Creates the VertexData of the IcoSphere.
  33217. */
  33218. VertexData.CreateIcoSphere = function (options) {
  33219. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33220. var radius = options.radius || 1;
  33221. var flat = (options.flat === undefined) ? true : options.flat;
  33222. var subdivisions = options.subdivisions || 4;
  33223. var radiusX = options.radiusX || radius;
  33224. var radiusY = options.radiusY || radius;
  33225. var radiusZ = options.radiusZ || radius;
  33226. var t = (1 + Math.sqrt(5)) / 2;
  33227. // 12 vertex x,y,z
  33228. var ico_vertices = [
  33229. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33230. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33231. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33232. ];
  33233. // index of 3 vertex makes a face of icopshere
  33234. var ico_indices = [
  33235. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33236. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33237. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33238. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33239. ];
  33240. // vertex for uv have aliased position, not for UV
  33241. var vertices_unalias_id = [
  33242. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33243. // vertex alias
  33244. 0,
  33245. 2,
  33246. 3,
  33247. 3,
  33248. 3,
  33249. 4,
  33250. 7,
  33251. 8,
  33252. 9,
  33253. 9,
  33254. 10,
  33255. 11 // 23: B + 12
  33256. ];
  33257. // uv as integer step (not pixels !)
  33258. var ico_vertexuv = [
  33259. 5, 1, 3, 1, 6, 4, 0, 0,
  33260. 5, 3, 4, 2, 2, 2, 4, 0,
  33261. 2, 0, 1, 1, 6, 0, 6, 2,
  33262. // vertex alias (for same vertex on different faces)
  33263. 0, 4,
  33264. 3, 3,
  33265. 4, 4,
  33266. 3, 1,
  33267. 4, 2,
  33268. 4, 4,
  33269. 0, 2,
  33270. 1, 1,
  33271. 2, 2,
  33272. 3, 3,
  33273. 1, 3,
  33274. 2, 4 // 23: B + 12
  33275. ];
  33276. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33277. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33278. // First island of uv mapping
  33279. // v = 4h 3+ 2
  33280. // v = 3h 9+ 4
  33281. // v = 2h 9+ 5 B
  33282. // v = 1h 9 1 0
  33283. // v = 0h 3 8 7 A
  33284. // u = 0 1 2 3 4 5 6 *a
  33285. // Second island of uv mapping
  33286. // v = 4h 0+ B+ 4+
  33287. // v = 3h A+ 2+
  33288. // v = 2h 7+ 6 3+
  33289. // v = 1h 8+ 3+
  33290. // v = 0h
  33291. // u = 0 1 2 3 4 5 6 *a
  33292. // Face layout on texture UV mapping
  33293. // ============
  33294. // \ 4 /\ 16 / ======
  33295. // \ / \ / /\ 11 /
  33296. // \/ 7 \/ / \ /
  33297. // ======= / 10 \/
  33298. // /\ 17 /\ =======
  33299. // / \ / \ \ 15 /\
  33300. // / 8 \/ 12 \ \ / \
  33301. // ============ \/ 6 \
  33302. // \ 18 /\ ============
  33303. // \ / \ \ 5 /\ 0 /
  33304. // \/ 13 \ \ / \ /
  33305. // ======= \/ 1 \/
  33306. // =============
  33307. // /\ 19 /\ 2 /\
  33308. // / \ / \ / \
  33309. // / 14 \/ 9 \/ 3 \
  33310. // ===================
  33311. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33312. var ustep = 138 / 1024;
  33313. var vstep = 239 / 1024;
  33314. var uoffset = 60 / 1024;
  33315. var voffset = 26 / 1024;
  33316. // Second island should have margin, not to touch the first island
  33317. // avoid any borderline artefact in pixel rounding
  33318. var island_u_offset = -40 / 1024;
  33319. var island_v_offset = +20 / 1024;
  33320. // face is either island 0 or 1 :
  33321. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33322. var island = [
  33323. 0, 0, 0, 0, 1,
  33324. 0, 0, 1, 1, 0,
  33325. 0, 0, 1, 1, 0,
  33326. 0, 1, 1, 1, 0 // 15 - 19
  33327. ];
  33328. var indices = new Array();
  33329. var positions = new Array();
  33330. var normals = new Array();
  33331. var uvs = new Array();
  33332. var current_indice = 0;
  33333. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33334. var face_vertex_pos = new Array(3);
  33335. var face_vertex_uv = new Array(3);
  33336. var v012;
  33337. for (v012 = 0; v012 < 3; v012++) {
  33338. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33339. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33340. }
  33341. // create all with normals
  33342. for (var face = 0; face < 20; face++) {
  33343. // 3 vertex per face
  33344. for (v012 = 0; v012 < 3; v012++) {
  33345. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33346. var v_id = ico_indices[3 * face + v012];
  33347. // vertex have 3D position (x,y,z)
  33348. 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]);
  33349. // Normalize to get normal, then scale to radius
  33350. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33351. // uv Coordinates from vertex ID
  33352. 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);
  33353. }
  33354. // Subdivide the face (interpolate pos, norm, uv)
  33355. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33356. // - norm is linear interpolation of vertex corner normal
  33357. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33358. // - uv is linear interpolation
  33359. //
  33360. // Topology is as below for sub-divide by 2
  33361. // vertex shown as v0,v1,v2
  33362. // interp index is i1 to progress in range [v0,v1[
  33363. // interp index is i2 to progress in range [v0,v2[
  33364. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33365. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33366. //
  33367. //
  33368. // i2 v2
  33369. // ^ ^
  33370. // / / \
  33371. // / / \
  33372. // / / \
  33373. // / / (0,1) \
  33374. // / #---------\
  33375. // / / \ (0,0)'/ \
  33376. // / / \ / \
  33377. // / / \ / \
  33378. // / / (0,0) \ / (1,0) \
  33379. // / #---------#---------\
  33380. // v0 v1
  33381. //
  33382. // --------------------> i1
  33383. //
  33384. // interp of (i1,i2):
  33385. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33386. // along i1 : lerp(x0,x1, i1/(S-i2))
  33387. //
  33388. // centroid of triangle is needed to get help normal computation
  33389. // (c1,c2) are used for centroid location
  33390. var interp_vertex = function (i1, i2, c1, c2) {
  33391. // vertex is interpolated from
  33392. // - face_vertex_pos[0..2]
  33393. // - face_vertex_uv[0..2]
  33394. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33395. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33396. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33397. pos_interp.normalize();
  33398. var vertex_normal;
  33399. if (flat) {
  33400. // in flat mode, recalculate normal as face centroid normal
  33401. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33402. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33403. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33404. }
  33405. else {
  33406. // in smooth mode, recalculate normal from each single vertex position
  33407. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33408. }
  33409. // Vertex normal need correction due to X,Y,Z radius scaling
  33410. vertex_normal.x /= radiusX;
  33411. vertex_normal.y /= radiusY;
  33412. vertex_normal.z /= radiusZ;
  33413. vertex_normal.normalize();
  33414. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33415. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33416. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33417. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33418. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33419. uvs.push(uv_interp.x, uv_interp.y);
  33420. // push each vertex has member of a face
  33421. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33422. indices.push(current_indice);
  33423. current_indice++;
  33424. };
  33425. for (var i2 = 0; i2 < subdivisions; i2++) {
  33426. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33427. // face : (i1,i2) for /\ :
  33428. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33429. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33430. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33431. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33432. if (i1 + i2 + 1 < subdivisions) {
  33433. // face : (i1,i2)' for \/ :
  33434. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33435. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33436. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33437. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33438. }
  33439. }
  33440. }
  33441. }
  33442. // Sides
  33443. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33444. // Result
  33445. var vertexData = new VertexData();
  33446. vertexData.indices = indices;
  33447. vertexData.positions = positions;
  33448. vertexData.normals = normals;
  33449. vertexData.uvs = uvs;
  33450. return vertexData;
  33451. };
  33452. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33453. /**
  33454. * Creates the VertexData of the Polyhedron.
  33455. */
  33456. VertexData.CreatePolyhedron = function (options) {
  33457. // provided polyhedron types :
  33458. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33459. // 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)
  33460. var polyhedra = [];
  33461. 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]] };
  33462. 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]] };
  33463. polyhedra[2] = {
  33464. 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]],
  33465. 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]]
  33466. };
  33467. polyhedra[3] = {
  33468. 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]],
  33469. 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]]
  33470. };
  33471. polyhedra[4] = {
  33472. 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]],
  33473. 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]]
  33474. };
  33475. 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]] };
  33476. 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]] };
  33477. 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]] };
  33478. 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]] };
  33479. 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]] };
  33480. 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]] };
  33481. 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]] };
  33482. 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]] };
  33483. 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]] };
  33484. polyhedra[14] = {
  33485. 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]],
  33486. 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]]
  33487. };
  33488. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33489. var size = options.size;
  33490. var sizeX = options.sizeX || size || 1;
  33491. var sizeY = options.sizeY || size || 1;
  33492. var sizeZ = options.sizeZ || size || 1;
  33493. var data = options.custom || polyhedra[type];
  33494. var nbfaces = data.face.length;
  33495. var faceUV = options.faceUV || new Array(nbfaces);
  33496. var faceColors = options.faceColors;
  33497. var flat = (options.flat === undefined) ? true : options.flat;
  33498. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33499. var positions = new Array();
  33500. var indices = new Array();
  33501. var normals = new Array();
  33502. var uvs = new Array();
  33503. var colors = new Array();
  33504. var index = 0;
  33505. var faceIdx = 0; // face cursor in the array "indexes"
  33506. var indexes = new Array();
  33507. var i = 0;
  33508. var f = 0;
  33509. var u, v, ang, x, y, tmp;
  33510. // default face colors and UV if undefined
  33511. if (flat) {
  33512. for (f = 0; f < nbfaces; f++) {
  33513. if (faceColors && faceColors[f] === undefined) {
  33514. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33515. }
  33516. if (faceUV && faceUV[f] === undefined) {
  33517. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33518. }
  33519. }
  33520. }
  33521. if (!flat) {
  33522. for (i = 0; i < data.vertex.length; i++) {
  33523. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33524. uvs.push(0, 0);
  33525. }
  33526. for (f = 0; f < nbfaces; f++) {
  33527. for (i = 0; i < data.face[f].length - 2; i++) {
  33528. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33529. }
  33530. }
  33531. }
  33532. else {
  33533. for (f = 0; f < nbfaces; f++) {
  33534. var fl = data.face[f].length; // number of vertices of the current face
  33535. ang = 2 * Math.PI / fl;
  33536. x = 0.5 * Math.tan(ang / 2);
  33537. y = 0.5;
  33538. // positions, uvs, colors
  33539. for (i = 0; i < fl; i++) {
  33540. // positions
  33541. 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);
  33542. indexes.push(index);
  33543. index++;
  33544. // uvs
  33545. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33546. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33547. uvs.push(u, v);
  33548. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33549. y = x * Math.sin(ang) + y * Math.cos(ang);
  33550. x = tmp;
  33551. // colors
  33552. if (faceColors) {
  33553. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33554. }
  33555. }
  33556. // indices from indexes
  33557. for (i = 0; i < fl - 2; i++) {
  33558. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33559. }
  33560. faceIdx += fl;
  33561. }
  33562. }
  33563. VertexData.ComputeNormals(positions, indices, normals);
  33564. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33565. var vertexData = new VertexData();
  33566. vertexData.positions = positions;
  33567. vertexData.indices = indices;
  33568. vertexData.normals = normals;
  33569. vertexData.uvs = uvs;
  33570. if (faceColors && flat) {
  33571. vertexData.colors = colors;
  33572. }
  33573. return vertexData;
  33574. };
  33575. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33576. /**
  33577. * Creates the VertexData of the Torus Knot.
  33578. */
  33579. VertexData.CreateTorusKnot = function (options) {
  33580. var indices = new Array();
  33581. var positions = new Array();
  33582. var normals = new Array();
  33583. var uvs = new Array();
  33584. var radius = options.radius || 2;
  33585. var tube = options.tube || 0.5;
  33586. var radialSegments = options.radialSegments || 32;
  33587. var tubularSegments = options.tubularSegments || 32;
  33588. var p = options.p || 2;
  33589. var q = options.q || 3;
  33590. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33591. // Helper
  33592. var getPos = function (angle) {
  33593. var cu = Math.cos(angle);
  33594. var su = Math.sin(angle);
  33595. var quOverP = q / p * angle;
  33596. var cs = Math.cos(quOverP);
  33597. var tx = radius * (2 + cs) * 0.5 * cu;
  33598. var ty = radius * (2 + cs) * su * 0.5;
  33599. var tz = radius * Math.sin(quOverP) * 0.5;
  33600. return new BABYLON.Vector3(tx, ty, tz);
  33601. };
  33602. // Vertices
  33603. var i;
  33604. var j;
  33605. for (i = 0; i <= radialSegments; i++) {
  33606. var modI = i % radialSegments;
  33607. var u = modI / radialSegments * 2 * p * Math.PI;
  33608. var p1 = getPos(u);
  33609. var p2 = getPos(u + 0.01);
  33610. var tang = p2.subtract(p1);
  33611. var n = p2.add(p1);
  33612. var bitan = BABYLON.Vector3.Cross(tang, n);
  33613. n = BABYLON.Vector3.Cross(bitan, tang);
  33614. bitan.normalize();
  33615. n.normalize();
  33616. for (j = 0; j < tubularSegments; j++) {
  33617. var modJ = j % tubularSegments;
  33618. var v = modJ / tubularSegments * 2 * Math.PI;
  33619. var cx = -tube * Math.cos(v);
  33620. var cy = tube * Math.sin(v);
  33621. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33622. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33623. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33624. uvs.push(i / radialSegments);
  33625. uvs.push(j / tubularSegments);
  33626. }
  33627. }
  33628. for (i = 0; i < radialSegments; i++) {
  33629. for (j = 0; j < tubularSegments; j++) {
  33630. var jNext = (j + 1) % tubularSegments;
  33631. var a = i * tubularSegments + j;
  33632. var b = (i + 1) * tubularSegments + j;
  33633. var c = (i + 1) * tubularSegments + jNext;
  33634. var d = i * tubularSegments + jNext;
  33635. indices.push(d);
  33636. indices.push(b);
  33637. indices.push(a);
  33638. indices.push(d);
  33639. indices.push(c);
  33640. indices.push(b);
  33641. }
  33642. }
  33643. // Normals
  33644. VertexData.ComputeNormals(positions, indices, normals);
  33645. // Sides
  33646. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33647. // Result
  33648. var vertexData = new VertexData();
  33649. vertexData.indices = indices;
  33650. vertexData.positions = positions;
  33651. vertexData.normals = normals;
  33652. vertexData.uvs = uvs;
  33653. return vertexData;
  33654. };
  33655. // Tools
  33656. /**
  33657. * @param {any} - positions (number[] or Float32Array)
  33658. * @param {any} - indices (number[] or Uint16Array)
  33659. * @param {any} - normals (number[] or Float32Array)
  33660. * options (optional) :
  33661. * facetPositions : optional array of facet positions (vector3)
  33662. * facetNormals : optional array of facet normals (vector3)
  33663. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33664. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33665. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33666. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33667. * bInfo : optional bounding info, required for facetPartitioning computation
  33668. * useRightHandedSystem: optional boolean to for right handed system computation
  33669. * depthSort : optional boolean to enable the facet depth sort computation
  33670. * distanceTo : optional Vector3 to compute the facet depth from this location
  33671. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33672. */
  33673. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33674. // temporary scalar variables
  33675. var index = 0; // facet index
  33676. var p1p2x = 0.0; // p1p2 vector x coordinate
  33677. var p1p2y = 0.0; // p1p2 vector y coordinate
  33678. var p1p2z = 0.0; // p1p2 vector z coordinate
  33679. var p3p2x = 0.0; // p3p2 vector x coordinate
  33680. var p3p2y = 0.0; // p3p2 vector y coordinate
  33681. var p3p2z = 0.0; // p3p2 vector z coordinate
  33682. var faceNormalx = 0.0; // facet normal x coordinate
  33683. var faceNormaly = 0.0; // facet normal y coordinate
  33684. var faceNormalz = 0.0; // facet normal z coordinate
  33685. var length = 0.0; // facet normal length before normalization
  33686. var v1x = 0; // vector1 x index in the positions array
  33687. var v1y = 0; // vector1 y index in the positions array
  33688. var v1z = 0; // vector1 z index in the positions array
  33689. var v2x = 0; // vector2 x index in the positions array
  33690. var v2y = 0; // vector2 y index in the positions array
  33691. var v2z = 0; // vector2 z index in the positions array
  33692. var v3x = 0; // vector3 x index in the positions array
  33693. var v3y = 0; // vector3 y index in the positions array
  33694. var v3z = 0; // vector3 z index in the positions array
  33695. var computeFacetNormals = false;
  33696. var computeFacetPositions = false;
  33697. var computeFacetPartitioning = false;
  33698. var computeDepthSort = false;
  33699. var faceNormalSign = 1;
  33700. var ratio = 0;
  33701. var distanceTo = null;
  33702. if (options) {
  33703. computeFacetNormals = (options.facetNormals) ? true : false;
  33704. computeFacetPositions = (options.facetPositions) ? true : false;
  33705. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33706. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33707. ratio = options.ratio || 0;
  33708. computeDepthSort = (options.depthSort) ? true : false;
  33709. distanceTo = (options.distanceTo);
  33710. if (computeDepthSort) {
  33711. if (distanceTo === undefined) {
  33712. distanceTo = BABYLON.Vector3.Zero();
  33713. }
  33714. var depthSortedFacets = options.depthSortedFacets;
  33715. }
  33716. }
  33717. // facetPartitioning reinit if needed
  33718. var xSubRatio = 0;
  33719. var ySubRatio = 0;
  33720. var zSubRatio = 0;
  33721. var subSq = 0;
  33722. if (computeFacetPartitioning && options && options.bbSize) {
  33723. var ox = 0; // X partitioning index for facet position
  33724. var oy = 0; // Y partinioning index for facet position
  33725. var oz = 0; // Z partinioning index for facet position
  33726. var b1x = 0; // X partitioning index for facet v1 vertex
  33727. var b1y = 0; // Y partitioning index for facet v1 vertex
  33728. var b1z = 0; // z partitioning index for facet v1 vertex
  33729. var b2x = 0; // X partitioning index for facet v2 vertex
  33730. var b2y = 0; // Y partitioning index for facet v2 vertex
  33731. var b2z = 0; // Z partitioning index for facet v2 vertex
  33732. var b3x = 0; // X partitioning index for facet v3 vertex
  33733. var b3y = 0; // Y partitioning index for facet v3 vertex
  33734. var b3z = 0; // Z partitioning index for facet v3 vertex
  33735. var block_idx_o = 0; // facet barycenter block index
  33736. var block_idx_v1 = 0; // v1 vertex block index
  33737. var block_idx_v2 = 0; // v2 vertex block index
  33738. var block_idx_v3 = 0; // v3 vertex block index
  33739. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33740. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33741. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33742. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33743. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33744. subSq = options.subDiv.max * options.subDiv.max;
  33745. options.facetPartitioning.length = 0;
  33746. }
  33747. // reset the normals
  33748. for (index = 0; index < positions.length; index++) {
  33749. normals[index] = 0.0;
  33750. }
  33751. // Loop : 1 indice triplet = 1 facet
  33752. var nbFaces = (indices.length / 3) | 0;
  33753. for (index = 0; index < nbFaces; index++) {
  33754. // get the indexes of the coordinates of each vertex of the facet
  33755. v1x = indices[index * 3] * 3;
  33756. v1y = v1x + 1;
  33757. v1z = v1x + 2;
  33758. v2x = indices[index * 3 + 1] * 3;
  33759. v2y = v2x + 1;
  33760. v2z = v2x + 2;
  33761. v3x = indices[index * 3 + 2] * 3;
  33762. v3y = v3x + 1;
  33763. v3z = v3x + 2;
  33764. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33765. p1p2y = positions[v1y] - positions[v2y];
  33766. p1p2z = positions[v1z] - positions[v2z];
  33767. p3p2x = positions[v3x] - positions[v2x];
  33768. p3p2y = positions[v3y] - positions[v2y];
  33769. p3p2z = positions[v3z] - positions[v2z];
  33770. // compute the face normal with the cross product
  33771. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33772. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33773. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33774. // normalize this normal and store it in the array facetData
  33775. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33776. length = (length === 0) ? 1.0 : length;
  33777. faceNormalx /= length;
  33778. faceNormaly /= length;
  33779. faceNormalz /= length;
  33780. if (computeFacetNormals && options) {
  33781. options.facetNormals[index].x = faceNormalx;
  33782. options.facetNormals[index].y = faceNormaly;
  33783. options.facetNormals[index].z = faceNormalz;
  33784. }
  33785. if (computeFacetPositions && options) {
  33786. // compute and the facet barycenter coordinates in the array facetPositions
  33787. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33788. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33789. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33790. }
  33791. if (computeFacetPartitioning && options) {
  33792. // store the facet indexes in arrays in the main facetPartitioning array :
  33793. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33794. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33795. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33796. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33797. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33798. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33799. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33800. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33801. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33802. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33803. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33804. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33805. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33806. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33807. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33808. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33809. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33810. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33811. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33812. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33813. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33814. // push each facet index in each block containing the vertex
  33815. options.facetPartitioning[block_idx_v1].push(index);
  33816. if (block_idx_v2 != block_idx_v1) {
  33817. options.facetPartitioning[block_idx_v2].push(index);
  33818. }
  33819. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33820. options.facetPartitioning[block_idx_v3].push(index);
  33821. }
  33822. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33823. options.facetPartitioning[block_idx_o].push(index);
  33824. }
  33825. }
  33826. if (computeDepthSort && options && options.facetPositions) {
  33827. var dsf = depthSortedFacets[index];
  33828. dsf.ind = index * 3;
  33829. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33830. }
  33831. // compute the normals anyway
  33832. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33833. normals[v1y] += faceNormaly;
  33834. normals[v1z] += faceNormalz;
  33835. normals[v2x] += faceNormalx;
  33836. normals[v2y] += faceNormaly;
  33837. normals[v2z] += faceNormalz;
  33838. normals[v3x] += faceNormalx;
  33839. normals[v3y] += faceNormaly;
  33840. normals[v3z] += faceNormalz;
  33841. }
  33842. // last normalization of each normal
  33843. for (index = 0; index < normals.length / 3; index++) {
  33844. faceNormalx = normals[index * 3];
  33845. faceNormaly = normals[index * 3 + 1];
  33846. faceNormalz = normals[index * 3 + 2];
  33847. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33848. length = (length === 0) ? 1.0 : length;
  33849. faceNormalx /= length;
  33850. faceNormaly /= length;
  33851. faceNormalz /= length;
  33852. normals[index * 3] = faceNormalx;
  33853. normals[index * 3 + 1] = faceNormaly;
  33854. normals[index * 3 + 2] = faceNormalz;
  33855. }
  33856. };
  33857. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33858. var li = indices.length;
  33859. var ln = normals.length;
  33860. var i;
  33861. var n;
  33862. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33863. switch (sideOrientation) {
  33864. case BABYLON.Mesh.FRONTSIDE:
  33865. // nothing changed
  33866. break;
  33867. case BABYLON.Mesh.BACKSIDE:
  33868. var tmp;
  33869. // indices
  33870. for (i = 0; i < li; i += 3) {
  33871. tmp = indices[i];
  33872. indices[i] = indices[i + 2];
  33873. indices[i + 2] = tmp;
  33874. }
  33875. // normals
  33876. for (n = 0; n < ln; n++) {
  33877. normals[n] = -normals[n];
  33878. }
  33879. break;
  33880. case BABYLON.Mesh.DOUBLESIDE:
  33881. // positions
  33882. var lp = positions.length;
  33883. var l = lp / 3;
  33884. for (var p = 0; p < lp; p++) {
  33885. positions[lp + p] = positions[p];
  33886. }
  33887. // indices
  33888. for (i = 0; i < li; i += 3) {
  33889. indices[i + li] = indices[i + 2] + l;
  33890. indices[i + 1 + li] = indices[i + 1] + l;
  33891. indices[i + 2 + li] = indices[i] + l;
  33892. }
  33893. // normals
  33894. for (n = 0; n < ln; n++) {
  33895. normals[ln + n] = -normals[n];
  33896. }
  33897. // uvs
  33898. var lu = uvs.length;
  33899. var u = 0;
  33900. for (u = 0; u < lu; u++) {
  33901. uvs[u + lu] = uvs[u];
  33902. }
  33903. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33904. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33905. u = 0;
  33906. for (i = 0; i < lu / 2; i++) {
  33907. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33908. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33909. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33910. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33911. u += 2;
  33912. }
  33913. break;
  33914. }
  33915. };
  33916. /**
  33917. * Creates a new VertexData from the imported parameters.
  33918. */
  33919. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33920. var vertexData = new VertexData();
  33921. // positions
  33922. var positions = parsedVertexData.positions;
  33923. if (positions) {
  33924. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33925. }
  33926. // normals
  33927. var normals = parsedVertexData.normals;
  33928. if (normals) {
  33929. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33930. }
  33931. // tangents
  33932. var tangents = parsedVertexData.tangents;
  33933. if (tangents) {
  33934. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33935. }
  33936. // uvs
  33937. var uvs = parsedVertexData.uvs;
  33938. if (uvs) {
  33939. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33940. }
  33941. // uv2s
  33942. var uv2s = parsedVertexData.uv2s;
  33943. if (uv2s) {
  33944. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33945. }
  33946. // uv3s
  33947. var uv3s = parsedVertexData.uv3s;
  33948. if (uv3s) {
  33949. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33950. }
  33951. // uv4s
  33952. var uv4s = parsedVertexData.uv4s;
  33953. if (uv4s) {
  33954. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33955. }
  33956. // uv5s
  33957. var uv5s = parsedVertexData.uv5s;
  33958. if (uv5s) {
  33959. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33960. }
  33961. // uv6s
  33962. var uv6s = parsedVertexData.uv6s;
  33963. if (uv6s) {
  33964. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33965. }
  33966. // colors
  33967. var colors = parsedVertexData.colors;
  33968. if (colors) {
  33969. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33970. }
  33971. // matricesIndices
  33972. var matricesIndices = parsedVertexData.matricesIndices;
  33973. if (matricesIndices) {
  33974. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33975. }
  33976. // matricesWeights
  33977. var matricesWeights = parsedVertexData.matricesWeights;
  33978. if (matricesWeights) {
  33979. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33980. }
  33981. // indices
  33982. var indices = parsedVertexData.indices;
  33983. if (indices) {
  33984. vertexData.indices = indices;
  33985. }
  33986. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33987. };
  33988. return VertexData;
  33989. }());
  33990. BABYLON.VertexData = VertexData;
  33991. })(BABYLON || (BABYLON = {}));
  33992. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33993. var BABYLON;
  33994. (function (BABYLON) {
  33995. /**
  33996. * Class used to store geometry data (vertex buffers + index buffer)
  33997. */
  33998. var Geometry = /** @class */ (function () {
  33999. /**
  34000. * Creates a new geometry
  34001. * @param id defines the unique ID
  34002. * @param scene defines the hosting scene
  34003. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34004. * @param updatable defines if geometry must be updatable (false by default)
  34005. * @param mesh defines the mesh that will be associated with the geometry
  34006. */
  34007. function Geometry(id, scene, vertexData, updatable, mesh) {
  34008. if (updatable === void 0) { updatable = false; }
  34009. if (mesh === void 0) { mesh = null; }
  34010. /**
  34011. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34012. */
  34013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34014. this._totalVertices = 0;
  34015. this._isDisposed = false;
  34016. this._indexBufferIsUpdatable = false;
  34017. this.id = id;
  34018. this._engine = scene.getEngine();
  34019. this._meshes = [];
  34020. this._scene = scene;
  34021. //Init vertex buffer cache
  34022. this._vertexBuffers = {};
  34023. this._indices = [];
  34024. this._updatable = updatable;
  34025. // vertexData
  34026. if (vertexData) {
  34027. this.setAllVerticesData(vertexData, updatable);
  34028. }
  34029. else {
  34030. this._totalVertices = 0;
  34031. this._indices = [];
  34032. }
  34033. if (this._engine.getCaps().vertexArrayObject) {
  34034. this._vertexArrayObjects = {};
  34035. }
  34036. // applyToMesh
  34037. if (mesh) {
  34038. if (mesh.getClassName() === "LinesMesh") {
  34039. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34040. this.updateExtend();
  34041. }
  34042. this.applyToMesh(mesh);
  34043. mesh.computeWorldMatrix(true);
  34044. }
  34045. }
  34046. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34047. /**
  34048. * 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
  34049. */
  34050. get: function () {
  34051. return this._boundingBias;
  34052. },
  34053. /**
  34054. * 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
  34055. */
  34056. set: function (value) {
  34057. if (this._boundingBias && this._boundingBias.equals(value)) {
  34058. return;
  34059. }
  34060. this._boundingBias = value.clone();
  34061. this.updateBoundingInfo(true, null);
  34062. },
  34063. enumerable: true,
  34064. configurable: true
  34065. });
  34066. /**
  34067. * Static function used to attach a new empty geometry to a mesh
  34068. * @param mesh defines the mesh to attach the geometry to
  34069. * @returns the new {BABYLON.Geometry}
  34070. */
  34071. Geometry.CreateGeometryForMesh = function (mesh) {
  34072. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34073. geometry.applyToMesh(mesh);
  34074. return geometry;
  34075. };
  34076. Object.defineProperty(Geometry.prototype, "extend", {
  34077. /**
  34078. * Gets the current extend of the geometry
  34079. */
  34080. get: function () {
  34081. return this._extend;
  34082. },
  34083. enumerable: true,
  34084. configurable: true
  34085. });
  34086. /**
  34087. * Gets the hosting scene
  34088. * @returns the hosting {BABYLON.Scene}
  34089. */
  34090. Geometry.prototype.getScene = function () {
  34091. return this._scene;
  34092. };
  34093. /**
  34094. * Gets the hosting engine
  34095. * @returns the hosting {BABYLON.Engine}
  34096. */
  34097. Geometry.prototype.getEngine = function () {
  34098. return this._engine;
  34099. };
  34100. /**
  34101. * Defines if the geometry is ready to use
  34102. * @returns true if the geometry is ready to be used
  34103. */
  34104. Geometry.prototype.isReady = function () {
  34105. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34106. };
  34107. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34108. /**
  34109. * Gets a value indicating that the geometry should not be serialized
  34110. */
  34111. get: function () {
  34112. for (var index = 0; index < this._meshes.length; index++) {
  34113. if (!this._meshes[index].doNotSerialize) {
  34114. return false;
  34115. }
  34116. }
  34117. return true;
  34118. },
  34119. enumerable: true,
  34120. configurable: true
  34121. });
  34122. /** @ignore */
  34123. Geometry.prototype._rebuild = function () {
  34124. if (this._vertexArrayObjects) {
  34125. this._vertexArrayObjects = {};
  34126. }
  34127. // Index buffer
  34128. if (this._meshes.length !== 0 && this._indices) {
  34129. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34130. }
  34131. // Vertex buffers
  34132. for (var key in this._vertexBuffers) {
  34133. var vertexBuffer = this._vertexBuffers[key];
  34134. vertexBuffer._rebuild();
  34135. }
  34136. };
  34137. /**
  34138. * Affects all gemetry data in one call
  34139. * @param vertexData defines the geometry data
  34140. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34141. */
  34142. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34143. vertexData.applyToGeometry(this, updatable);
  34144. this.notifyUpdate();
  34145. };
  34146. /**
  34147. * Set specific vertex data
  34148. * @param kind defines the data kind (Position, normal, etc...)
  34149. * @param data defines the vertex data to use
  34150. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34151. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34152. */
  34153. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34154. if (updatable === void 0) { updatable = false; }
  34155. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34156. this.setVerticesBuffer(buffer);
  34157. };
  34158. /**
  34159. * Removes a specific vertex data
  34160. * @param kind defines the data kind (Position, normal, etc...)
  34161. */
  34162. Geometry.prototype.removeVerticesData = function (kind) {
  34163. if (this._vertexBuffers[kind]) {
  34164. this._vertexBuffers[kind].dispose();
  34165. delete this._vertexBuffers[kind];
  34166. }
  34167. };
  34168. /**
  34169. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34170. * @param buffer defines the vertex buffer to use
  34171. */
  34172. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34173. var kind = buffer.getKind();
  34174. if (this._vertexBuffers[kind]) {
  34175. this._vertexBuffers[kind].dispose();
  34176. }
  34177. this._vertexBuffers[kind] = buffer;
  34178. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34179. var data = buffer.getData();
  34180. var stride = buffer.getStrideSize();
  34181. this._totalVertices = data.length / stride;
  34182. this.updateExtend(data, stride);
  34183. this._resetPointsArrayCache();
  34184. var meshes = this._meshes;
  34185. var numOfMeshes = meshes.length;
  34186. for (var index = 0; index < numOfMeshes; index++) {
  34187. var mesh = meshes[index];
  34188. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34189. mesh._createGlobalSubMesh(false);
  34190. mesh.computeWorldMatrix(true);
  34191. }
  34192. }
  34193. this.notifyUpdate(kind);
  34194. if (this._vertexArrayObjects) {
  34195. this._disposeVertexArrayObjects();
  34196. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34197. }
  34198. };
  34199. /**
  34200. * Update a specific vertex buffer
  34201. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34202. * It will do nothing if the buffer is not updatable
  34203. * @param kind defines the data kind (Position, normal, etc...)
  34204. * @param data defines the data to use
  34205. * @param offset defines the offset in the target buffer where to store the data
  34206. */
  34207. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34208. var vertexBuffer = this.getVertexBuffer(kind);
  34209. if (!vertexBuffer) {
  34210. return;
  34211. }
  34212. vertexBuffer.updateDirectly(data, offset);
  34213. this.notifyUpdate(kind);
  34214. };
  34215. /**
  34216. * Update a specific vertex buffer
  34217. * This function will create a new buffer if the current one is not updatable
  34218. * @param kind defines the data kind (Position, normal, etc...)
  34219. * @param data defines the data to use
  34220. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34221. */
  34222. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34223. if (updateExtends === void 0) { updateExtends = false; }
  34224. var vertexBuffer = this.getVertexBuffer(kind);
  34225. if (!vertexBuffer) {
  34226. return;
  34227. }
  34228. vertexBuffer.update(data);
  34229. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34230. var stride = vertexBuffer.getStrideSize();
  34231. this._totalVertices = data.length / stride;
  34232. this.updateBoundingInfo(updateExtends, data);
  34233. }
  34234. this.notifyUpdate(kind);
  34235. };
  34236. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34237. if (updateExtends) {
  34238. this.updateExtend(data);
  34239. }
  34240. var meshes = this._meshes;
  34241. var numOfMeshes = meshes.length;
  34242. this._resetPointsArrayCache();
  34243. for (var index = 0; index < numOfMeshes; index++) {
  34244. var mesh = meshes[index];
  34245. if (updateExtends) {
  34246. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34247. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34248. var subMesh = mesh.subMeshes[subIndex];
  34249. subMesh.refreshBoundingInfo();
  34250. }
  34251. }
  34252. }
  34253. };
  34254. /** @ignore */
  34255. Geometry.prototype._bind = function (effect, indexToBind) {
  34256. if (!effect) {
  34257. return;
  34258. }
  34259. if (indexToBind === undefined) {
  34260. indexToBind = this._indexBuffer;
  34261. }
  34262. var vbs = this.getVertexBuffers();
  34263. if (!vbs) {
  34264. return;
  34265. }
  34266. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34267. this._engine.bindBuffers(vbs, indexToBind, effect);
  34268. return;
  34269. }
  34270. // Using VAO
  34271. if (!this._vertexArrayObjects[effect.key]) {
  34272. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34273. }
  34274. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34275. };
  34276. /**
  34277. * Gets total number of vertices
  34278. * @returns the total number of vertices
  34279. */
  34280. Geometry.prototype.getTotalVertices = function () {
  34281. if (!this.isReady()) {
  34282. return 0;
  34283. }
  34284. return this._totalVertices;
  34285. };
  34286. /**
  34287. * Gets a specific vertex data attached to this geometry
  34288. * @param kind defines the data kind (Position, normal, etc...)
  34289. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34290. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34291. * @returns a float array containing vertex data
  34292. */
  34293. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34294. var vertexBuffer = this.getVertexBuffer(kind);
  34295. if (!vertexBuffer) {
  34296. return null;
  34297. }
  34298. var orig = vertexBuffer.getData();
  34299. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34300. return orig;
  34301. }
  34302. else {
  34303. var len = orig.length;
  34304. var copy = [];
  34305. for (var i = 0; i < len; i++) {
  34306. copy.push(orig[i]);
  34307. }
  34308. return copy;
  34309. }
  34310. };
  34311. /**
  34312. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34313. * @param kind defines the data kind (Position, normal, etc...)
  34314. * @returns true if the vertex buffer with the specified kind is updatable
  34315. */
  34316. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34317. var vb = this._vertexBuffers[kind];
  34318. if (!vb) {
  34319. return false;
  34320. }
  34321. return vb.isUpdatable();
  34322. };
  34323. /**
  34324. * Gets a specific vertex buffer
  34325. * @param kind defines the data kind (Position, normal, etc...)
  34326. * @returns a {BABYLON.VertexBuffer}
  34327. */
  34328. Geometry.prototype.getVertexBuffer = function (kind) {
  34329. if (!this.isReady()) {
  34330. return null;
  34331. }
  34332. return this._vertexBuffers[kind];
  34333. };
  34334. /**
  34335. * Returns all vertex buffers
  34336. * @return an object holding all vertex buffers indexed by kind
  34337. */
  34338. Geometry.prototype.getVertexBuffers = function () {
  34339. if (!this.isReady()) {
  34340. return null;
  34341. }
  34342. return this._vertexBuffers;
  34343. };
  34344. /**
  34345. * Gets a boolean indicating if specific vertex buffer is present
  34346. * @param kind defines the data kind (Position, normal, etc...)
  34347. * @returns true if data is present
  34348. */
  34349. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34350. if (!this._vertexBuffers) {
  34351. if (this._delayInfo) {
  34352. return this._delayInfo.indexOf(kind) !== -1;
  34353. }
  34354. return false;
  34355. }
  34356. return this._vertexBuffers[kind] !== undefined;
  34357. };
  34358. /**
  34359. * Gets a list of all attached data kinds (Position, normal, etc...)
  34360. * @returns a list of string containing all kinds
  34361. */
  34362. Geometry.prototype.getVerticesDataKinds = function () {
  34363. var result = [];
  34364. var kind;
  34365. if (!this._vertexBuffers && this._delayInfo) {
  34366. for (kind in this._delayInfo) {
  34367. result.push(kind);
  34368. }
  34369. }
  34370. else {
  34371. for (kind in this._vertexBuffers) {
  34372. result.push(kind);
  34373. }
  34374. }
  34375. return result;
  34376. };
  34377. /**
  34378. * Update index buffer
  34379. * @param indices defines the indices to store in the index buffer
  34380. * @param offset defines the offset in the target buffer where to store the data
  34381. */
  34382. Geometry.prototype.updateIndices = function (indices, offset) {
  34383. if (!this._indexBuffer) {
  34384. return;
  34385. }
  34386. if (!this._indexBufferIsUpdatable) {
  34387. this.setIndices(indices, null, true);
  34388. }
  34389. else {
  34390. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34391. }
  34392. };
  34393. /**
  34394. * Creates a new index buffer
  34395. * @param indices defines the indices to store in the index buffer
  34396. * @param totalVertices defines the total number of vertices (could be null)
  34397. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34398. */
  34399. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34400. if (totalVertices === void 0) { totalVertices = null; }
  34401. if (updatable === void 0) { updatable = false; }
  34402. if (this._indexBuffer) {
  34403. this._engine._releaseBuffer(this._indexBuffer);
  34404. }
  34405. this._disposeVertexArrayObjects();
  34406. this._indices = indices;
  34407. this._indexBufferIsUpdatable = updatable;
  34408. if (this._meshes.length !== 0 && this._indices) {
  34409. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34410. }
  34411. if (totalVertices != undefined) {
  34412. this._totalVertices = totalVertices;
  34413. }
  34414. var meshes = this._meshes;
  34415. var numOfMeshes = meshes.length;
  34416. for (var index = 0; index < numOfMeshes; index++) {
  34417. meshes[index]._createGlobalSubMesh(true);
  34418. }
  34419. this.notifyUpdate();
  34420. };
  34421. /**
  34422. * Return the total number of indices
  34423. * @returns the total number of indices
  34424. */
  34425. Geometry.prototype.getTotalIndices = function () {
  34426. if (!this.isReady()) {
  34427. return 0;
  34428. }
  34429. return this._indices.length;
  34430. };
  34431. /**
  34432. * Gets the index buffer array
  34433. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34434. * @returns the index buffer array
  34435. */
  34436. Geometry.prototype.getIndices = function (copyWhenShared) {
  34437. if (!this.isReady()) {
  34438. return null;
  34439. }
  34440. var orig = this._indices;
  34441. if (!copyWhenShared || this._meshes.length === 1) {
  34442. return orig;
  34443. }
  34444. else {
  34445. var len = orig.length;
  34446. var copy = [];
  34447. for (var i = 0; i < len; i++) {
  34448. copy.push(orig[i]);
  34449. }
  34450. return copy;
  34451. }
  34452. };
  34453. /**
  34454. * Gets the index buffer
  34455. * @return the index buffer
  34456. */
  34457. Geometry.prototype.getIndexBuffer = function () {
  34458. if (!this.isReady()) {
  34459. return null;
  34460. }
  34461. return this._indexBuffer;
  34462. };
  34463. /** @ignore */
  34464. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34465. if (effect === void 0) { effect = null; }
  34466. if (!effect || !this._vertexArrayObjects) {
  34467. return;
  34468. }
  34469. if (this._vertexArrayObjects[effect.key]) {
  34470. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34471. delete this._vertexArrayObjects[effect.key];
  34472. }
  34473. };
  34474. /**
  34475. * Release the associated resources for a specific mesh
  34476. * @param mesh defines the source mesh
  34477. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34478. */
  34479. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34480. var meshes = this._meshes;
  34481. var index = meshes.indexOf(mesh);
  34482. if (index === -1) {
  34483. return;
  34484. }
  34485. meshes.splice(index, 1);
  34486. mesh._geometry = null;
  34487. if (meshes.length === 0 && shouldDispose) {
  34488. this.dispose();
  34489. }
  34490. };
  34491. /**
  34492. * Apply current geometry to a given mesh
  34493. * @param mesh defines the mesh to apply geometry to
  34494. */
  34495. Geometry.prototype.applyToMesh = function (mesh) {
  34496. if (mesh._geometry === this) {
  34497. return;
  34498. }
  34499. var previousGeometry = mesh._geometry;
  34500. if (previousGeometry) {
  34501. previousGeometry.releaseForMesh(mesh);
  34502. }
  34503. var meshes = this._meshes;
  34504. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34505. mesh._geometry = this;
  34506. this._scene.pushGeometry(this);
  34507. meshes.push(mesh);
  34508. if (this.isReady()) {
  34509. this._applyToMesh(mesh);
  34510. }
  34511. else {
  34512. mesh._boundingInfo = this._boundingInfo;
  34513. }
  34514. };
  34515. Geometry.prototype.updateExtend = function (data, stride) {
  34516. if (data === void 0) { data = null; }
  34517. if (!data) {
  34518. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34519. }
  34520. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34521. };
  34522. Geometry.prototype._applyToMesh = function (mesh) {
  34523. var numOfMeshes = this._meshes.length;
  34524. // vertexBuffers
  34525. for (var kind in this._vertexBuffers) {
  34526. if (numOfMeshes === 1) {
  34527. this._vertexBuffers[kind].create();
  34528. }
  34529. var buffer = this._vertexBuffers[kind].getBuffer();
  34530. if (buffer)
  34531. buffer.references = numOfMeshes;
  34532. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34533. if (!this._extend) {
  34534. this.updateExtend(this._vertexBuffers[kind].getData());
  34535. }
  34536. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34537. mesh._createGlobalSubMesh(false);
  34538. //bounding info was just created again, world matrix should be applied again.
  34539. mesh._updateBoundingInfo();
  34540. }
  34541. }
  34542. // indexBuffer
  34543. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34544. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34545. }
  34546. if (this._indexBuffer) {
  34547. this._indexBuffer.references = numOfMeshes;
  34548. }
  34549. };
  34550. Geometry.prototype.notifyUpdate = function (kind) {
  34551. if (this.onGeometryUpdated) {
  34552. this.onGeometryUpdated(this, kind);
  34553. }
  34554. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34555. var mesh = _a[_i];
  34556. mesh._markSubMeshesAsAttributesDirty();
  34557. }
  34558. };
  34559. /**
  34560. * Load the geometry if it was flagged as delay loaded
  34561. * @param scene defines the hosting scene
  34562. * @param onLoaded defines a callback called when the geometry is loaded
  34563. */
  34564. Geometry.prototype.load = function (scene, onLoaded) {
  34565. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34566. return;
  34567. }
  34568. if (this.isReady()) {
  34569. if (onLoaded) {
  34570. onLoaded();
  34571. }
  34572. return;
  34573. }
  34574. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34575. this._queueLoad(scene, onLoaded);
  34576. };
  34577. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34578. var _this = this;
  34579. if (!this.delayLoadingFile) {
  34580. return;
  34581. }
  34582. scene._addPendingData(this);
  34583. scene._loadFile(this.delayLoadingFile, function (data) {
  34584. if (!_this._delayLoadingFunction) {
  34585. return;
  34586. }
  34587. _this._delayLoadingFunction(JSON.parse(data), _this);
  34588. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34589. _this._delayInfo = [];
  34590. scene._removePendingData(_this);
  34591. var meshes = _this._meshes;
  34592. var numOfMeshes = meshes.length;
  34593. for (var index = 0; index < numOfMeshes; index++) {
  34594. _this._applyToMesh(meshes[index]);
  34595. }
  34596. if (onLoaded) {
  34597. onLoaded();
  34598. }
  34599. }, undefined, true);
  34600. };
  34601. /**
  34602. * Invert the geometry to move from a right handed system to a left handed one.
  34603. */
  34604. Geometry.prototype.toLeftHanded = function () {
  34605. // Flip faces
  34606. var tIndices = this.getIndices(false);
  34607. if (tIndices != null && tIndices.length > 0) {
  34608. for (var i = 0; i < tIndices.length; i += 3) {
  34609. var tTemp = tIndices[i + 0];
  34610. tIndices[i + 0] = tIndices[i + 2];
  34611. tIndices[i + 2] = tTemp;
  34612. }
  34613. this.setIndices(tIndices);
  34614. }
  34615. // Negate position.z
  34616. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34617. if (tPositions != null && tPositions.length > 0) {
  34618. for (var i = 0; i < tPositions.length; i += 3) {
  34619. tPositions[i + 2] = -tPositions[i + 2];
  34620. }
  34621. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34622. }
  34623. // Negate normal.z
  34624. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34625. if (tNormals != null && tNormals.length > 0) {
  34626. for (var i = 0; i < tNormals.length; i += 3) {
  34627. tNormals[i + 2] = -tNormals[i + 2];
  34628. }
  34629. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34630. }
  34631. };
  34632. // Cache
  34633. /** @ignore */
  34634. Geometry.prototype._resetPointsArrayCache = function () {
  34635. this._positions = null;
  34636. };
  34637. /** @ignore */
  34638. Geometry.prototype._generatePointsArray = function () {
  34639. if (this._positions)
  34640. return true;
  34641. this._positions = [];
  34642. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34643. if (!data) {
  34644. return false;
  34645. }
  34646. for (var index = 0; index < data.length; index += 3) {
  34647. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34648. }
  34649. return true;
  34650. };
  34651. /**
  34652. * Gets a value indicating if the geometry is disposed
  34653. * @returns true if the geometry was disposed
  34654. */
  34655. Geometry.prototype.isDisposed = function () {
  34656. return this._isDisposed;
  34657. };
  34658. Geometry.prototype._disposeVertexArrayObjects = function () {
  34659. if (this._vertexArrayObjects) {
  34660. for (var kind in this._vertexArrayObjects) {
  34661. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34662. }
  34663. this._vertexArrayObjects = {};
  34664. }
  34665. };
  34666. /**
  34667. * Free all associated resources
  34668. */
  34669. Geometry.prototype.dispose = function () {
  34670. var meshes = this._meshes;
  34671. var numOfMeshes = meshes.length;
  34672. var index;
  34673. for (index = 0; index < numOfMeshes; index++) {
  34674. this.releaseForMesh(meshes[index]);
  34675. }
  34676. this._meshes = [];
  34677. this._disposeVertexArrayObjects();
  34678. for (var kind in this._vertexBuffers) {
  34679. this._vertexBuffers[kind].dispose();
  34680. }
  34681. this._vertexBuffers = {};
  34682. this._totalVertices = 0;
  34683. if (this._indexBuffer) {
  34684. this._engine._releaseBuffer(this._indexBuffer);
  34685. }
  34686. this._indexBuffer = null;
  34687. this._indices = [];
  34688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34689. this.delayLoadingFile = null;
  34690. this._delayLoadingFunction = null;
  34691. this._delayInfo = [];
  34692. this._boundingInfo = null;
  34693. this._scene.removeGeometry(this);
  34694. this._isDisposed = true;
  34695. };
  34696. /**
  34697. * Clone the current geometry into a new geometry
  34698. * @param id defines the unique ID of the new geometry
  34699. * @returns a new geometry object
  34700. */
  34701. Geometry.prototype.copy = function (id) {
  34702. var vertexData = new BABYLON.VertexData();
  34703. vertexData.indices = [];
  34704. var indices = this.getIndices();
  34705. if (indices) {
  34706. for (var index = 0; index < indices.length; index++) {
  34707. vertexData.indices.push(indices[index]);
  34708. }
  34709. }
  34710. var updatable = false;
  34711. var stopChecking = false;
  34712. var kind;
  34713. for (kind in this._vertexBuffers) {
  34714. // using slice() to make a copy of the array and not just reference it
  34715. var data = this.getVerticesData(kind);
  34716. if (data instanceof Float32Array) {
  34717. vertexData.set(new Float32Array(data), kind);
  34718. }
  34719. else {
  34720. vertexData.set(data.slice(0), kind);
  34721. }
  34722. if (!stopChecking) {
  34723. var vb = this.getVertexBuffer(kind);
  34724. if (vb) {
  34725. updatable = vb.isUpdatable();
  34726. stopChecking = !updatable;
  34727. }
  34728. }
  34729. }
  34730. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34731. geometry.delayLoadState = this.delayLoadState;
  34732. geometry.delayLoadingFile = this.delayLoadingFile;
  34733. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34734. for (kind in this._delayInfo) {
  34735. geometry._delayInfo = geometry._delayInfo || [];
  34736. geometry._delayInfo.push(kind);
  34737. }
  34738. // Bounding info
  34739. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34740. return geometry;
  34741. };
  34742. /**
  34743. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34744. * @return a JSON representation of the current geometry data (without the vertices data)
  34745. */
  34746. Geometry.prototype.serialize = function () {
  34747. var serializationObject = {};
  34748. serializationObject.id = this.id;
  34749. serializationObject.updatable = this._updatable;
  34750. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34751. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34752. }
  34753. return serializationObject;
  34754. };
  34755. Geometry.prototype.toNumberArray = function (origin) {
  34756. if (Array.isArray(origin)) {
  34757. return origin;
  34758. }
  34759. else {
  34760. return Array.prototype.slice.call(origin);
  34761. }
  34762. };
  34763. /**
  34764. * Serialize all vertices data into a JSON oject
  34765. * @returns a JSON representation of the current geometry data
  34766. */
  34767. Geometry.prototype.serializeVerticeData = function () {
  34768. var serializationObject = this.serialize();
  34769. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34770. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34771. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34772. serializationObject.positions._updatable = true;
  34773. }
  34774. }
  34775. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34776. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34777. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34778. serializationObject.normals._updatable = true;
  34779. }
  34780. }
  34781. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34782. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34783. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34784. serializationObject.tangets._updatable = true;
  34785. }
  34786. }
  34787. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34788. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34789. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34790. serializationObject.uvs._updatable = true;
  34791. }
  34792. }
  34793. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34794. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34795. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34796. serializationObject.uv2s._updatable = true;
  34797. }
  34798. }
  34799. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34800. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34801. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34802. serializationObject.uv3s._updatable = true;
  34803. }
  34804. }
  34805. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34806. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34807. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34808. serializationObject.uv4s._updatable = true;
  34809. }
  34810. }
  34811. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34812. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34813. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34814. serializationObject.uv5s._updatable = true;
  34815. }
  34816. }
  34817. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34818. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34819. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34820. serializationObject.uv6s._updatable = true;
  34821. }
  34822. }
  34823. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34824. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34825. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34826. serializationObject.colors._updatable = true;
  34827. }
  34828. }
  34829. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34830. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34831. serializationObject.matricesIndices._isExpanded = true;
  34832. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34833. serializationObject.matricesIndices._updatable = true;
  34834. }
  34835. }
  34836. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34837. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34838. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34839. serializationObject.matricesWeights._updatable = true;
  34840. }
  34841. }
  34842. serializationObject.indices = this.toNumberArray(this.getIndices());
  34843. return serializationObject;
  34844. };
  34845. // Statics
  34846. /**
  34847. * Extracts a clone of a mesh geometry
  34848. * @param mesh defines the source mesh
  34849. * @param id defines the unique ID of the new geometry object
  34850. * @returns the new geometry object
  34851. */
  34852. Geometry.ExtractFromMesh = function (mesh, id) {
  34853. var geometry = mesh._geometry;
  34854. if (!geometry) {
  34855. return null;
  34856. }
  34857. return geometry.copy(id);
  34858. };
  34859. /**
  34860. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34861. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34862. * Be aware Math.random() could cause collisions, but:
  34863. * "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"
  34864. * @returns a string containing a new GUID
  34865. */
  34866. Geometry.RandomId = function () {
  34867. return BABYLON.Tools.RandomId();
  34868. };
  34869. /** @ignore */
  34870. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34871. var scene = mesh.getScene();
  34872. // Geometry
  34873. var geometryId = parsedGeometry.geometryId;
  34874. if (geometryId) {
  34875. var geometry = scene.getGeometryByID(geometryId);
  34876. if (geometry) {
  34877. geometry.applyToMesh(mesh);
  34878. }
  34879. }
  34880. else if (parsedGeometry instanceof ArrayBuffer) {
  34881. var binaryInfo = mesh._binaryInfo;
  34882. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34883. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34884. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34885. }
  34886. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34887. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34888. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34889. }
  34890. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34891. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34892. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34893. }
  34894. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34895. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34896. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34897. }
  34898. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34899. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34900. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34901. }
  34902. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34903. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34904. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34905. }
  34906. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34907. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34908. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34909. }
  34910. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34911. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34912. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34913. }
  34914. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34915. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34916. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34917. }
  34918. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34919. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34920. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34921. }
  34922. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34923. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34924. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34925. }
  34926. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34927. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34928. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34929. }
  34930. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34931. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34932. mesh.setIndices(indicesData, null);
  34933. }
  34934. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34935. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34936. mesh.subMeshes = [];
  34937. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34938. var materialIndex = subMeshesData[(i * 5) + 0];
  34939. var verticesStart = subMeshesData[(i * 5) + 1];
  34940. var verticesCount = subMeshesData[(i * 5) + 2];
  34941. var indexStart = subMeshesData[(i * 5) + 3];
  34942. var indexCount = subMeshesData[(i * 5) + 4];
  34943. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34944. }
  34945. }
  34946. }
  34947. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34948. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34949. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34950. if (parsedGeometry.tangents) {
  34951. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34952. }
  34953. if (parsedGeometry.uvs) {
  34954. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34955. }
  34956. if (parsedGeometry.uvs2) {
  34957. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34958. }
  34959. if (parsedGeometry.uvs3) {
  34960. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34961. }
  34962. if (parsedGeometry.uvs4) {
  34963. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34964. }
  34965. if (parsedGeometry.uvs5) {
  34966. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34967. }
  34968. if (parsedGeometry.uvs6) {
  34969. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34970. }
  34971. if (parsedGeometry.colors) {
  34972. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34973. }
  34974. if (parsedGeometry.matricesIndices) {
  34975. if (!parsedGeometry.matricesIndices._isExpanded) {
  34976. var floatIndices = [];
  34977. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34978. var matricesIndex = parsedGeometry.matricesIndices[i];
  34979. floatIndices.push(matricesIndex & 0x000000FF);
  34980. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34981. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34982. floatIndices.push(matricesIndex >> 24);
  34983. }
  34984. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34985. }
  34986. else {
  34987. delete parsedGeometry.matricesIndices._isExpanded;
  34988. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34989. }
  34990. }
  34991. if (parsedGeometry.matricesIndicesExtra) {
  34992. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34993. var floatIndices = [];
  34994. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34995. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34996. floatIndices.push(matricesIndex & 0x000000FF);
  34997. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34998. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34999. floatIndices.push(matricesIndex >> 24);
  35000. }
  35001. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35002. }
  35003. else {
  35004. delete parsedGeometry.matricesIndices._isExpanded;
  35005. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35006. }
  35007. }
  35008. if (parsedGeometry.matricesWeights) {
  35009. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35010. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35011. }
  35012. if (parsedGeometry.matricesWeightsExtra) {
  35013. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35014. }
  35015. mesh.setIndices(parsedGeometry.indices, null);
  35016. }
  35017. // SubMeshes
  35018. if (parsedGeometry.subMeshes) {
  35019. mesh.subMeshes = [];
  35020. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35021. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35022. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35023. }
  35024. }
  35025. // Flat shading
  35026. if (mesh._shouldGenerateFlatShading) {
  35027. mesh.convertToFlatShadedMesh();
  35028. delete mesh._shouldGenerateFlatShading;
  35029. }
  35030. // Update
  35031. mesh.computeWorldMatrix(true);
  35032. // Octree
  35033. var sceneOctree = scene.selectionOctree;
  35034. if (sceneOctree !== undefined && sceneOctree !== null) {
  35035. sceneOctree.addMesh(mesh);
  35036. }
  35037. };
  35038. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35039. var epsilon = 1e-3;
  35040. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35041. return;
  35042. }
  35043. var noInfluenceBoneIndex = 0.0;
  35044. if (parsedGeometry.skeletonId > -1) {
  35045. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35046. if (!skeleton) {
  35047. return;
  35048. }
  35049. noInfluenceBoneIndex = skeleton.bones.length;
  35050. }
  35051. else {
  35052. return;
  35053. }
  35054. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35055. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35056. var matricesWeights = parsedGeometry.matricesWeights;
  35057. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35058. var influencers = parsedGeometry.numBoneInfluencer;
  35059. var size = matricesWeights.length;
  35060. for (var i = 0; i < size; i += 4) {
  35061. var weight = 0.0;
  35062. var firstZeroWeight = -1;
  35063. for (var j = 0; j < 4; j++) {
  35064. var w = matricesWeights[i + j];
  35065. weight += w;
  35066. if (w < epsilon && firstZeroWeight < 0) {
  35067. firstZeroWeight = j;
  35068. }
  35069. }
  35070. if (matricesWeightsExtra) {
  35071. for (var j = 0; j < 4; j++) {
  35072. var w = matricesWeightsExtra[i + j];
  35073. weight += w;
  35074. if (w < epsilon && firstZeroWeight < 0) {
  35075. firstZeroWeight = j + 4;
  35076. }
  35077. }
  35078. }
  35079. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35080. firstZeroWeight = influencers - 1;
  35081. }
  35082. if (weight > epsilon) {
  35083. var mweight = 1.0 / weight;
  35084. for (var j = 0; j < 4; j++) {
  35085. matricesWeights[i + j] *= mweight;
  35086. }
  35087. if (matricesWeightsExtra) {
  35088. for (var j = 0; j < 4; j++) {
  35089. matricesWeightsExtra[i + j] *= mweight;
  35090. }
  35091. }
  35092. }
  35093. else {
  35094. if (firstZeroWeight >= 4) {
  35095. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35096. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35097. }
  35098. else {
  35099. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35100. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35101. }
  35102. }
  35103. }
  35104. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35105. if (parsedGeometry.matricesWeightsExtra) {
  35106. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35107. }
  35108. };
  35109. /**
  35110. * Create a new geometry from persisted data (Using .babylon file format)
  35111. * @param parsedVertexData defines the persisted data
  35112. * @param scene defines the hosting scene
  35113. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35114. * @returns the new geometry object
  35115. */
  35116. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35117. if (scene.getGeometryByID(parsedVertexData.id)) {
  35118. return null; // null since geometry could be something else than a box...
  35119. }
  35120. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35121. if (BABYLON.Tags) {
  35122. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35123. }
  35124. if (parsedVertexData.delayLoadingFile) {
  35125. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35126. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35127. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35128. geometry._delayInfo = [];
  35129. if (parsedVertexData.hasUVs) {
  35130. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35131. }
  35132. if (parsedVertexData.hasUVs2) {
  35133. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35134. }
  35135. if (parsedVertexData.hasUVs3) {
  35136. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35137. }
  35138. if (parsedVertexData.hasUVs4) {
  35139. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35140. }
  35141. if (parsedVertexData.hasUVs5) {
  35142. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35143. }
  35144. if (parsedVertexData.hasUVs6) {
  35145. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35146. }
  35147. if (parsedVertexData.hasColors) {
  35148. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35149. }
  35150. if (parsedVertexData.hasMatricesIndices) {
  35151. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35152. }
  35153. if (parsedVertexData.hasMatricesWeights) {
  35154. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35155. }
  35156. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35157. }
  35158. else {
  35159. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35160. }
  35161. scene.pushGeometry(geometry, true);
  35162. return geometry;
  35163. };
  35164. return Geometry;
  35165. }());
  35166. BABYLON.Geometry = Geometry;
  35167. // Primitives
  35168. /// Abstract class
  35169. /**
  35170. * Abstract class used to provide common services for all typed geometries
  35171. */
  35172. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35173. __extends(_PrimitiveGeometry, _super);
  35174. /**
  35175. * Creates a new typed geometry
  35176. * @param id defines the unique ID of the geometry
  35177. * @param scene defines the hosting scene
  35178. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35179. * @param mesh defines the hosting mesh (can be null)
  35180. */
  35181. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35182. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35183. if (mesh === void 0) { mesh = null; }
  35184. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35185. _this._canBeRegenerated = _canBeRegenerated;
  35186. _this._beingRegenerated = true;
  35187. _this.regenerate();
  35188. _this._beingRegenerated = false;
  35189. return _this;
  35190. }
  35191. /**
  35192. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35193. * @returns true if the geometry can be regenerated
  35194. */
  35195. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35196. return this._canBeRegenerated;
  35197. };
  35198. /**
  35199. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35200. */
  35201. _PrimitiveGeometry.prototype.regenerate = function () {
  35202. if (!this._canBeRegenerated) {
  35203. return;
  35204. }
  35205. this._beingRegenerated = true;
  35206. this.setAllVerticesData(this._regenerateVertexData(), false);
  35207. this._beingRegenerated = false;
  35208. };
  35209. /**
  35210. * Clone the geometry
  35211. * @param id defines the unique ID of the new geometry
  35212. * @returns the new geometry
  35213. */
  35214. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35215. return _super.prototype.copy.call(this, id);
  35216. };
  35217. // overrides
  35218. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35219. if (!this._beingRegenerated) {
  35220. return;
  35221. }
  35222. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35223. };
  35224. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35225. if (!this._beingRegenerated) {
  35226. return;
  35227. }
  35228. _super.prototype.setVerticesData.call(this, kind, data, false);
  35229. };
  35230. // to override
  35231. /** @ignore */
  35232. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35233. throw new Error("Abstract method");
  35234. };
  35235. _PrimitiveGeometry.prototype.copy = function (id) {
  35236. throw new Error("Must be overriden in sub-classes.");
  35237. };
  35238. _PrimitiveGeometry.prototype.serialize = function () {
  35239. var serializationObject = _super.prototype.serialize.call(this);
  35240. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35241. return serializationObject;
  35242. };
  35243. return _PrimitiveGeometry;
  35244. }(Geometry));
  35245. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35246. /**
  35247. * Creates a ribbon geometry
  35248. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35249. */
  35250. var RibbonGeometry = /** @class */ (function (_super) {
  35251. __extends(RibbonGeometry, _super);
  35252. /**
  35253. * Creates a ribbon geometry
  35254. * @param id defines the unique ID of the geometry
  35255. * @param scene defines the hosting scene
  35256. * @param pathArray defines the array of paths to use
  35257. * @param closeArray defines if the last path and the first path must be joined
  35258. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35259. * @param offset defines the offset between points
  35260. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35261. * @param mesh defines the hosting mesh (can be null)
  35262. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35263. */
  35264. function RibbonGeometry(id, scene,
  35265. /**
  35266. * Defines the array of paths to use
  35267. */
  35268. pathArray,
  35269. /**
  35270. * Defines if the last and first points of each path in your pathArray must be joined
  35271. */
  35272. closeArray,
  35273. /**
  35274. * Defines if the last and first points of each path in your pathArray must be joined
  35275. */
  35276. closePath,
  35277. /**
  35278. * Defines the offset between points
  35279. */
  35280. offset, canBeRegenerated, mesh,
  35281. /**
  35282. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35283. */
  35284. side) {
  35285. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35286. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35287. _this.pathArray = pathArray;
  35288. _this.closeArray = closeArray;
  35289. _this.closePath = closePath;
  35290. _this.offset = offset;
  35291. _this.side = side;
  35292. return _this;
  35293. }
  35294. /** @ignore */
  35295. RibbonGeometry.prototype._regenerateVertexData = function () {
  35296. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35297. };
  35298. RibbonGeometry.prototype.copy = function (id) {
  35299. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35300. };
  35301. return RibbonGeometry;
  35302. }(_PrimitiveGeometry));
  35303. BABYLON.RibbonGeometry = RibbonGeometry;
  35304. /**
  35305. * Creates a box geometry
  35306. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35307. */
  35308. var BoxGeometry = /** @class */ (function (_super) {
  35309. __extends(BoxGeometry, _super);
  35310. /**
  35311. * Creates a box geometry
  35312. * @param id defines the unique ID of the geometry
  35313. * @param scene defines the hosting scene
  35314. * @param size defines the zise of the box (width, height and depth are the same)
  35315. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35316. * @param mesh defines the hosting mesh (can be null)
  35317. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35318. */
  35319. function BoxGeometry(id, scene,
  35320. /**
  35321. * Defines the zise of the box (width, height and depth are the same)
  35322. */
  35323. size, canBeRegenerated, mesh,
  35324. /**
  35325. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35326. */
  35327. side) {
  35328. if (mesh === void 0) { mesh = null; }
  35329. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35330. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35331. _this.size = size;
  35332. _this.side = side;
  35333. return _this;
  35334. }
  35335. BoxGeometry.prototype._regenerateVertexData = function () {
  35336. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35337. };
  35338. BoxGeometry.prototype.copy = function (id) {
  35339. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35340. };
  35341. BoxGeometry.prototype.serialize = function () {
  35342. var serializationObject = _super.prototype.serialize.call(this);
  35343. serializationObject.size = this.size;
  35344. return serializationObject;
  35345. };
  35346. BoxGeometry.Parse = function (parsedBox, scene) {
  35347. if (scene.getGeometryByID(parsedBox.id)) {
  35348. return null; // null since geometry could be something else than a box...
  35349. }
  35350. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35351. if (BABYLON.Tags) {
  35352. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35353. }
  35354. scene.pushGeometry(box, true);
  35355. return box;
  35356. };
  35357. return BoxGeometry;
  35358. }(_PrimitiveGeometry));
  35359. BABYLON.BoxGeometry = BoxGeometry;
  35360. /**
  35361. * Creates a sphere geometry
  35362. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35363. */
  35364. var SphereGeometry = /** @class */ (function (_super) {
  35365. __extends(SphereGeometry, _super);
  35366. /**
  35367. * Create a new sphere geometry
  35368. * @param id defines the unique ID of the geometry
  35369. * @param scene defines the hosting scene
  35370. * @param segments defines the number of segments to use to create the sphere
  35371. * @param diameter defines the diameter of the sphere
  35372. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35373. * @param mesh defines the hosting mesh (can be null)
  35374. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35375. */
  35376. function SphereGeometry(id, scene,
  35377. /**
  35378. * Defines the number of segments to use to create the sphere
  35379. */
  35380. segments,
  35381. /**
  35382. * Defines the diameter of the sphere
  35383. */
  35384. diameter, canBeRegenerated, mesh,
  35385. /**
  35386. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35387. */
  35388. side) {
  35389. if (mesh === void 0) { mesh = null; }
  35390. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35391. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35392. _this.segments = segments;
  35393. _this.diameter = diameter;
  35394. _this.side = side;
  35395. return _this;
  35396. }
  35397. SphereGeometry.prototype._regenerateVertexData = function () {
  35398. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35399. };
  35400. SphereGeometry.prototype.copy = function (id) {
  35401. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35402. };
  35403. SphereGeometry.prototype.serialize = function () {
  35404. var serializationObject = _super.prototype.serialize.call(this);
  35405. serializationObject.segments = this.segments;
  35406. serializationObject.diameter = this.diameter;
  35407. return serializationObject;
  35408. };
  35409. SphereGeometry.Parse = function (parsedSphere, scene) {
  35410. if (scene.getGeometryByID(parsedSphere.id)) {
  35411. return null; // null since geometry could be something else than a sphere...
  35412. }
  35413. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35414. if (BABYLON.Tags) {
  35415. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35416. }
  35417. scene.pushGeometry(sphere, true);
  35418. return sphere;
  35419. };
  35420. return SphereGeometry;
  35421. }(_PrimitiveGeometry));
  35422. BABYLON.SphereGeometry = SphereGeometry;
  35423. /**
  35424. * Creates a disc geometry
  35425. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35426. */
  35427. var DiscGeometry = /** @class */ (function (_super) {
  35428. __extends(DiscGeometry, _super);
  35429. /**
  35430. * Creates a new disc geometry
  35431. * @param id defines the unique ID of the geometry
  35432. * @param scene defines the hosting scene
  35433. * @param radius defines the radius of the disc
  35434. * @param tessellation defines the tesselation factor to apply to the disc
  35435. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35436. * @param mesh defines the hosting mesh (can be null)
  35437. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35438. */
  35439. function DiscGeometry(id, scene,
  35440. /**
  35441. * Defines the radius of the disc
  35442. */
  35443. radius,
  35444. /**
  35445. * Defines the tesselation factor to apply to the disc
  35446. */
  35447. tessellation, canBeRegenerated, mesh,
  35448. /**
  35449. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35450. */
  35451. side) {
  35452. if (mesh === void 0) { mesh = null; }
  35453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35454. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35455. _this.radius = radius;
  35456. _this.tessellation = tessellation;
  35457. _this.side = side;
  35458. return _this;
  35459. }
  35460. DiscGeometry.prototype._regenerateVertexData = function () {
  35461. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35462. };
  35463. DiscGeometry.prototype.copy = function (id) {
  35464. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35465. };
  35466. return DiscGeometry;
  35467. }(_PrimitiveGeometry));
  35468. BABYLON.DiscGeometry = DiscGeometry;
  35469. /**
  35470. * Creates a new cylinder geometry
  35471. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35472. */
  35473. var CylinderGeometry = /** @class */ (function (_super) {
  35474. __extends(CylinderGeometry, _super);
  35475. /**
  35476. * Creates a new cylinder geometry
  35477. * @param id defines the unique ID of the geometry
  35478. * @param scene defines the hosting scene
  35479. * @param height defines the height of the cylinder
  35480. * @param diameterTop defines the diameter of the cylinder's top cap
  35481. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35482. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35483. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35484. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35485. * @param mesh defines the hosting mesh (can be null)
  35486. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35487. */
  35488. function CylinderGeometry(id, scene,
  35489. /**
  35490. * Defines the height of the cylinder
  35491. */
  35492. height,
  35493. /**
  35494. * Defines the diameter of the cylinder's top cap
  35495. */
  35496. diameterTop,
  35497. /**
  35498. * Defines the diameter of the cylinder's bottom cap
  35499. */
  35500. diameterBottom,
  35501. /**
  35502. * Defines the tessellation factor to apply to the cylinder
  35503. */
  35504. tessellation,
  35505. /**
  35506. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35507. */
  35508. subdivisions, canBeRegenerated, mesh,
  35509. /**
  35510. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35511. */
  35512. side) {
  35513. if (subdivisions === void 0) { subdivisions = 1; }
  35514. if (mesh === void 0) { mesh = null; }
  35515. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35516. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35517. _this.height = height;
  35518. _this.diameterTop = diameterTop;
  35519. _this.diameterBottom = diameterBottom;
  35520. _this.tessellation = tessellation;
  35521. _this.subdivisions = subdivisions;
  35522. _this.side = side;
  35523. return _this;
  35524. }
  35525. CylinderGeometry.prototype._regenerateVertexData = function () {
  35526. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35527. };
  35528. CylinderGeometry.prototype.copy = function (id) {
  35529. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35530. };
  35531. CylinderGeometry.prototype.serialize = function () {
  35532. var serializationObject = _super.prototype.serialize.call(this);
  35533. serializationObject.height = this.height;
  35534. serializationObject.diameterTop = this.diameterTop;
  35535. serializationObject.diameterBottom = this.diameterBottom;
  35536. serializationObject.tessellation = this.tessellation;
  35537. return serializationObject;
  35538. };
  35539. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35540. if (scene.getGeometryByID(parsedCylinder.id)) {
  35541. return null; // null since geometry could be something else than a cylinder...
  35542. }
  35543. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35544. if (BABYLON.Tags) {
  35545. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35546. }
  35547. scene.pushGeometry(cylinder, true);
  35548. return cylinder;
  35549. };
  35550. return CylinderGeometry;
  35551. }(_PrimitiveGeometry));
  35552. BABYLON.CylinderGeometry = CylinderGeometry;
  35553. /**
  35554. * Creates a new torus geometry
  35555. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35556. */
  35557. var TorusGeometry = /** @class */ (function (_super) {
  35558. __extends(TorusGeometry, _super);
  35559. /**
  35560. * Creates a new torus geometry
  35561. * @param id defines the unique ID of the geometry
  35562. * @param scene defines the hosting scene
  35563. * @param diameter defines the diameter of the torus
  35564. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35565. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35566. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35567. * @param mesh defines the hosting mesh (can be null)
  35568. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35569. */
  35570. function TorusGeometry(id, scene,
  35571. /**
  35572. * Defines the diameter of the torus
  35573. */
  35574. diameter,
  35575. /**
  35576. * Defines the thickness of the torus (ie. internal diameter)
  35577. */
  35578. thickness,
  35579. /**
  35580. * Defines the tesselation factor to apply to the torus
  35581. */
  35582. tessellation, canBeRegenerated, mesh,
  35583. /**
  35584. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35585. */
  35586. side) {
  35587. if (mesh === void 0) { mesh = null; }
  35588. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35589. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35590. _this.diameter = diameter;
  35591. _this.thickness = thickness;
  35592. _this.tessellation = tessellation;
  35593. _this.side = side;
  35594. return _this;
  35595. }
  35596. TorusGeometry.prototype._regenerateVertexData = function () {
  35597. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35598. };
  35599. TorusGeometry.prototype.copy = function (id) {
  35600. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35601. };
  35602. TorusGeometry.prototype.serialize = function () {
  35603. var serializationObject = _super.prototype.serialize.call(this);
  35604. serializationObject.diameter = this.diameter;
  35605. serializationObject.thickness = this.thickness;
  35606. serializationObject.tessellation = this.tessellation;
  35607. return serializationObject;
  35608. };
  35609. TorusGeometry.Parse = function (parsedTorus, scene) {
  35610. if (scene.getGeometryByID(parsedTorus.id)) {
  35611. return null; // null since geometry could be something else than a torus...
  35612. }
  35613. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35614. if (BABYLON.Tags) {
  35615. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35616. }
  35617. scene.pushGeometry(torus, true);
  35618. return torus;
  35619. };
  35620. return TorusGeometry;
  35621. }(_PrimitiveGeometry));
  35622. BABYLON.TorusGeometry = TorusGeometry;
  35623. /**
  35624. * Creates a new ground geometry
  35625. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35626. */
  35627. var GroundGeometry = /** @class */ (function (_super) {
  35628. __extends(GroundGeometry, _super);
  35629. /**
  35630. * Creates a new ground geometry
  35631. * @param id defines the unique ID of the geometry
  35632. * @param scene defines the hosting scene
  35633. * @param width defines the width of the ground
  35634. * @param height defines the height of the ground
  35635. * @param subdivisions defines the subdivisions to apply to the ground
  35636. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35637. * @param mesh defines the hosting mesh (can be null)
  35638. */
  35639. function GroundGeometry(id, scene,
  35640. /**
  35641. * Defines the width of the ground
  35642. */
  35643. width,
  35644. /**
  35645. * Defines the height of the ground
  35646. */
  35647. height,
  35648. /**
  35649. * Defines the subdivisions to apply to the ground
  35650. */
  35651. subdivisions, canBeRegenerated, mesh) {
  35652. if (mesh === void 0) { mesh = null; }
  35653. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35654. _this.width = width;
  35655. _this.height = height;
  35656. _this.subdivisions = subdivisions;
  35657. return _this;
  35658. }
  35659. GroundGeometry.prototype._regenerateVertexData = function () {
  35660. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35661. };
  35662. GroundGeometry.prototype.copy = function (id) {
  35663. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35664. };
  35665. GroundGeometry.prototype.serialize = function () {
  35666. var serializationObject = _super.prototype.serialize.call(this);
  35667. serializationObject.width = this.width;
  35668. serializationObject.height = this.height;
  35669. serializationObject.subdivisions = this.subdivisions;
  35670. return serializationObject;
  35671. };
  35672. GroundGeometry.Parse = function (parsedGround, scene) {
  35673. if (scene.getGeometryByID(parsedGround.id)) {
  35674. return null; // null since geometry could be something else than a ground...
  35675. }
  35676. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35677. if (BABYLON.Tags) {
  35678. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35679. }
  35680. scene.pushGeometry(ground, true);
  35681. return ground;
  35682. };
  35683. return GroundGeometry;
  35684. }(_PrimitiveGeometry));
  35685. BABYLON.GroundGeometry = GroundGeometry;
  35686. /**
  35687. * Creates a tiled ground geometry
  35688. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35689. */
  35690. var TiledGroundGeometry = /** @class */ (function (_super) {
  35691. __extends(TiledGroundGeometry, _super);
  35692. /**
  35693. * Creates a tiled ground geometry
  35694. * @param id defines the unique ID of the geometry
  35695. * @param scene defines the hosting scene
  35696. * @param xmin defines the minimum value on X axis
  35697. * @param zmin defines the minimum value on Z axis
  35698. * @param xmax defines the maximum value on X axis
  35699. * @param zmax defines the maximum value on Z axis
  35700. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35701. * @param precision defines the precision to use when computing the tiles
  35702. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35703. * @param mesh defines the hosting mesh (can be null)
  35704. */
  35705. function TiledGroundGeometry(id, scene,
  35706. /**
  35707. * Defines the minimum value on X axis
  35708. */
  35709. xmin,
  35710. /**
  35711. * Defines the minimum value on Z axis
  35712. */
  35713. zmin,
  35714. /**
  35715. * Defines the maximum value on X axis
  35716. */
  35717. xmax,
  35718. /**
  35719. * Defines the maximum value on Z axis
  35720. */
  35721. zmax,
  35722. /**
  35723. * Defines the subdivisions to apply to the ground
  35724. */
  35725. subdivisions,
  35726. /**
  35727. * Defines the precision to use when computing the tiles
  35728. */
  35729. precision, canBeRegenerated, mesh) {
  35730. if (mesh === void 0) { mesh = null; }
  35731. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35732. _this.xmin = xmin;
  35733. _this.zmin = zmin;
  35734. _this.xmax = xmax;
  35735. _this.zmax = zmax;
  35736. _this.subdivisions = subdivisions;
  35737. _this.precision = precision;
  35738. return _this;
  35739. }
  35740. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35741. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35742. };
  35743. TiledGroundGeometry.prototype.copy = function (id) {
  35744. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35745. };
  35746. return TiledGroundGeometry;
  35747. }(_PrimitiveGeometry));
  35748. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35749. /**
  35750. * Creates a plane geometry
  35751. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35752. */
  35753. var PlaneGeometry = /** @class */ (function (_super) {
  35754. __extends(PlaneGeometry, _super);
  35755. /**
  35756. * Creates a plane geometry
  35757. * @param id defines the unique ID of the geometry
  35758. * @param scene defines the hosting scene
  35759. * @param size defines the size of the plane (width === height)
  35760. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35761. * @param mesh defines the hosting mesh (can be null)
  35762. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35763. */
  35764. function PlaneGeometry(id, scene,
  35765. /**
  35766. * Defines the size of the plane (width === height)
  35767. */
  35768. size, canBeRegenerated, mesh,
  35769. /**
  35770. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35771. */
  35772. side) {
  35773. if (mesh === void 0) { mesh = null; }
  35774. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35775. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35776. _this.size = size;
  35777. _this.side = side;
  35778. return _this;
  35779. }
  35780. PlaneGeometry.prototype._regenerateVertexData = function () {
  35781. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35782. };
  35783. PlaneGeometry.prototype.copy = function (id) {
  35784. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35785. };
  35786. PlaneGeometry.prototype.serialize = function () {
  35787. var serializationObject = _super.prototype.serialize.call(this);
  35788. serializationObject.size = this.size;
  35789. return serializationObject;
  35790. };
  35791. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35792. if (scene.getGeometryByID(parsedPlane.id)) {
  35793. return null; // null since geometry could be something else than a ground...
  35794. }
  35795. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35796. if (BABYLON.Tags) {
  35797. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35798. }
  35799. scene.pushGeometry(plane, true);
  35800. return plane;
  35801. };
  35802. return PlaneGeometry;
  35803. }(_PrimitiveGeometry));
  35804. BABYLON.PlaneGeometry = PlaneGeometry;
  35805. /**
  35806. * Creates a torus knot geometry
  35807. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35808. */
  35809. var TorusKnotGeometry = /** @class */ (function (_super) {
  35810. __extends(TorusKnotGeometry, _super);
  35811. /**
  35812. * Creates a torus knot geometry
  35813. * @param id defines the unique ID of the geometry
  35814. * @param scene defines the hosting scene
  35815. * @param radius defines the radius of the torus knot
  35816. * @param tube defines the thickness of the torus knot tube
  35817. * @param radialSegments defines the number of radial segments
  35818. * @param tubularSegments defines the number of tubular segments
  35819. * @param p defines the first number of windings
  35820. * @param q defines the second number of windings
  35821. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35822. * @param mesh defines the hosting mesh (can be null)
  35823. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35824. */
  35825. function TorusKnotGeometry(id, scene,
  35826. /**
  35827. * Defines the radius of the torus knot
  35828. */
  35829. radius,
  35830. /**
  35831. * Defines the thickness of the torus knot tube
  35832. */
  35833. tube,
  35834. /**
  35835. * Defines the number of radial segments
  35836. */
  35837. radialSegments,
  35838. /**
  35839. * Defines the number of tubular segments
  35840. */
  35841. tubularSegments,
  35842. /**
  35843. * Defines the first number of windings
  35844. */
  35845. p,
  35846. /**
  35847. * Defines the second number of windings
  35848. */
  35849. q, canBeRegenerated, mesh,
  35850. /**
  35851. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35852. */
  35853. side) {
  35854. if (mesh === void 0) { mesh = null; }
  35855. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35856. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35857. _this.radius = radius;
  35858. _this.tube = tube;
  35859. _this.radialSegments = radialSegments;
  35860. _this.tubularSegments = tubularSegments;
  35861. _this.p = p;
  35862. _this.q = q;
  35863. _this.side = side;
  35864. return _this;
  35865. }
  35866. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35867. 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 });
  35868. };
  35869. TorusKnotGeometry.prototype.copy = function (id) {
  35870. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35871. };
  35872. TorusKnotGeometry.prototype.serialize = function () {
  35873. var serializationObject = _super.prototype.serialize.call(this);
  35874. serializationObject.radius = this.radius;
  35875. serializationObject.tube = this.tube;
  35876. serializationObject.radialSegments = this.radialSegments;
  35877. serializationObject.tubularSegments = this.tubularSegments;
  35878. serializationObject.p = this.p;
  35879. serializationObject.q = this.q;
  35880. return serializationObject;
  35881. };
  35882. ;
  35883. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35884. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35885. return null; // null since geometry could be something else than a ground...
  35886. }
  35887. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35888. if (BABYLON.Tags) {
  35889. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35890. }
  35891. scene.pushGeometry(torusKnot, true);
  35892. return torusKnot;
  35893. };
  35894. return TorusKnotGeometry;
  35895. }(_PrimitiveGeometry));
  35896. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35897. //}
  35898. })(BABYLON || (BABYLON = {}));
  35899. //# sourceMappingURL=babylon.geometry.js.map
  35900. var BABYLON;
  35901. (function (BABYLON) {
  35902. /**
  35903. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35904. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35905. */
  35906. var PostProcessManager = /** @class */ (function () {
  35907. /**
  35908. * Creates a new instance of @see PostProcess
  35909. * @param scene The scene that the post process is associated with.
  35910. */
  35911. function PostProcessManager(scene) {
  35912. this._vertexBuffers = {};
  35913. this._scene = scene;
  35914. }
  35915. PostProcessManager.prototype._prepareBuffers = function () {
  35916. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35917. return;
  35918. }
  35919. // VBO
  35920. var vertices = [];
  35921. vertices.push(1, 1);
  35922. vertices.push(-1, 1);
  35923. vertices.push(-1, -1);
  35924. vertices.push(1, -1);
  35925. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35926. this._buildIndexBuffer();
  35927. };
  35928. PostProcessManager.prototype._buildIndexBuffer = function () {
  35929. // Indices
  35930. var indices = [];
  35931. indices.push(0);
  35932. indices.push(1);
  35933. indices.push(2);
  35934. indices.push(0);
  35935. indices.push(2);
  35936. indices.push(3);
  35937. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35938. };
  35939. /**
  35940. * Rebuilds the vertex buffers of the manager.
  35941. */
  35942. PostProcessManager.prototype._rebuild = function () {
  35943. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35944. if (!vb) {
  35945. return;
  35946. }
  35947. vb._rebuild();
  35948. this._buildIndexBuffer();
  35949. };
  35950. // Methods
  35951. /**
  35952. * Prepares a frame to be run through a post process.
  35953. * @param sourceTexture The input texture to the post procesess. (default: null)
  35954. * @param postProcesses An array of post processes to be run. (default: null)
  35955. * @returns True if the post processes were able to be run.
  35956. */
  35957. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35958. if (sourceTexture === void 0) { sourceTexture = null; }
  35959. if (postProcesses === void 0) { postProcesses = null; }
  35960. var camera = this._scene.activeCamera;
  35961. if (!camera) {
  35962. return false;
  35963. }
  35964. var postProcesses = postProcesses || camera._postProcesses;
  35965. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35966. return false;
  35967. }
  35968. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35969. return true;
  35970. };
  35971. /**
  35972. * Manually render a set of post processes to a texture.
  35973. * @param postProcesses An array of post processes to be run.
  35974. * @param targetTexture The target texture to render to.
  35975. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35976. */
  35977. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35978. if (targetTexture === void 0) { targetTexture = null; }
  35979. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35980. var engine = this._scene.getEngine();
  35981. for (var index = 0; index < postProcesses.length; index++) {
  35982. if (index < postProcesses.length - 1) {
  35983. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35984. }
  35985. else {
  35986. if (targetTexture) {
  35987. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35988. }
  35989. else {
  35990. engine.restoreDefaultFramebuffer();
  35991. }
  35992. }
  35993. var pp = postProcesses[index];
  35994. var effect = pp.apply();
  35995. if (effect) {
  35996. pp.onBeforeRenderObservable.notifyObservers(effect);
  35997. // VBOs
  35998. this._prepareBuffers();
  35999. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36000. // Draw order
  36001. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36002. pp.onAfterRenderObservable.notifyObservers(effect);
  36003. }
  36004. }
  36005. // Restore depth buffer
  36006. engine.setDepthBuffer(true);
  36007. engine.setDepthWrite(true);
  36008. };
  36009. /**
  36010. * Finalize the result of the output of the postprocesses.
  36011. * @param doNotPresent If true the result will not be displayed to the screen.
  36012. * @param targetTexture The target texture to render to.
  36013. * @param faceIndex The index of the face to bind the target texture to.
  36014. * @param postProcesses The array of post processes to render.
  36015. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36016. */
  36017. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36018. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36019. var camera = this._scene.activeCamera;
  36020. if (!camera) {
  36021. return;
  36022. }
  36023. postProcesses = postProcesses || camera._postProcesses;
  36024. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36025. return;
  36026. }
  36027. var engine = this._scene.getEngine();
  36028. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36029. if (index < len - 1) {
  36030. postProcesses[index + 1].activate(camera, targetTexture);
  36031. }
  36032. else {
  36033. if (targetTexture) {
  36034. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36035. }
  36036. else {
  36037. engine.restoreDefaultFramebuffer();
  36038. }
  36039. }
  36040. if (doNotPresent) {
  36041. break;
  36042. }
  36043. var pp = postProcesses[index];
  36044. var effect = pp.apply();
  36045. if (effect) {
  36046. pp.onBeforeRenderObservable.notifyObservers(effect);
  36047. // VBOs
  36048. this._prepareBuffers();
  36049. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36050. // Draw order
  36051. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36052. pp.onAfterRenderObservable.notifyObservers(effect);
  36053. }
  36054. }
  36055. // Restore states
  36056. engine.setDepthBuffer(true);
  36057. engine.setDepthWrite(true);
  36058. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36059. };
  36060. /**
  36061. * Disposes of the post process manager.
  36062. */
  36063. PostProcessManager.prototype.dispose = function () {
  36064. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36065. if (buffer) {
  36066. buffer.dispose();
  36067. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36068. }
  36069. if (this._indexBuffer) {
  36070. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36071. this._indexBuffer = null;
  36072. }
  36073. };
  36074. return PostProcessManager;
  36075. }());
  36076. BABYLON.PostProcessManager = PostProcessManager;
  36077. })(BABYLON || (BABYLON = {}));
  36078. //# sourceMappingURL=babylon.postProcessManager.js.map
  36079. var BABYLON;
  36080. (function (BABYLON) {
  36081. /**
  36082. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36083. */
  36084. var PerformanceMonitor = /** @class */ (function () {
  36085. /**
  36086. * constructor
  36087. * @param frameSampleSize The number of samples required to saturate the sliding window
  36088. */
  36089. function PerformanceMonitor(frameSampleSize) {
  36090. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36091. this._enabled = true;
  36092. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36093. }
  36094. /**
  36095. * Samples current frame
  36096. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36097. */
  36098. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36099. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36100. if (!this._enabled)
  36101. return;
  36102. if (this._lastFrameTimeMs != null) {
  36103. var dt = timeMs - this._lastFrameTimeMs;
  36104. this._rollingFrameTime.add(dt);
  36105. }
  36106. this._lastFrameTimeMs = timeMs;
  36107. };
  36108. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36109. /**
  36110. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36111. * @return Average frame time in milliseconds
  36112. */
  36113. get: function () {
  36114. return this._rollingFrameTime.average;
  36115. },
  36116. enumerable: true,
  36117. configurable: true
  36118. });
  36119. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36120. /**
  36121. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36122. * @return Frame time variance in milliseconds squared
  36123. */
  36124. get: function () {
  36125. return this._rollingFrameTime.variance;
  36126. },
  36127. enumerable: true,
  36128. configurable: true
  36129. });
  36130. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36131. /**
  36132. * Returns the frame time of the most recent frame
  36133. * @return Frame time in milliseconds
  36134. */
  36135. get: function () {
  36136. return this._rollingFrameTime.history(0);
  36137. },
  36138. enumerable: true,
  36139. configurable: true
  36140. });
  36141. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36142. /**
  36143. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36144. * @return Framerate in frames per second
  36145. */
  36146. get: function () {
  36147. return 1000.0 / this._rollingFrameTime.average;
  36148. },
  36149. enumerable: true,
  36150. configurable: true
  36151. });
  36152. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36153. /**
  36154. * Returns the average framerate in frames per second using the most recent frame time
  36155. * @return Framerate in frames per second
  36156. */
  36157. get: function () {
  36158. var history = this._rollingFrameTime.history(0);
  36159. if (history === 0) {
  36160. return 0;
  36161. }
  36162. return 1000.0 / history;
  36163. },
  36164. enumerable: true,
  36165. configurable: true
  36166. });
  36167. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36168. /**
  36169. * Returns true if enough samples have been taken to completely fill the sliding window
  36170. * @return true if saturated
  36171. */
  36172. get: function () {
  36173. return this._rollingFrameTime.isSaturated();
  36174. },
  36175. enumerable: true,
  36176. configurable: true
  36177. });
  36178. /**
  36179. * Enables contributions to the sliding window sample set
  36180. */
  36181. PerformanceMonitor.prototype.enable = function () {
  36182. this._enabled = true;
  36183. };
  36184. /**
  36185. * Disables contributions to the sliding window sample set
  36186. * Samples will not be interpolated over the disabled period
  36187. */
  36188. PerformanceMonitor.prototype.disable = function () {
  36189. this._enabled = false;
  36190. //clear last sample to avoid interpolating over the disabled period when next enabled
  36191. this._lastFrameTimeMs = null;
  36192. };
  36193. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36194. /**
  36195. * Returns true if sampling is enabled
  36196. * @return true if enabled
  36197. */
  36198. get: function () {
  36199. return this._enabled;
  36200. },
  36201. enumerable: true,
  36202. configurable: true
  36203. });
  36204. /**
  36205. * Resets performance monitor
  36206. */
  36207. PerformanceMonitor.prototype.reset = function () {
  36208. //clear last sample to avoid interpolating over the disabled period when next enabled
  36209. this._lastFrameTimeMs = null;
  36210. //wipe record
  36211. this._rollingFrameTime.reset();
  36212. };
  36213. return PerformanceMonitor;
  36214. }());
  36215. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36216. /**
  36217. * RollingAverage
  36218. *
  36219. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36220. */
  36221. var RollingAverage = /** @class */ (function () {
  36222. /**
  36223. * constructor
  36224. * @param length The number of samples required to saturate the sliding window
  36225. */
  36226. function RollingAverage(length) {
  36227. this._samples = new Array(length);
  36228. this.reset();
  36229. }
  36230. /**
  36231. * Adds a sample to the sample set
  36232. * @param v The sample value
  36233. */
  36234. RollingAverage.prototype.add = function (v) {
  36235. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36236. var delta;
  36237. //we need to check if we've already wrapped round
  36238. if (this.isSaturated()) {
  36239. //remove bottom of stack from mean
  36240. var bottomValue = this._samples[this._pos];
  36241. delta = bottomValue - this.average;
  36242. this.average -= delta / (this._sampleCount - 1);
  36243. this._m2 -= delta * (bottomValue - this.average);
  36244. }
  36245. else {
  36246. this._sampleCount++;
  36247. }
  36248. //add new value to mean
  36249. delta = v - this.average;
  36250. this.average += delta / (this._sampleCount);
  36251. this._m2 += delta * (v - this.average);
  36252. //set the new variance
  36253. this.variance = this._m2 / (this._sampleCount - 1);
  36254. this._samples[this._pos] = v;
  36255. this._pos++;
  36256. this._pos %= this._samples.length; //positive wrap around
  36257. };
  36258. /**
  36259. * Returns previously added values or null if outside of history or outside the sliding window domain
  36260. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36261. * @return Value previously recorded with add() or null if outside of range
  36262. */
  36263. RollingAverage.prototype.history = function (i) {
  36264. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36265. return 0;
  36266. }
  36267. var i0 = this._wrapPosition(this._pos - 1.0);
  36268. return this._samples[this._wrapPosition(i0 - i)];
  36269. };
  36270. /**
  36271. * Returns true if enough samples have been taken to completely fill the sliding window
  36272. * @return true if sample-set saturated
  36273. */
  36274. RollingAverage.prototype.isSaturated = function () {
  36275. return this._sampleCount >= this._samples.length;
  36276. };
  36277. /**
  36278. * Resets the rolling average (equivalent to 0 samples taken so far)
  36279. */
  36280. RollingAverage.prototype.reset = function () {
  36281. this.average = 0;
  36282. this.variance = 0;
  36283. this._sampleCount = 0;
  36284. this._pos = 0;
  36285. this._m2 = 0;
  36286. };
  36287. /**
  36288. * Wraps a value around the sample range boundaries
  36289. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36290. * @return Wrapped position in sample range
  36291. */
  36292. RollingAverage.prototype._wrapPosition = function (i) {
  36293. var max = this._samples.length;
  36294. return ((i % max) + max) % max;
  36295. };
  36296. return RollingAverage;
  36297. }());
  36298. BABYLON.RollingAverage = RollingAverage;
  36299. })(BABYLON || (BABYLON = {}));
  36300. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36301. var BABYLON;
  36302. (function (BABYLON) {
  36303. /**
  36304. * This groups together the common properties used for image processing either in direct forward pass
  36305. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36306. * or not.
  36307. */
  36308. var ImageProcessingConfiguration = /** @class */ (function () {
  36309. function ImageProcessingConfiguration() {
  36310. /**
  36311. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36312. */
  36313. this.colorCurves = new BABYLON.ColorCurves();
  36314. this._colorCurvesEnabled = false;
  36315. this._colorGradingEnabled = false;
  36316. this._colorGradingWithGreenDepth = true;
  36317. this._colorGradingBGR = true;
  36318. this._exposure = 1.0;
  36319. this._toneMappingEnabled = false;
  36320. this._contrast = 1.0;
  36321. /**
  36322. * Vignette stretch size.
  36323. */
  36324. this.vignetteStretch = 0;
  36325. /**
  36326. * Vignette centre X Offset.
  36327. */
  36328. this.vignetteCentreX = 0;
  36329. /**
  36330. * Vignette centre Y Offset.
  36331. */
  36332. this.vignetteCentreY = 0;
  36333. /**
  36334. * Vignette weight or intensity of the vignette effect.
  36335. */
  36336. this.vignetteWeight = 1.5;
  36337. /**
  36338. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36339. * if vignetteEnabled is set to true.
  36340. */
  36341. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36342. /**
  36343. * Camera field of view used by the Vignette effect.
  36344. */
  36345. this.vignetteCameraFov = 0.5;
  36346. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36347. this._vignetteEnabled = false;
  36348. this._applyByPostProcess = false;
  36349. this._isEnabled = true;
  36350. /**
  36351. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36352. * @type {BABYLON.Observable}
  36353. */
  36354. this.onUpdateParameters = new BABYLON.Observable();
  36355. }
  36356. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36357. /**
  36358. * Gets wether the color curves effect is enabled.
  36359. */
  36360. get: function () {
  36361. return this._colorCurvesEnabled;
  36362. },
  36363. /**
  36364. * Sets wether the color curves effect is enabled.
  36365. */
  36366. set: function (value) {
  36367. if (this._colorCurvesEnabled === value) {
  36368. return;
  36369. }
  36370. this._colorCurvesEnabled = value;
  36371. this._updateParameters();
  36372. },
  36373. enumerable: true,
  36374. configurable: true
  36375. });
  36376. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36377. /**
  36378. * Gets wether the color grading effect is enabled.
  36379. */
  36380. get: function () {
  36381. return this._colorGradingEnabled;
  36382. },
  36383. /**
  36384. * Sets wether the color grading effect is enabled.
  36385. */
  36386. set: function (value) {
  36387. if (this._colorGradingEnabled === value) {
  36388. return;
  36389. }
  36390. this._colorGradingEnabled = value;
  36391. this._updateParameters();
  36392. },
  36393. enumerable: true,
  36394. configurable: true
  36395. });
  36396. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36397. /**
  36398. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36399. */
  36400. get: function () {
  36401. return this._colorGradingWithGreenDepth;
  36402. },
  36403. /**
  36404. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36405. */
  36406. set: function (value) {
  36407. if (this._colorGradingWithGreenDepth === value) {
  36408. return;
  36409. }
  36410. this._colorGradingWithGreenDepth = value;
  36411. this._updateParameters();
  36412. },
  36413. enumerable: true,
  36414. configurable: true
  36415. });
  36416. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36417. /**
  36418. * Gets wether the color grading texture contains BGR values.
  36419. */
  36420. get: function () {
  36421. return this._colorGradingBGR;
  36422. },
  36423. /**
  36424. * Sets wether the color grading texture contains BGR values.
  36425. */
  36426. set: function (value) {
  36427. if (this._colorGradingBGR === value) {
  36428. return;
  36429. }
  36430. this._colorGradingBGR = value;
  36431. this._updateParameters();
  36432. },
  36433. enumerable: true,
  36434. configurable: true
  36435. });
  36436. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36437. /**
  36438. * Gets the Exposure used in the effect.
  36439. */
  36440. get: function () {
  36441. return this._exposure;
  36442. },
  36443. /**
  36444. * Sets the Exposure used in the effect.
  36445. */
  36446. set: function (value) {
  36447. if (this._exposure === value) {
  36448. return;
  36449. }
  36450. this._exposure = value;
  36451. this._updateParameters();
  36452. },
  36453. enumerable: true,
  36454. configurable: true
  36455. });
  36456. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36457. /**
  36458. * Gets wether the tone mapping effect is enabled.
  36459. */
  36460. get: function () {
  36461. return this._toneMappingEnabled;
  36462. },
  36463. /**
  36464. * Sets wether the tone mapping effect is enabled.
  36465. */
  36466. set: function (value) {
  36467. if (this._toneMappingEnabled === value) {
  36468. return;
  36469. }
  36470. this._toneMappingEnabled = value;
  36471. this._updateParameters();
  36472. },
  36473. enumerable: true,
  36474. configurable: true
  36475. });
  36476. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36477. /**
  36478. * Gets the contrast used in the effect.
  36479. */
  36480. get: function () {
  36481. return this._contrast;
  36482. },
  36483. /**
  36484. * Sets the contrast used in the effect.
  36485. */
  36486. set: function (value) {
  36487. if (this._contrast === value) {
  36488. return;
  36489. }
  36490. this._contrast = value;
  36491. this._updateParameters();
  36492. },
  36493. enumerable: true,
  36494. configurable: true
  36495. });
  36496. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36497. /**
  36498. * Gets the vignette blend mode allowing different kind of effect.
  36499. */
  36500. get: function () {
  36501. return this._vignetteBlendMode;
  36502. },
  36503. /**
  36504. * Sets the vignette blend mode allowing different kind of effect.
  36505. */
  36506. set: function (value) {
  36507. if (this._vignetteBlendMode === value) {
  36508. return;
  36509. }
  36510. this._vignetteBlendMode = value;
  36511. this._updateParameters();
  36512. },
  36513. enumerable: true,
  36514. configurable: true
  36515. });
  36516. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36517. /**
  36518. * Gets wether the vignette effect is enabled.
  36519. */
  36520. get: function () {
  36521. return this._vignetteEnabled;
  36522. },
  36523. /**
  36524. * Sets wether the vignette effect is enabled.
  36525. */
  36526. set: function (value) {
  36527. if (this._vignetteEnabled === value) {
  36528. return;
  36529. }
  36530. this._vignetteEnabled = value;
  36531. this._updateParameters();
  36532. },
  36533. enumerable: true,
  36534. configurable: true
  36535. });
  36536. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36537. /**
  36538. * Gets wether the image processing is applied through a post process or not.
  36539. */
  36540. get: function () {
  36541. return this._applyByPostProcess;
  36542. },
  36543. /**
  36544. * Sets wether the image processing is applied through a post process or not.
  36545. */
  36546. set: function (value) {
  36547. if (this._applyByPostProcess === value) {
  36548. return;
  36549. }
  36550. this._applyByPostProcess = value;
  36551. this._updateParameters();
  36552. },
  36553. enumerable: true,
  36554. configurable: true
  36555. });
  36556. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36557. /**
  36558. * Gets wether the image processing is enabled or not.
  36559. */
  36560. get: function () {
  36561. return this._isEnabled;
  36562. },
  36563. /**
  36564. * Sets wether the image processing is enabled or not.
  36565. */
  36566. set: function (value) {
  36567. if (this._isEnabled === value) {
  36568. return;
  36569. }
  36570. this._isEnabled = value;
  36571. this._updateParameters();
  36572. },
  36573. enumerable: true,
  36574. configurable: true
  36575. });
  36576. /**
  36577. * Method called each time the image processing information changes requires to recompile the effect.
  36578. */
  36579. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36580. this.onUpdateParameters.notifyObservers(this);
  36581. };
  36582. ImageProcessingConfiguration.prototype.getClassName = function () {
  36583. return "ImageProcessingConfiguration";
  36584. };
  36585. /**
  36586. * Prepare the list of uniforms associated with the Image Processing effects.
  36587. * @param uniformsList The list of uniforms used in the effect
  36588. * @param defines the list of defines currently in use
  36589. */
  36590. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36591. if (defines.EXPOSURE) {
  36592. uniforms.push("exposureLinear");
  36593. }
  36594. if (defines.CONTRAST) {
  36595. uniforms.push("contrast");
  36596. }
  36597. if (defines.COLORGRADING) {
  36598. uniforms.push("colorTransformSettings");
  36599. }
  36600. if (defines.VIGNETTE) {
  36601. uniforms.push("vInverseScreenSize");
  36602. uniforms.push("vignetteSettings1");
  36603. uniforms.push("vignetteSettings2");
  36604. }
  36605. if (defines.COLORCURVES) {
  36606. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36607. }
  36608. };
  36609. /**
  36610. * Prepare the list of samplers associated with the Image Processing effects.
  36611. * @param uniformsList The list of uniforms used in the effect
  36612. * @param defines the list of defines currently in use
  36613. */
  36614. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36615. if (defines.COLORGRADING) {
  36616. samplersList.push("txColorTransform");
  36617. }
  36618. };
  36619. /**
  36620. * Prepare the list of defines associated to the shader.
  36621. * @param defines the list of defines to complete
  36622. */
  36623. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36624. if (forPostProcess === void 0) { forPostProcess = false; }
  36625. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36626. defines.VIGNETTE = false;
  36627. defines.TONEMAPPING = false;
  36628. defines.CONTRAST = false;
  36629. defines.EXPOSURE = false;
  36630. defines.COLORCURVES = false;
  36631. defines.COLORGRADING = false;
  36632. defines.COLORGRADING3D = false;
  36633. defines.IMAGEPROCESSING = false;
  36634. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36635. return;
  36636. }
  36637. defines.VIGNETTE = this.vignetteEnabled;
  36638. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36639. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36640. defines.TONEMAPPING = this.toneMappingEnabled;
  36641. defines.CONTRAST = (this.contrast !== 1.0);
  36642. defines.EXPOSURE = (this.exposure !== 1.0);
  36643. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36644. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36645. if (defines.COLORGRADING) {
  36646. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36647. }
  36648. else {
  36649. defines.COLORGRADING3D = false;
  36650. }
  36651. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36652. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36653. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36654. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36655. };
  36656. /**
  36657. * Returns true if all the image processing information are ready.
  36658. */
  36659. ImageProcessingConfiguration.prototype.isReady = function () {
  36660. // Color Grading texure can not be none blocking.
  36661. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36662. };
  36663. /**
  36664. * Binds the image processing to the shader.
  36665. * @param effect The effect to bind to
  36666. */
  36667. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36668. if (aspectRatio === void 0) { aspectRatio = 1; }
  36669. // Color Curves
  36670. if (this._colorCurvesEnabled && this.colorCurves) {
  36671. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36672. }
  36673. // Vignette
  36674. if (this._vignetteEnabled) {
  36675. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36676. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36677. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36678. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36679. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36680. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36681. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36682. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36683. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36684. var vignettePower = -2.0 * this.vignetteWeight;
  36685. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36686. }
  36687. // Exposure
  36688. effect.setFloat("exposureLinear", this.exposure);
  36689. // Contrast
  36690. effect.setFloat("contrast", this.contrast);
  36691. // Color transform settings
  36692. if (this.colorGradingTexture) {
  36693. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36694. var textureSize = this.colorGradingTexture.getSize().height;
  36695. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36696. 0.5 / textureSize, // textureOffset
  36697. textureSize, // textureSize
  36698. this.colorGradingTexture.level // weight
  36699. );
  36700. }
  36701. };
  36702. /**
  36703. * Clones the current image processing instance.
  36704. * @return The cloned image processing
  36705. */
  36706. ImageProcessingConfiguration.prototype.clone = function () {
  36707. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36708. };
  36709. /**
  36710. * Serializes the current image processing instance to a json representation.
  36711. * @return a JSON representation
  36712. */
  36713. ImageProcessingConfiguration.prototype.serialize = function () {
  36714. return BABYLON.SerializationHelper.Serialize(this);
  36715. };
  36716. /**
  36717. * Parses the image processing from a json representation.
  36718. * @param source the JSON source to parse
  36719. * @return The parsed image processing
  36720. */
  36721. ImageProcessingConfiguration.Parse = function (source) {
  36722. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36723. };
  36724. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36725. /**
  36726. * Used to apply the vignette as a mix with the pixel color.
  36727. */
  36728. get: function () {
  36729. return this._VIGNETTEMODE_MULTIPLY;
  36730. },
  36731. enumerable: true,
  36732. configurable: true
  36733. });
  36734. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36735. /**
  36736. * Used to apply the vignette as a replacement of the pixel color.
  36737. */
  36738. get: function () {
  36739. return this._VIGNETTEMODE_OPAQUE;
  36740. },
  36741. enumerable: true,
  36742. configurable: true
  36743. });
  36744. // Static constants associated to the image processing.
  36745. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36746. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36747. __decorate([
  36748. BABYLON.serializeAsColorCurves()
  36749. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36750. __decorate([
  36751. BABYLON.serialize()
  36752. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36753. __decorate([
  36754. BABYLON.serializeAsTexture()
  36755. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36756. __decorate([
  36757. BABYLON.serialize()
  36758. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36759. __decorate([
  36760. BABYLON.serialize()
  36761. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36762. __decorate([
  36763. BABYLON.serialize()
  36764. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36765. __decorate([
  36766. BABYLON.serialize()
  36767. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36768. __decorate([
  36769. BABYLON.serialize()
  36770. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36771. __decorate([
  36772. BABYLON.serialize()
  36773. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36774. __decorate([
  36775. BABYLON.serialize()
  36776. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36777. __decorate([
  36778. BABYLON.serialize()
  36779. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36780. __decorate([
  36781. BABYLON.serialize()
  36782. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36783. __decorate([
  36784. BABYLON.serialize()
  36785. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36786. __decorate([
  36787. BABYLON.serializeAsColor4()
  36788. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36789. __decorate([
  36790. BABYLON.serialize()
  36791. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36792. __decorate([
  36793. BABYLON.serialize()
  36794. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36795. __decorate([
  36796. BABYLON.serialize()
  36797. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36798. __decorate([
  36799. BABYLON.serialize()
  36800. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36801. __decorate([
  36802. BABYLON.serialize()
  36803. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36804. return ImageProcessingConfiguration;
  36805. }());
  36806. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36807. })(BABYLON || (BABYLON = {}));
  36808. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36809. var BABYLON;
  36810. (function (BABYLON) {
  36811. /**
  36812. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36813. * It can help converting any input color in a desired output one. This can then be used to create effects
  36814. * from sepia, black and white to sixties or futuristic rendering...
  36815. *
  36816. * The only supported format is currently 3dl.
  36817. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36818. */
  36819. var ColorGradingTexture = /** @class */ (function (_super) {
  36820. __extends(ColorGradingTexture, _super);
  36821. /**
  36822. * Instantiates a ColorGradingTexture from the following parameters.
  36823. *
  36824. * @param url The location of the color gradind data (currently only supporting 3dl)
  36825. * @param scene The scene the texture will be used in
  36826. */
  36827. function ColorGradingTexture(url, scene) {
  36828. var _this = _super.call(this, scene) || this;
  36829. if (!url) {
  36830. return _this;
  36831. }
  36832. _this._engine = scene.getEngine();
  36833. _this._textureMatrix = BABYLON.Matrix.Identity();
  36834. _this.name = url;
  36835. _this.url = url;
  36836. _this.hasAlpha = false;
  36837. _this.isCube = false;
  36838. _this.is3D = _this._engine.webGLVersion > 1;
  36839. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36840. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36841. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36842. _this.anisotropicFilteringLevel = 1;
  36843. _this._texture = _this._getFromCache(url, true);
  36844. if (!_this._texture) {
  36845. if (!scene.useDelayedTextureLoading) {
  36846. _this.loadTexture();
  36847. }
  36848. else {
  36849. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36850. }
  36851. }
  36852. return _this;
  36853. }
  36854. /**
  36855. * Returns the texture matrix used in most of the material.
  36856. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36857. */
  36858. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36859. return this._textureMatrix;
  36860. };
  36861. /**
  36862. * Occurs when the file being loaded is a .3dl LUT file.
  36863. */
  36864. ColorGradingTexture.prototype.load3dlTexture = function () {
  36865. var engine = this._engine;
  36866. var texture;
  36867. if (engine.webGLVersion === 1) {
  36868. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36869. }
  36870. else {
  36871. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36872. }
  36873. this._texture = texture;
  36874. var callback = function (text) {
  36875. if (typeof text !== "string") {
  36876. return;
  36877. }
  36878. var data = null;
  36879. var tempData = null;
  36880. var line;
  36881. var lines = text.split('\n');
  36882. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36883. var maxColor = 0;
  36884. for (var i = 0; i < lines.length; i++) {
  36885. line = lines[i];
  36886. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36887. continue;
  36888. if (line.indexOf('#') === 0)
  36889. continue;
  36890. var words = line.split(" ");
  36891. if (size === 0) {
  36892. // Number of space + one
  36893. size = words.length;
  36894. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36895. tempData = new Float32Array(size * size * size * 4);
  36896. continue;
  36897. }
  36898. if (size != 0) {
  36899. var r = Math.max(parseInt(words[0]), 0);
  36900. var g = Math.max(parseInt(words[1]), 0);
  36901. var b = Math.max(parseInt(words[2]), 0);
  36902. maxColor = Math.max(r, maxColor);
  36903. maxColor = Math.max(g, maxColor);
  36904. maxColor = Math.max(b, maxColor);
  36905. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36906. if (tempData) {
  36907. tempData[pixelStorageIndex + 0] = r;
  36908. tempData[pixelStorageIndex + 1] = g;
  36909. tempData[pixelStorageIndex + 2] = b;
  36910. }
  36911. pixelIndexSlice++;
  36912. if (pixelIndexSlice % size == 0) {
  36913. pixelIndexH++;
  36914. pixelIndexSlice = 0;
  36915. if (pixelIndexH % size == 0) {
  36916. pixelIndexW++;
  36917. pixelIndexH = 0;
  36918. }
  36919. }
  36920. }
  36921. }
  36922. if (tempData && data) {
  36923. for (var i = 0; i < tempData.length; i++) {
  36924. if (i > 0 && (i + 1) % 4 === 0) {
  36925. data[i] = 255;
  36926. }
  36927. else {
  36928. var value = tempData[i];
  36929. data[i] = (value / maxColor * 255);
  36930. }
  36931. }
  36932. }
  36933. if (texture.is3D) {
  36934. texture.updateSize(size, size, size);
  36935. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36936. }
  36937. else {
  36938. texture.updateSize(size * size, size);
  36939. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36940. }
  36941. };
  36942. var scene = this.getScene();
  36943. if (scene) {
  36944. scene._loadFile(this.url, callback);
  36945. }
  36946. else {
  36947. this._engine._loadFile(this.url, callback);
  36948. }
  36949. return this._texture;
  36950. };
  36951. /**
  36952. * Starts the loading process of the texture.
  36953. */
  36954. ColorGradingTexture.prototype.loadTexture = function () {
  36955. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36956. this.load3dlTexture();
  36957. }
  36958. };
  36959. /**
  36960. * Clones the color gradind texture.
  36961. */
  36962. ColorGradingTexture.prototype.clone = function () {
  36963. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36964. // Base texture
  36965. newTexture.level = this.level;
  36966. return newTexture;
  36967. };
  36968. /**
  36969. * Called during delayed load for textures.
  36970. */
  36971. ColorGradingTexture.prototype.delayLoad = function () {
  36972. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36973. return;
  36974. }
  36975. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36976. this._texture = this._getFromCache(this.url, true);
  36977. if (!this._texture) {
  36978. this.loadTexture();
  36979. }
  36980. };
  36981. /**
  36982. * Parses a color grading texture serialized by Babylon.
  36983. * @param parsedTexture The texture information being parsedTexture
  36984. * @param scene The scene to load the texture in
  36985. * @param rootUrl The root url of the data assets to load
  36986. * @return A color gradind texture
  36987. */
  36988. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36989. var texture = null;
  36990. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36991. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36992. texture.name = parsedTexture.name;
  36993. texture.level = parsedTexture.level;
  36994. }
  36995. return texture;
  36996. };
  36997. /**
  36998. * Serializes the LUT texture to json format.
  36999. */
  37000. ColorGradingTexture.prototype.serialize = function () {
  37001. if (!this.name) {
  37002. return null;
  37003. }
  37004. var serializationObject = {};
  37005. serializationObject.name = this.name;
  37006. serializationObject.level = this.level;
  37007. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37008. return serializationObject;
  37009. };
  37010. /**
  37011. * Empty line regex stored for GC.
  37012. */
  37013. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37014. return ColorGradingTexture;
  37015. }(BABYLON.BaseTexture));
  37016. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37017. })(BABYLON || (BABYLON = {}));
  37018. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37019. var BABYLON;
  37020. (function (BABYLON) {
  37021. /**
  37022. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37023. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37024. * 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;
  37025. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37026. */
  37027. var ColorCurves = /** @class */ (function () {
  37028. function ColorCurves() {
  37029. this._dirty = true;
  37030. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37031. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37032. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37033. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37034. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37035. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37036. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37037. this._globalHue = 30;
  37038. this._globalDensity = 0;
  37039. this._globalSaturation = 0;
  37040. this._globalExposure = 0;
  37041. this._highlightsHue = 30;
  37042. this._highlightsDensity = 0;
  37043. this._highlightsSaturation = 0;
  37044. this._highlightsExposure = 0;
  37045. this._midtonesHue = 30;
  37046. this._midtonesDensity = 0;
  37047. this._midtonesSaturation = 0;
  37048. this._midtonesExposure = 0;
  37049. this._shadowsHue = 30;
  37050. this._shadowsDensity = 0;
  37051. this._shadowsSaturation = 0;
  37052. this._shadowsExposure = 0;
  37053. }
  37054. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37055. /**
  37056. * Gets the global Hue value.
  37057. * 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).
  37058. */
  37059. get: function () {
  37060. return this._globalHue;
  37061. },
  37062. /**
  37063. * Sets the global Hue value.
  37064. * 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).
  37065. */
  37066. set: function (value) {
  37067. this._globalHue = value;
  37068. this._dirty = true;
  37069. },
  37070. enumerable: true,
  37071. configurable: true
  37072. });
  37073. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37074. /**
  37075. * Gets the global Density value.
  37076. * 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.
  37077. * Values less than zero provide a filter of opposite hue.
  37078. */
  37079. get: function () {
  37080. return this._globalDensity;
  37081. },
  37082. /**
  37083. * Sets the global Density value.
  37084. * 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.
  37085. * Values less than zero provide a filter of opposite hue.
  37086. */
  37087. set: function (value) {
  37088. this._globalDensity = value;
  37089. this._dirty = true;
  37090. },
  37091. enumerable: true,
  37092. configurable: true
  37093. });
  37094. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37095. /**
  37096. * Gets the global Saturation value.
  37097. * 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.
  37098. */
  37099. get: function () {
  37100. return this._globalSaturation;
  37101. },
  37102. /**
  37103. * Sets the global Saturation value.
  37104. * 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.
  37105. */
  37106. set: function (value) {
  37107. this._globalSaturation = value;
  37108. this._dirty = true;
  37109. },
  37110. enumerable: true,
  37111. configurable: true
  37112. });
  37113. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37114. /**
  37115. * Gets the highlights Hue value.
  37116. * 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).
  37117. */
  37118. get: function () {
  37119. return this._highlightsHue;
  37120. },
  37121. /**
  37122. * Sets the highlights Hue value.
  37123. * 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).
  37124. */
  37125. set: function (value) {
  37126. this._highlightsHue = value;
  37127. this._dirty = true;
  37128. },
  37129. enumerable: true,
  37130. configurable: true
  37131. });
  37132. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37133. /**
  37134. * Gets the highlights Density value.
  37135. * 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.
  37136. * Values less than zero provide a filter of opposite hue.
  37137. */
  37138. get: function () {
  37139. return this._highlightsDensity;
  37140. },
  37141. /**
  37142. * Sets the highlights Density value.
  37143. * 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.
  37144. * Values less than zero provide a filter of opposite hue.
  37145. */
  37146. set: function (value) {
  37147. this._highlightsDensity = value;
  37148. this._dirty = true;
  37149. },
  37150. enumerable: true,
  37151. configurable: true
  37152. });
  37153. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37154. /**
  37155. * Gets the highlights Saturation value.
  37156. * 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.
  37157. */
  37158. get: function () {
  37159. return this._highlightsSaturation;
  37160. },
  37161. /**
  37162. * Sets the highlights Saturation value.
  37163. * 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.
  37164. */
  37165. set: function (value) {
  37166. this._highlightsSaturation = value;
  37167. this._dirty = true;
  37168. },
  37169. enumerable: true,
  37170. configurable: true
  37171. });
  37172. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37173. /**
  37174. * Gets the highlights Exposure value.
  37175. * 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.
  37176. */
  37177. get: function () {
  37178. return this._highlightsExposure;
  37179. },
  37180. /**
  37181. * Sets the highlights Exposure value.
  37182. * 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.
  37183. */
  37184. set: function (value) {
  37185. this._highlightsExposure = value;
  37186. this._dirty = true;
  37187. },
  37188. enumerable: true,
  37189. configurable: true
  37190. });
  37191. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37192. /**
  37193. * Gets the midtones Hue value.
  37194. * 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).
  37195. */
  37196. get: function () {
  37197. return this._midtonesHue;
  37198. },
  37199. /**
  37200. * Sets the midtones Hue value.
  37201. * 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).
  37202. */
  37203. set: function (value) {
  37204. this._midtonesHue = value;
  37205. this._dirty = true;
  37206. },
  37207. enumerable: true,
  37208. configurable: true
  37209. });
  37210. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37211. /**
  37212. * Gets the midtones Density value.
  37213. * 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.
  37214. * Values less than zero provide a filter of opposite hue.
  37215. */
  37216. get: function () {
  37217. return this._midtonesDensity;
  37218. },
  37219. /**
  37220. * Sets the midtones Density value.
  37221. * 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.
  37222. * Values less than zero provide a filter of opposite hue.
  37223. */
  37224. set: function (value) {
  37225. this._midtonesDensity = value;
  37226. this._dirty = true;
  37227. },
  37228. enumerable: true,
  37229. configurable: true
  37230. });
  37231. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37232. /**
  37233. * Gets the midtones Saturation value.
  37234. * 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.
  37235. */
  37236. get: function () {
  37237. return this._midtonesSaturation;
  37238. },
  37239. /**
  37240. * Sets the midtones Saturation value.
  37241. * 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.
  37242. */
  37243. set: function (value) {
  37244. this._midtonesSaturation = value;
  37245. this._dirty = true;
  37246. },
  37247. enumerable: true,
  37248. configurable: true
  37249. });
  37250. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37251. /**
  37252. * Gets the midtones Exposure value.
  37253. * 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.
  37254. */
  37255. get: function () {
  37256. return this._midtonesExposure;
  37257. },
  37258. /**
  37259. * Sets the midtones Exposure value.
  37260. * 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.
  37261. */
  37262. set: function (value) {
  37263. this._midtonesExposure = value;
  37264. this._dirty = true;
  37265. },
  37266. enumerable: true,
  37267. configurable: true
  37268. });
  37269. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37270. /**
  37271. * Gets the shadows Hue value.
  37272. * 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).
  37273. */
  37274. get: function () {
  37275. return this._shadowsHue;
  37276. },
  37277. /**
  37278. * Sets the shadows Hue value.
  37279. * 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).
  37280. */
  37281. set: function (value) {
  37282. this._shadowsHue = value;
  37283. this._dirty = true;
  37284. },
  37285. enumerable: true,
  37286. configurable: true
  37287. });
  37288. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37289. /**
  37290. * Gets the shadows Density value.
  37291. * 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.
  37292. * Values less than zero provide a filter of opposite hue.
  37293. */
  37294. get: function () {
  37295. return this._shadowsDensity;
  37296. },
  37297. /**
  37298. * Sets the shadows Density value.
  37299. * 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.
  37300. * Values less than zero provide a filter of opposite hue.
  37301. */
  37302. set: function (value) {
  37303. this._shadowsDensity = value;
  37304. this._dirty = true;
  37305. },
  37306. enumerable: true,
  37307. configurable: true
  37308. });
  37309. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37310. /**
  37311. * Gets the shadows Saturation value.
  37312. * 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.
  37313. */
  37314. get: function () {
  37315. return this._shadowsSaturation;
  37316. },
  37317. /**
  37318. * Sets the shadows Saturation value.
  37319. * 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.
  37320. */
  37321. set: function (value) {
  37322. this._shadowsSaturation = value;
  37323. this._dirty = true;
  37324. },
  37325. enumerable: true,
  37326. configurable: true
  37327. });
  37328. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37329. /**
  37330. * Gets the shadows Exposure value.
  37331. * 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.
  37332. */
  37333. get: function () {
  37334. return this._shadowsExposure;
  37335. },
  37336. /**
  37337. * Sets the shadows Exposure value.
  37338. * 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.
  37339. */
  37340. set: function (value) {
  37341. this._shadowsExposure = value;
  37342. this._dirty = true;
  37343. },
  37344. enumerable: true,
  37345. configurable: true
  37346. });
  37347. ColorCurves.prototype.getClassName = function () {
  37348. return "ColorCurves";
  37349. };
  37350. /**
  37351. * Binds the color curves to the shader.
  37352. * @param colorCurves The color curve to bind
  37353. * @param effect The effect to bind to
  37354. */
  37355. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37356. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37357. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37358. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37359. if (colorCurves._dirty) {
  37360. colorCurves._dirty = false;
  37361. // Fill in global info.
  37362. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37363. // Compute highlights info.
  37364. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37365. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37366. // Compute midtones info.
  37367. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37368. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37369. // Compute shadows info.
  37370. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37371. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37372. // Compute deltas (neutral is midtones).
  37373. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37374. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37375. }
  37376. if (effect) {
  37377. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37378. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37379. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37380. }
  37381. };
  37382. /**
  37383. * Prepare the list of uniforms associated with the ColorCurves effects.
  37384. * @param uniformsList The list of uniforms used in the effect
  37385. */
  37386. ColorCurves.PrepareUniforms = function (uniformsList) {
  37387. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37388. };
  37389. /**
  37390. * Returns color grading data based on a hue, density, saturation and exposure value.
  37391. * @param filterHue The hue of the color filter.
  37392. * @param filterDensity The density of the color filter.
  37393. * @param saturation The saturation.
  37394. * @param exposure The exposure.
  37395. * @param result The result data container.
  37396. */
  37397. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37398. if (hue == null) {
  37399. return;
  37400. }
  37401. hue = ColorCurves.clamp(hue, 0, 360);
  37402. density = ColorCurves.clamp(density, -100, 100);
  37403. saturation = ColorCurves.clamp(saturation, -100, 100);
  37404. exposure = ColorCurves.clamp(exposure, -100, 100);
  37405. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37406. // so that the maximum filter density is only 50% control. This provides fine control
  37407. // for small values and reasonable range.
  37408. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37409. density *= 0.5;
  37410. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37411. if (density < 0) {
  37412. density *= -1;
  37413. hue = (hue + 180) % 360;
  37414. }
  37415. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37416. result.scaleToRef(2, result);
  37417. result.a = 1 + 0.01 * saturation;
  37418. };
  37419. /**
  37420. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37421. * @param value The input slider value in range [-100,100].
  37422. * @returns Adjusted value.
  37423. */
  37424. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37425. value /= 100;
  37426. var x = Math.abs(value);
  37427. x = Math.pow(x, 2);
  37428. if (value < 0) {
  37429. x *= -1;
  37430. }
  37431. x *= 100;
  37432. return x;
  37433. };
  37434. /**
  37435. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37436. * @param hue The hue (H) input.
  37437. * @param saturation The saturation (S) input.
  37438. * @param brightness The brightness (B) input.
  37439. * @result An RGBA color represented as Vector4.
  37440. */
  37441. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37442. var h = ColorCurves.clamp(hue, 0, 360);
  37443. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37444. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37445. if (s === 0) {
  37446. result.r = v;
  37447. result.g = v;
  37448. result.b = v;
  37449. }
  37450. else {
  37451. // sector 0 to 5
  37452. h /= 60;
  37453. var i = Math.floor(h);
  37454. // fractional part of h
  37455. var f = h - i;
  37456. var p = v * (1 - s);
  37457. var q = v * (1 - s * f);
  37458. var t = v * (1 - s * (1 - f));
  37459. switch (i) {
  37460. case 0:
  37461. result.r = v;
  37462. result.g = t;
  37463. result.b = p;
  37464. break;
  37465. case 1:
  37466. result.r = q;
  37467. result.g = v;
  37468. result.b = p;
  37469. break;
  37470. case 2:
  37471. result.r = p;
  37472. result.g = v;
  37473. result.b = t;
  37474. break;
  37475. case 3:
  37476. result.r = p;
  37477. result.g = q;
  37478. result.b = v;
  37479. break;
  37480. case 4:
  37481. result.r = t;
  37482. result.g = p;
  37483. result.b = v;
  37484. break;
  37485. default:// case 5:
  37486. result.r = v;
  37487. result.g = p;
  37488. result.b = q;
  37489. break;
  37490. }
  37491. }
  37492. result.a = 1;
  37493. };
  37494. /**
  37495. * Returns a value clamped between min and max
  37496. * @param value The value to clamp
  37497. * @param min The minimum of value
  37498. * @param max The maximum of value
  37499. * @returns The clamped value.
  37500. */
  37501. ColorCurves.clamp = function (value, min, max) {
  37502. return Math.min(Math.max(value, min), max);
  37503. };
  37504. /**
  37505. * Clones the current color curve instance.
  37506. * @return The cloned curves
  37507. */
  37508. ColorCurves.prototype.clone = function () {
  37509. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37510. };
  37511. /**
  37512. * Serializes the current color curve instance to a json representation.
  37513. * @return a JSON representation
  37514. */
  37515. ColorCurves.prototype.serialize = function () {
  37516. return BABYLON.SerializationHelper.Serialize(this);
  37517. };
  37518. /**
  37519. * Parses the color curve from a json representation.
  37520. * @param source the JSON source to parse
  37521. * @return The parsed curves
  37522. */
  37523. ColorCurves.Parse = function (source) {
  37524. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37525. };
  37526. __decorate([
  37527. BABYLON.serialize()
  37528. ], ColorCurves.prototype, "_globalHue", void 0);
  37529. __decorate([
  37530. BABYLON.serialize()
  37531. ], ColorCurves.prototype, "_globalDensity", void 0);
  37532. __decorate([
  37533. BABYLON.serialize()
  37534. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37535. __decorate([
  37536. BABYLON.serialize()
  37537. ], ColorCurves.prototype, "_globalExposure", void 0);
  37538. __decorate([
  37539. BABYLON.serialize()
  37540. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37541. __decorate([
  37542. BABYLON.serialize()
  37543. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37544. __decorate([
  37545. BABYLON.serialize()
  37546. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37547. __decorate([
  37548. BABYLON.serialize()
  37549. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37550. __decorate([
  37551. BABYLON.serialize()
  37552. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37553. __decorate([
  37554. BABYLON.serialize()
  37555. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37556. __decorate([
  37557. BABYLON.serialize()
  37558. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37559. __decorate([
  37560. BABYLON.serialize()
  37561. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37562. return ColorCurves;
  37563. }());
  37564. BABYLON.ColorCurves = ColorCurves;
  37565. })(BABYLON || (BABYLON = {}));
  37566. //# sourceMappingURL=babylon.colorCurves.js.map
  37567. //# sourceMappingURL=babylon.behavior.js.map
  37568. var BABYLON;
  37569. (function (BABYLON) {
  37570. /**
  37571. * "Static Class" containing the most commonly used helper while dealing with material for
  37572. * rendering purpose.
  37573. *
  37574. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37575. *
  37576. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37577. */
  37578. var MaterialHelper = /** @class */ (function () {
  37579. function MaterialHelper() {
  37580. }
  37581. /**
  37582. * Bind the current view position to an effect.
  37583. * @param effect The effect to be bound
  37584. * @param scene The scene the eyes position is used from
  37585. */
  37586. MaterialHelper.BindEyePosition = function (effect, scene) {
  37587. if (scene._forcedViewPosition) {
  37588. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37589. return;
  37590. }
  37591. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37592. };
  37593. /**
  37594. * Helps preparing the defines values about the UVs in used in the effect.
  37595. * UVs are shared as much as we can accross chanels in the shaders.
  37596. * @param texture The texture we are preparing the UVs for
  37597. * @param defines The defines to update
  37598. * @param key The chanel key "diffuse", "specular"... used in the shader
  37599. */
  37600. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37601. defines._needUVs = true;
  37602. defines[key] = true;
  37603. if (texture.getTextureMatrix().isIdentity(true)) {
  37604. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37605. if (texture.coordinatesIndex === 0) {
  37606. defines["MAINUV1"] = true;
  37607. }
  37608. else {
  37609. defines["MAINUV2"] = true;
  37610. }
  37611. }
  37612. else {
  37613. defines[key + "DIRECTUV"] = 0;
  37614. }
  37615. };
  37616. /**
  37617. * Binds a texture matrix value to its corrsponding uniform
  37618. * @param texture The texture to bind the matrix for
  37619. * @param uniformBuffer The uniform buffer receivin the data
  37620. * @param key The chanel key "diffuse", "specular"... used in the shader
  37621. */
  37622. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37623. var matrix = texture.getTextureMatrix();
  37624. if (!matrix.isIdentity(true)) {
  37625. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37626. }
  37627. };
  37628. /**
  37629. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37630. * @param mesh defines the current mesh
  37631. * @param scene defines the current scene
  37632. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37633. * @param pointsCloud defines if point cloud rendering has to be turned on
  37634. * @param fogEnabled defines if fog has to be turned on
  37635. * @param alphaTest defines if alpha testing has to be turned on
  37636. * @param defines defines the current list of defines
  37637. */
  37638. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37639. if (defines._areMiscDirty) {
  37640. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37641. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37642. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37643. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37644. defines["ALPHATEST"] = alphaTest;
  37645. }
  37646. };
  37647. /**
  37648. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37649. * @param scene defines the current scene
  37650. * @param engine defines the current engine
  37651. * @param defines specifies the list of active defines
  37652. * @param useInstances defines if instances have to be turned on
  37653. * @param useClipPlane defines if clip plane have to be turned on
  37654. */
  37655. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37656. if (useClipPlane === void 0) { useClipPlane = null; }
  37657. var changed = false;
  37658. if (useClipPlane == null) {
  37659. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37660. }
  37661. if (defines["CLIPPLANE"] !== useClipPlane) {
  37662. defines["CLIPPLANE"] = useClipPlane;
  37663. changed = true;
  37664. }
  37665. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37666. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37667. changed = true;
  37668. }
  37669. if (defines["INSTANCES"] !== useInstances) {
  37670. defines["INSTANCES"] = useInstances;
  37671. changed = true;
  37672. }
  37673. if (changed) {
  37674. defines.markAsUnprocessed();
  37675. }
  37676. };
  37677. /**
  37678. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37679. * @param mesh The mesh containing the geometry data we will draw
  37680. * @param defines The defines to update
  37681. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37682. * @param useBones Precise whether bones should be used or not (override mesh info)
  37683. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37684. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37685. * @returns false if defines are considered not dirty and have not been checked
  37686. */
  37687. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37688. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37689. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37690. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37691. return false;
  37692. }
  37693. defines._normals = defines._needNormals;
  37694. defines._uvs = defines._needUVs;
  37695. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37696. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37697. defines["TANGENT"] = true;
  37698. }
  37699. if (defines._needUVs) {
  37700. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37701. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37702. }
  37703. else {
  37704. defines["UV1"] = false;
  37705. defines["UV2"] = false;
  37706. }
  37707. if (useVertexColor) {
  37708. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37709. defines["VERTEXCOLOR"] = hasVertexColors;
  37710. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37711. }
  37712. if (useBones) {
  37713. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37714. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37715. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37716. }
  37717. else {
  37718. defines["NUM_BONE_INFLUENCERS"] = 0;
  37719. defines["BonesPerMesh"] = 0;
  37720. }
  37721. }
  37722. if (useMorphTargets) {
  37723. var manager = mesh.morphTargetManager;
  37724. if (manager) {
  37725. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37726. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37727. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37728. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37729. }
  37730. else {
  37731. defines["MORPHTARGETS_TANGENT"] = false;
  37732. defines["MORPHTARGETS_NORMAL"] = false;
  37733. defines["MORPHTARGETS"] = false;
  37734. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37735. }
  37736. }
  37737. return true;
  37738. };
  37739. /**
  37740. * Prepares the defines related to the light information passed in parameter
  37741. * @param scene The scene we are intending to draw
  37742. * @param mesh The mesh the effect is compiling for
  37743. * @param defines The defines to update
  37744. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37745. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37746. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37747. * @returns true if normals will be required for the rest of the effect
  37748. */
  37749. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37750. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37751. if (disableLighting === void 0) { disableLighting = false; }
  37752. if (!defines._areLightsDirty) {
  37753. return defines._needNormals;
  37754. }
  37755. var lightIndex = 0;
  37756. var needNormals = false;
  37757. var needRebuild = false;
  37758. var lightmapMode = false;
  37759. var shadowEnabled = false;
  37760. var specularEnabled = false;
  37761. if (scene.lightsEnabled && !disableLighting) {
  37762. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37763. var light = _a[_i];
  37764. needNormals = true;
  37765. if (defines["LIGHT" + lightIndex] === undefined) {
  37766. needRebuild = true;
  37767. }
  37768. defines["LIGHT" + lightIndex] = true;
  37769. defines["SPOTLIGHT" + lightIndex] = false;
  37770. defines["HEMILIGHT" + lightIndex] = false;
  37771. defines["POINTLIGHT" + lightIndex] = false;
  37772. defines["DIRLIGHT" + lightIndex] = false;
  37773. var type;
  37774. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37775. type = "SPOTLIGHT" + lightIndex;
  37776. var spotLight = light;
  37777. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37778. }
  37779. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37780. type = "HEMILIGHT" + lightIndex;
  37781. }
  37782. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37783. type = "POINTLIGHT" + lightIndex;
  37784. }
  37785. else {
  37786. type = "DIRLIGHT" + lightIndex;
  37787. }
  37788. defines[type] = true;
  37789. // Specular
  37790. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37791. specularEnabled = true;
  37792. }
  37793. // Shadows
  37794. defines["SHADOW" + lightIndex] = false;
  37795. defines["SHADOWPCF" + lightIndex] = false;
  37796. defines["SHADOWESM" + lightIndex] = false;
  37797. defines["SHADOWCUBE" + lightIndex] = false;
  37798. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37799. var shadowGenerator = light.getShadowGenerator();
  37800. if (shadowGenerator) {
  37801. shadowEnabled = true;
  37802. shadowGenerator.prepareDefines(defines, lightIndex);
  37803. }
  37804. }
  37805. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37806. lightmapMode = true;
  37807. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37808. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37809. }
  37810. else {
  37811. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37812. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37813. }
  37814. lightIndex++;
  37815. if (lightIndex === maxSimultaneousLights)
  37816. break;
  37817. }
  37818. }
  37819. defines["SPECULARTERM"] = specularEnabled;
  37820. defines["SHADOWS"] = shadowEnabled;
  37821. // Resetting all other lights if any
  37822. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37823. if (defines["LIGHT" + index] !== undefined) {
  37824. defines["LIGHT" + index] = false;
  37825. defines["HEMILIGHT" + lightIndex] = false;
  37826. defines["POINTLIGHT" + lightIndex] = false;
  37827. defines["DIRLIGHT" + lightIndex] = false;
  37828. defines["SPOTLIGHT" + lightIndex] = false;
  37829. defines["SHADOW" + lightIndex] = false;
  37830. }
  37831. }
  37832. var caps = scene.getEngine().getCaps();
  37833. if (defines["SHADOWFLOAT"] === undefined) {
  37834. needRebuild = true;
  37835. }
  37836. defines["SHADOWFLOAT"] = shadowEnabled &&
  37837. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37838. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37839. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37840. if (needRebuild) {
  37841. defines.rebuild();
  37842. }
  37843. return needNormals;
  37844. };
  37845. /**
  37846. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37847. * that won t be acctive due to defines being turned off.
  37848. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37849. * @param samplersList The samplers list
  37850. * @param defines The defines helping in the list generation
  37851. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37852. */
  37853. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37854. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37855. var uniformsList;
  37856. var uniformBuffersList = null;
  37857. if (uniformsListOrOptions.uniformsNames) {
  37858. var options = uniformsListOrOptions;
  37859. uniformsList = options.uniformsNames;
  37860. uniformBuffersList = options.uniformBuffersNames;
  37861. samplersList = options.samplers;
  37862. defines = options.defines;
  37863. maxSimultaneousLights = options.maxSimultaneousLights;
  37864. }
  37865. else {
  37866. uniformsList = uniformsListOrOptions;
  37867. if (!samplersList) {
  37868. samplersList = [];
  37869. }
  37870. }
  37871. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37872. if (!defines["LIGHT" + lightIndex]) {
  37873. break;
  37874. }
  37875. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37876. if (uniformBuffersList) {
  37877. uniformBuffersList.push("Light" + lightIndex);
  37878. }
  37879. samplersList.push("shadowSampler" + lightIndex);
  37880. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37881. samplersList.push("projectionLightSampler" + lightIndex);
  37882. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37883. }
  37884. }
  37885. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37886. uniformsList.push("morphTargetInfluences");
  37887. }
  37888. };
  37889. /**
  37890. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37891. * @param defines The defines to update while falling back
  37892. * @param fallbacks The authorized effect fallbacks
  37893. * @param maxSimultaneousLights The maximum number of lights allowed
  37894. * @param rank the current rank of the Effect
  37895. * @returns The newly affected rank
  37896. */
  37897. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37898. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37899. if (rank === void 0) { rank = 0; }
  37900. var lightFallbackRank = 0;
  37901. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37902. if (!defines["LIGHT" + lightIndex]) {
  37903. break;
  37904. }
  37905. if (lightIndex > 0) {
  37906. lightFallbackRank = rank + lightIndex;
  37907. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37908. }
  37909. if (!defines["SHADOWS"]) {
  37910. if (defines["SHADOW" + lightIndex]) {
  37911. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37912. }
  37913. if (defines["SHADOWPCF" + lightIndex]) {
  37914. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37915. }
  37916. if (defines["SHADOWESM" + lightIndex]) {
  37917. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37918. }
  37919. }
  37920. }
  37921. return lightFallbackRank++;
  37922. };
  37923. /**
  37924. * Prepares the list of attributes required for morph targets according to the effect defines.
  37925. * @param attribs The current list of supported attribs
  37926. * @param mesh The mesh to prepare the morph targets attributes for
  37927. * @param defines The current Defines of the effect
  37928. */
  37929. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37930. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37931. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37932. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37933. var manager = mesh.morphTargetManager;
  37934. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37935. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37936. for (var index = 0; index < influencers; index++) {
  37937. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37938. if (normal) {
  37939. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37940. }
  37941. if (tangent) {
  37942. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37943. }
  37944. if (attribs.length > maxAttributesCount) {
  37945. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37946. }
  37947. }
  37948. }
  37949. };
  37950. /**
  37951. * Prepares the list of attributes required for bones according to the effect defines.
  37952. * @param attribs The current list of supported attribs
  37953. * @param mesh The mesh to prepare the bones attributes for
  37954. * @param defines The current Defines of the effect
  37955. * @param fallbacks The current efffect fallback strategy
  37956. */
  37957. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37958. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37959. fallbacks.addCPUSkinningFallback(0, mesh);
  37960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37962. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37965. }
  37966. }
  37967. };
  37968. /**
  37969. * Prepares the list of attributes required for instances according to the effect defines.
  37970. * @param attribs The current list of supported attribs
  37971. * @param defines The current Defines of the effect
  37972. */
  37973. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37974. if (defines["INSTANCES"]) {
  37975. attribs.push("world0");
  37976. attribs.push("world1");
  37977. attribs.push("world2");
  37978. attribs.push("world3");
  37979. }
  37980. };
  37981. /**
  37982. * Binds the light shadow information to the effect for the given mesh.
  37983. * @param light The light containing the generator
  37984. * @param scene The scene the lights belongs to
  37985. * @param mesh The mesh we are binding the information to render
  37986. * @param lightIndex The light index in the effect used to render the mesh
  37987. * @param effect The effect we are binding the data to
  37988. */
  37989. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37990. if (light.shadowEnabled && mesh.receiveShadows) {
  37991. var shadowGenerator = light.getShadowGenerator();
  37992. if (shadowGenerator) {
  37993. shadowGenerator.bindShadowLight(lightIndex, effect);
  37994. }
  37995. }
  37996. };
  37997. /**
  37998. * Binds the light information to the effect.
  37999. * @param light The light containing the generator
  38000. * @param effect The effect we are binding the data to
  38001. * @param lightIndex The light index in the effect used to render
  38002. */
  38003. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38004. light.transferToEffect(effect, lightIndex + "");
  38005. };
  38006. /**
  38007. * Binds the lights information from the scene to the effect for the given mesh.
  38008. * @param scene The scene the lights belongs to
  38009. * @param mesh The mesh we are binding the information to render
  38010. * @param effect The effect we are binding the data to
  38011. * @param defines The generated defines for the effect
  38012. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38013. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38014. */
  38015. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38016. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38017. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38018. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38019. for (var i = 0; i < len; i++) {
  38020. var light = mesh._lightSources[i];
  38021. var iAsString = i.toString();
  38022. var scaledIntensity = light.getScaledIntensity();
  38023. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38024. MaterialHelper.BindLightProperties(light, effect, i);
  38025. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38026. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38027. if (defines["SPECULARTERM"]) {
  38028. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38029. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38030. }
  38031. // Shadows
  38032. if (scene.shadowsEnabled) {
  38033. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38034. }
  38035. light._uniformBuffer.update();
  38036. }
  38037. };
  38038. /**
  38039. * Binds the fog information from the scene to the effect for the given mesh.
  38040. * @param scene The scene the lights belongs to
  38041. * @param mesh The mesh we are binding the information to render
  38042. * @param effect The effect we are binding the data to
  38043. */
  38044. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38045. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38046. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38047. effect.setColor3("vFogColor", scene.fogColor);
  38048. }
  38049. };
  38050. /**
  38051. * Binds the bones information from the mesh to the effect.
  38052. * @param mesh The mesh we are binding the information to render
  38053. * @param effect The effect we are binding the data to
  38054. */
  38055. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38056. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38057. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38058. if (matrices && effect) {
  38059. effect.setMatrices("mBones", matrices);
  38060. }
  38061. }
  38062. };
  38063. /**
  38064. * Binds the morph targets information from the mesh to the effect.
  38065. * @param abstractMesh The mesh we are binding the information to render
  38066. * @param effect The effect we are binding the data to
  38067. */
  38068. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38069. var manager = abstractMesh.morphTargetManager;
  38070. if (!abstractMesh || !manager) {
  38071. return;
  38072. }
  38073. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38074. };
  38075. /**
  38076. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38077. * @param defines The generated defines used in the effect
  38078. * @param effect The effect we are binding the data to
  38079. * @param scene The scene we are willing to render with logarithmic scale for
  38080. */
  38081. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38082. if (defines["LOGARITHMICDEPTH"]) {
  38083. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38084. }
  38085. };
  38086. /**
  38087. * Binds the clip plane information from the scene to the effect.
  38088. * @param scene The scene the clip plane information are extracted from
  38089. * @param effect The effect we are binding the data to
  38090. */
  38091. MaterialHelper.BindClipPlane = function (effect, scene) {
  38092. if (scene.clipPlane) {
  38093. var clipPlane = scene.clipPlane;
  38094. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38095. }
  38096. };
  38097. return MaterialHelper;
  38098. }());
  38099. BABYLON.MaterialHelper = MaterialHelper;
  38100. })(BABYLON || (BABYLON = {}));
  38101. //# sourceMappingURL=babylon.materialHelper.js.map
  38102. var BABYLON;
  38103. (function (BABYLON) {
  38104. var PushMaterial = /** @class */ (function (_super) {
  38105. __extends(PushMaterial, _super);
  38106. function PushMaterial(name, scene) {
  38107. var _this = _super.call(this, name, scene) || this;
  38108. _this.storeEffectOnSubMeshes = true;
  38109. return _this;
  38110. }
  38111. PushMaterial.prototype.getEffect = function () {
  38112. return this._activeEffect;
  38113. };
  38114. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38115. if (!mesh) {
  38116. return false;
  38117. }
  38118. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38119. return true;
  38120. }
  38121. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38122. };
  38123. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38124. this._activeEffect.setMatrix("world", world);
  38125. };
  38126. PushMaterial.prototype.bind = function (world, mesh) {
  38127. if (!mesh) {
  38128. return;
  38129. }
  38130. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38131. };
  38132. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38133. if (effect === void 0) { effect = null; }
  38134. _super.prototype._afterBind.call(this, mesh);
  38135. this.getScene()._cachedEffect = effect;
  38136. };
  38137. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38138. if (visibility === void 0) { visibility = 1; }
  38139. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38140. };
  38141. return PushMaterial;
  38142. }(BABYLON.Material));
  38143. BABYLON.PushMaterial = PushMaterial;
  38144. })(BABYLON || (BABYLON = {}));
  38145. //# sourceMappingURL=babylon.pushMaterial.js.map
  38146. var BABYLON;
  38147. (function (BABYLON) {
  38148. /** @ignore */
  38149. var StandardMaterialDefines = /** @class */ (function (_super) {
  38150. __extends(StandardMaterialDefines, _super);
  38151. function StandardMaterialDefines() {
  38152. var _this = _super.call(this) || this;
  38153. _this.MAINUV1 = false;
  38154. _this.MAINUV2 = false;
  38155. _this.DIFFUSE = false;
  38156. _this.DIFFUSEDIRECTUV = 0;
  38157. _this.AMBIENT = false;
  38158. _this.AMBIENTDIRECTUV = 0;
  38159. _this.OPACITY = false;
  38160. _this.OPACITYDIRECTUV = 0;
  38161. _this.OPACITYRGB = false;
  38162. _this.REFLECTION = false;
  38163. _this.EMISSIVE = false;
  38164. _this.EMISSIVEDIRECTUV = 0;
  38165. _this.SPECULAR = false;
  38166. _this.SPECULARDIRECTUV = 0;
  38167. _this.BUMP = false;
  38168. _this.BUMPDIRECTUV = 0;
  38169. _this.PARALLAX = false;
  38170. _this.PARALLAXOCCLUSION = false;
  38171. _this.SPECULAROVERALPHA = false;
  38172. _this.CLIPPLANE = false;
  38173. _this.ALPHATEST = false;
  38174. _this.DEPTHPREPASS = false;
  38175. _this.ALPHAFROMDIFFUSE = false;
  38176. _this.POINTSIZE = false;
  38177. _this.FOG = false;
  38178. _this.SPECULARTERM = false;
  38179. _this.DIFFUSEFRESNEL = false;
  38180. _this.OPACITYFRESNEL = false;
  38181. _this.REFLECTIONFRESNEL = false;
  38182. _this.REFRACTIONFRESNEL = false;
  38183. _this.EMISSIVEFRESNEL = false;
  38184. _this.FRESNEL = false;
  38185. _this.NORMAL = false;
  38186. _this.UV1 = false;
  38187. _this.UV2 = false;
  38188. _this.VERTEXCOLOR = false;
  38189. _this.VERTEXALPHA = false;
  38190. _this.NUM_BONE_INFLUENCERS = 0;
  38191. _this.BonesPerMesh = 0;
  38192. _this.INSTANCES = false;
  38193. _this.GLOSSINESS = false;
  38194. _this.ROUGHNESS = false;
  38195. _this.EMISSIVEASILLUMINATION = false;
  38196. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38197. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38198. _this.LIGHTMAP = false;
  38199. _this.LIGHTMAPDIRECTUV = 0;
  38200. _this.USELIGHTMAPASSHADOWMAP = false;
  38201. _this.REFLECTIONMAP_3D = false;
  38202. _this.REFLECTIONMAP_SPHERICAL = false;
  38203. _this.REFLECTIONMAP_PLANAR = false;
  38204. _this.REFLECTIONMAP_CUBIC = false;
  38205. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38206. _this.REFLECTIONMAP_PROJECTION = false;
  38207. _this.REFLECTIONMAP_SKYBOX = false;
  38208. _this.REFLECTIONMAP_EXPLICIT = false;
  38209. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38210. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38211. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38212. _this.INVERTCUBICMAP = false;
  38213. _this.LOGARITHMICDEPTH = false;
  38214. _this.REFRACTION = false;
  38215. _this.REFRACTIONMAP_3D = false;
  38216. _this.REFLECTIONOVERALPHA = false;
  38217. _this.TWOSIDEDLIGHTING = false;
  38218. _this.SHADOWFLOAT = false;
  38219. _this.MORPHTARGETS = false;
  38220. _this.MORPHTARGETS_NORMAL = false;
  38221. _this.MORPHTARGETS_TANGENT = false;
  38222. _this.NUM_MORPH_INFLUENCERS = 0;
  38223. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38224. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38225. _this.IMAGEPROCESSING = false;
  38226. _this.VIGNETTE = false;
  38227. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38228. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38229. _this.TONEMAPPING = false;
  38230. _this.CONTRAST = false;
  38231. _this.COLORCURVES = false;
  38232. _this.COLORGRADING = false;
  38233. _this.COLORGRADING3D = false;
  38234. _this.SAMPLER3DGREENDEPTH = false;
  38235. _this.SAMPLER3DBGRMAP = false;
  38236. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38237. _this.EXPOSURE = false;
  38238. _this.rebuild();
  38239. return _this;
  38240. }
  38241. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38242. var modes = [
  38243. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38244. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38245. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38246. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38247. ];
  38248. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38249. var mode = modes_1[_i];
  38250. this[mode] = (mode === modeToEnable);
  38251. }
  38252. };
  38253. return StandardMaterialDefines;
  38254. }(BABYLON.MaterialDefines));
  38255. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38256. var StandardMaterial = /** @class */ (function (_super) {
  38257. __extends(StandardMaterial, _super);
  38258. function StandardMaterial(name, scene) {
  38259. var _this = _super.call(this, name, scene) || this;
  38260. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38261. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38262. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38263. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38264. _this.specularPower = 64;
  38265. _this._useAlphaFromDiffuseTexture = false;
  38266. _this._useEmissiveAsIllumination = false;
  38267. _this._linkEmissiveWithDiffuse = false;
  38268. _this._useSpecularOverAlpha = false;
  38269. _this._useReflectionOverAlpha = false;
  38270. _this._disableLighting = false;
  38271. _this._useParallax = false;
  38272. _this._useParallaxOcclusion = false;
  38273. _this.parallaxScaleBias = 0.05;
  38274. _this._roughness = 0;
  38275. _this.indexOfRefraction = 0.98;
  38276. _this.invertRefractionY = true;
  38277. _this._useLightmapAsShadowmap = false;
  38278. _this._useReflectionFresnelFromSpecular = false;
  38279. _this._useGlossinessFromSpecularMapAlpha = false;
  38280. _this._maxSimultaneousLights = 4;
  38281. /**
  38282. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38283. */
  38284. _this._invertNormalMapX = false;
  38285. /**
  38286. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38287. */
  38288. _this._invertNormalMapY = false;
  38289. /**
  38290. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38291. */
  38292. _this._twoSidedLighting = false;
  38293. _this._renderTargets = new BABYLON.SmartArray(16);
  38294. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38295. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38296. // Setup the default processing configuration to the scene.
  38297. _this._attachImageProcessingConfiguration(null);
  38298. _this.getRenderTargetTextures = function () {
  38299. _this._renderTargets.reset();
  38300. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38301. _this._renderTargets.push(_this._reflectionTexture);
  38302. }
  38303. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38304. _this._renderTargets.push(_this._refractionTexture);
  38305. }
  38306. return _this._renderTargets;
  38307. };
  38308. return _this;
  38309. }
  38310. ;
  38311. ;
  38312. ;
  38313. ;
  38314. ;
  38315. ;
  38316. ;
  38317. ;
  38318. ;
  38319. ;
  38320. ;
  38321. ;
  38322. ;
  38323. ;
  38324. ;
  38325. ;
  38326. ;
  38327. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38328. /**
  38329. * Gets the image processing configuration used either in this material.
  38330. */
  38331. get: function () {
  38332. return this._imageProcessingConfiguration;
  38333. },
  38334. /**
  38335. * Sets the Default image processing configuration used either in the this material.
  38336. *
  38337. * If sets to null, the scene one is in use.
  38338. */
  38339. set: function (value) {
  38340. this._attachImageProcessingConfiguration(value);
  38341. // Ensure the effect will be rebuilt.
  38342. this._markAllSubMeshesAsTexturesDirty();
  38343. },
  38344. enumerable: true,
  38345. configurable: true
  38346. });
  38347. /**
  38348. * Attaches a new image processing configuration to the Standard Material.
  38349. * @param configuration
  38350. */
  38351. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38352. var _this = this;
  38353. if (configuration === this._imageProcessingConfiguration) {
  38354. return;
  38355. }
  38356. // Detaches observer.
  38357. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38358. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38359. }
  38360. // Pick the scene configuration if needed.
  38361. if (!configuration) {
  38362. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38363. }
  38364. else {
  38365. this._imageProcessingConfiguration = configuration;
  38366. }
  38367. // Attaches observer.
  38368. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38369. _this._markAllSubMeshesAsImageProcessingDirty();
  38370. });
  38371. };
  38372. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38373. /**
  38374. * Gets wether the color curves effect is enabled.
  38375. */
  38376. get: function () {
  38377. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38378. },
  38379. /**
  38380. * Sets wether the color curves effect is enabled.
  38381. */
  38382. set: function (value) {
  38383. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38384. },
  38385. enumerable: true,
  38386. configurable: true
  38387. });
  38388. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38389. /**
  38390. * Gets wether the color grading effect is enabled.
  38391. */
  38392. get: function () {
  38393. return this.imageProcessingConfiguration.colorGradingEnabled;
  38394. },
  38395. /**
  38396. * Gets wether the color grading effect is enabled.
  38397. */
  38398. set: function (value) {
  38399. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38400. },
  38401. enumerable: true,
  38402. configurable: true
  38403. });
  38404. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38405. /**
  38406. * Gets wether tonemapping is enabled or not.
  38407. */
  38408. get: function () {
  38409. return this._imageProcessingConfiguration.toneMappingEnabled;
  38410. },
  38411. /**
  38412. * Sets wether tonemapping is enabled or not
  38413. */
  38414. set: function (value) {
  38415. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38416. },
  38417. enumerable: true,
  38418. configurable: true
  38419. });
  38420. ;
  38421. ;
  38422. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38423. /**
  38424. * The camera exposure used on this material.
  38425. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38426. * This corresponds to a photographic exposure.
  38427. */
  38428. get: function () {
  38429. return this._imageProcessingConfiguration.exposure;
  38430. },
  38431. /**
  38432. * The camera exposure used on this material.
  38433. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38434. * This corresponds to a photographic exposure.
  38435. */
  38436. set: function (value) {
  38437. this._imageProcessingConfiguration.exposure = value;
  38438. },
  38439. enumerable: true,
  38440. configurable: true
  38441. });
  38442. ;
  38443. ;
  38444. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38445. /**
  38446. * Gets The camera contrast used on this material.
  38447. */
  38448. get: function () {
  38449. return this._imageProcessingConfiguration.contrast;
  38450. },
  38451. /**
  38452. * Sets The camera contrast used on this material.
  38453. */
  38454. set: function (value) {
  38455. this._imageProcessingConfiguration.contrast = value;
  38456. },
  38457. enumerable: true,
  38458. configurable: true
  38459. });
  38460. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38461. /**
  38462. * Gets the Color Grading 2D Lookup Texture.
  38463. */
  38464. get: function () {
  38465. return this._imageProcessingConfiguration.colorGradingTexture;
  38466. },
  38467. /**
  38468. * Sets the Color Grading 2D Lookup Texture.
  38469. */
  38470. set: function (value) {
  38471. this._imageProcessingConfiguration.colorGradingTexture = value;
  38472. },
  38473. enumerable: true,
  38474. configurable: true
  38475. });
  38476. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38477. /**
  38478. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38479. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38480. * 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;
  38481. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38482. */
  38483. get: function () {
  38484. return this._imageProcessingConfiguration.colorCurves;
  38485. },
  38486. /**
  38487. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38488. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38489. * 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;
  38490. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38491. */
  38492. set: function (value) {
  38493. this._imageProcessingConfiguration.colorCurves = value;
  38494. },
  38495. enumerable: true,
  38496. configurable: true
  38497. });
  38498. StandardMaterial.prototype.getClassName = function () {
  38499. return "StandardMaterial";
  38500. };
  38501. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38502. get: function () {
  38503. return this._useLogarithmicDepth;
  38504. },
  38505. set: function (value) {
  38506. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38507. this._markAllSubMeshesAsMiscDirty();
  38508. },
  38509. enumerable: true,
  38510. configurable: true
  38511. });
  38512. StandardMaterial.prototype.needAlphaBlending = function () {
  38513. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38514. };
  38515. StandardMaterial.prototype.needAlphaTesting = function () {
  38516. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38517. };
  38518. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38519. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38520. };
  38521. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38522. return this._diffuseTexture;
  38523. };
  38524. /**
  38525. * Child classes can use it to update shaders
  38526. */
  38527. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38528. if (useInstances === void 0) { useInstances = false; }
  38529. if (subMesh.effect && this.isFrozen) {
  38530. if (this._wasPreviouslyReady && subMesh.effect) {
  38531. return true;
  38532. }
  38533. }
  38534. if (!subMesh._materialDefines) {
  38535. subMesh._materialDefines = new StandardMaterialDefines();
  38536. }
  38537. var scene = this.getScene();
  38538. var defines = subMesh._materialDefines;
  38539. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38540. if (defines._renderId === scene.getRenderId()) {
  38541. return true;
  38542. }
  38543. }
  38544. var engine = scene.getEngine();
  38545. // Lights
  38546. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38547. // Textures
  38548. if (defines._areTexturesDirty) {
  38549. defines._needUVs = false;
  38550. defines.MAINUV1 = false;
  38551. defines.MAINUV2 = false;
  38552. if (scene.texturesEnabled) {
  38553. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38554. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38555. return false;
  38556. }
  38557. else {
  38558. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38559. }
  38560. }
  38561. else {
  38562. defines.DIFFUSE = false;
  38563. }
  38564. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38565. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38566. return false;
  38567. }
  38568. else {
  38569. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38570. }
  38571. }
  38572. else {
  38573. defines.AMBIENT = false;
  38574. }
  38575. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38576. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38577. return false;
  38578. }
  38579. else {
  38580. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38581. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38582. }
  38583. }
  38584. else {
  38585. defines.OPACITY = false;
  38586. }
  38587. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38588. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38589. return false;
  38590. }
  38591. else {
  38592. defines._needNormals = true;
  38593. defines.REFLECTION = true;
  38594. defines.ROUGHNESS = (this._roughness > 0);
  38595. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38596. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38597. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38598. switch (this._reflectionTexture.coordinatesMode) {
  38599. case BABYLON.Texture.CUBIC_MODE:
  38600. case BABYLON.Texture.INVCUBIC_MODE:
  38601. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38602. break;
  38603. case BABYLON.Texture.EXPLICIT_MODE:
  38604. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38605. break;
  38606. case BABYLON.Texture.PLANAR_MODE:
  38607. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38608. break;
  38609. case BABYLON.Texture.PROJECTION_MODE:
  38610. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38611. break;
  38612. case BABYLON.Texture.SKYBOX_MODE:
  38613. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38614. break;
  38615. case BABYLON.Texture.SPHERICAL_MODE:
  38616. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38617. break;
  38618. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38619. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38620. break;
  38621. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38622. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38623. break;
  38624. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38625. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38626. break;
  38627. }
  38628. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38629. }
  38630. }
  38631. else {
  38632. defines.REFLECTION = false;
  38633. }
  38634. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38635. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38636. return false;
  38637. }
  38638. else {
  38639. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38640. }
  38641. }
  38642. else {
  38643. defines.EMISSIVE = false;
  38644. }
  38645. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38646. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38647. return false;
  38648. }
  38649. else {
  38650. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38651. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38652. }
  38653. }
  38654. else {
  38655. defines.LIGHTMAP = false;
  38656. }
  38657. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38658. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38659. return false;
  38660. }
  38661. else {
  38662. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38663. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38664. }
  38665. }
  38666. else {
  38667. defines.SPECULAR = false;
  38668. }
  38669. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38670. // Bump texure can not be not blocking.
  38671. if (!this._bumpTexture.isReady()) {
  38672. return false;
  38673. }
  38674. else {
  38675. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38676. defines.PARALLAX = this._useParallax;
  38677. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38678. }
  38679. }
  38680. else {
  38681. defines.BUMP = false;
  38682. }
  38683. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38684. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38685. return false;
  38686. }
  38687. else {
  38688. defines._needUVs = true;
  38689. defines.REFRACTION = true;
  38690. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38691. }
  38692. }
  38693. else {
  38694. defines.REFRACTION = false;
  38695. }
  38696. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38697. }
  38698. else {
  38699. defines.DIFFUSE = false;
  38700. defines.AMBIENT = false;
  38701. defines.OPACITY = false;
  38702. defines.REFLECTION = false;
  38703. defines.EMISSIVE = false;
  38704. defines.LIGHTMAP = false;
  38705. defines.BUMP = false;
  38706. defines.REFRACTION = false;
  38707. }
  38708. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38709. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38710. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38711. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38712. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38713. }
  38714. if (defines._areImageProcessingDirty) {
  38715. if (!this._imageProcessingConfiguration.isReady()) {
  38716. return false;
  38717. }
  38718. this._imageProcessingConfiguration.prepareDefines(defines);
  38719. }
  38720. if (defines._areFresnelDirty) {
  38721. if (StandardMaterial.FresnelEnabled) {
  38722. // Fresnel
  38723. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38724. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38725. this._reflectionFresnelParameters) {
  38726. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38727. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38728. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38729. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38730. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38731. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38732. defines._needNormals = true;
  38733. defines.FRESNEL = true;
  38734. }
  38735. }
  38736. else {
  38737. defines.FRESNEL = false;
  38738. }
  38739. }
  38740. // Misc.
  38741. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38742. // Attribs
  38743. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38744. // Values that need to be evaluated on every frame
  38745. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38746. // Get correct effect
  38747. if (defines.isDirty) {
  38748. defines.markAsProcessed();
  38749. scene.resetCachedMaterial();
  38750. // Fallbacks
  38751. var fallbacks = new BABYLON.EffectFallbacks();
  38752. if (defines.REFLECTION) {
  38753. fallbacks.addFallback(0, "REFLECTION");
  38754. }
  38755. if (defines.SPECULAR) {
  38756. fallbacks.addFallback(0, "SPECULAR");
  38757. }
  38758. if (defines.BUMP) {
  38759. fallbacks.addFallback(0, "BUMP");
  38760. }
  38761. if (defines.PARALLAX) {
  38762. fallbacks.addFallback(1, "PARALLAX");
  38763. }
  38764. if (defines.PARALLAXOCCLUSION) {
  38765. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38766. }
  38767. if (defines.SPECULAROVERALPHA) {
  38768. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38769. }
  38770. if (defines.FOG) {
  38771. fallbacks.addFallback(1, "FOG");
  38772. }
  38773. if (defines.POINTSIZE) {
  38774. fallbacks.addFallback(0, "POINTSIZE");
  38775. }
  38776. if (defines.LOGARITHMICDEPTH) {
  38777. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38778. }
  38779. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38780. if (defines.SPECULARTERM) {
  38781. fallbacks.addFallback(0, "SPECULARTERM");
  38782. }
  38783. if (defines.DIFFUSEFRESNEL) {
  38784. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38785. }
  38786. if (defines.OPACITYFRESNEL) {
  38787. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38788. }
  38789. if (defines.REFLECTIONFRESNEL) {
  38790. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38791. }
  38792. if (defines.EMISSIVEFRESNEL) {
  38793. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38794. }
  38795. if (defines.FRESNEL) {
  38796. fallbacks.addFallback(4, "FRESNEL");
  38797. }
  38798. //Attributes
  38799. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38800. if (defines.NORMAL) {
  38801. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38802. }
  38803. if (defines.UV1) {
  38804. attribs.push(BABYLON.VertexBuffer.UVKind);
  38805. }
  38806. if (defines.UV2) {
  38807. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38808. }
  38809. if (defines.VERTEXCOLOR) {
  38810. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38811. }
  38812. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38813. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38814. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38815. var shaderName = "default";
  38816. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38817. "vFogInfos", "vFogColor", "pointSize",
  38818. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38819. "mBones",
  38820. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38821. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38822. "vReflectionPosition", "vReflectionSize",
  38823. "logarithmicDepthConstant", "vTangentSpaceParams"
  38824. ];
  38825. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38826. var uniformBuffers = ["Material", "Scene"];
  38827. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38828. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38829. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38830. uniformsNames: uniforms,
  38831. uniformBuffersNames: uniformBuffers,
  38832. samplers: samplers,
  38833. defines: defines,
  38834. maxSimultaneousLights: this._maxSimultaneousLights
  38835. });
  38836. if (this.customShaderNameResolve) {
  38837. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38838. }
  38839. var join = defines.toString();
  38840. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38841. attributes: attribs,
  38842. uniformsNames: uniforms,
  38843. uniformBuffersNames: uniformBuffers,
  38844. samplers: samplers,
  38845. defines: join,
  38846. fallbacks: fallbacks,
  38847. onCompiled: this.onCompiled,
  38848. onError: this.onError,
  38849. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38850. }, engine), defines);
  38851. this.buildUniformLayout();
  38852. }
  38853. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38854. return false;
  38855. }
  38856. defines._renderId = scene.getRenderId();
  38857. this._wasPreviouslyReady = true;
  38858. return true;
  38859. };
  38860. StandardMaterial.prototype.buildUniformLayout = function () {
  38861. // Order is important !
  38862. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38863. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38864. this._uniformBuffer.addUniform("opacityParts", 4);
  38865. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38866. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38867. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38868. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38869. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38870. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38871. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38872. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38873. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38874. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38875. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  38876. this._uniformBuffer.addUniform("vReflectionSize", 3);
  38877. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38878. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38879. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38880. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38881. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38882. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38883. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38884. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38885. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38886. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38887. this._uniformBuffer.addUniform("specularMatrix", 16);
  38888. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38889. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38890. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38891. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38892. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38893. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38894. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38895. this._uniformBuffer.addUniform("pointSize", 1);
  38896. this._uniformBuffer.create();
  38897. };
  38898. StandardMaterial.prototype.unbind = function () {
  38899. if (this._activeEffect) {
  38900. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38901. this._activeEffect.setTexture("reflection2DSampler", null);
  38902. }
  38903. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38904. this._activeEffect.setTexture("refraction2DSampler", null);
  38905. }
  38906. }
  38907. _super.prototype.unbind.call(this);
  38908. };
  38909. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38910. var scene = this.getScene();
  38911. var defines = subMesh._materialDefines;
  38912. if (!defines) {
  38913. return;
  38914. }
  38915. var effect = subMesh.effect;
  38916. if (!effect) {
  38917. return;
  38918. }
  38919. this._activeEffect = effect;
  38920. // Matrices
  38921. this.bindOnlyWorldMatrix(world);
  38922. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38923. // Bones
  38924. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38925. if (mustRebind) {
  38926. this._uniformBuffer.bindToEffect(effect, "Material");
  38927. this.bindViewProjection(effect);
  38928. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38929. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38930. // Fresnel
  38931. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38932. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38933. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38934. }
  38935. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38936. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38937. }
  38938. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38939. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38940. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38941. }
  38942. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38943. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38944. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38945. }
  38946. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38947. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38948. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38949. }
  38950. }
  38951. // Textures
  38952. if (scene.texturesEnabled) {
  38953. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38954. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38955. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38956. }
  38957. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38958. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38959. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38960. }
  38961. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38962. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38963. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38964. }
  38965. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38966. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38967. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38968. if (this._reflectionTexture.boundingBoxSize) {
  38969. var cubeTexture = this._reflectionTexture;
  38970. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  38971. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  38972. }
  38973. }
  38974. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38975. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38976. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38977. }
  38978. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38979. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38980. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38981. }
  38982. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38983. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38984. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38985. }
  38986. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38987. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38988. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38989. if (scene._mirroredCameraPosition) {
  38990. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38991. }
  38992. else {
  38993. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38994. }
  38995. }
  38996. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38997. var depth = 1.0;
  38998. if (!this._refractionTexture.isCube) {
  38999. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39000. if (this._refractionTexture.depth) {
  39001. depth = this._refractionTexture.depth;
  39002. }
  39003. }
  39004. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39005. }
  39006. }
  39007. // Point size
  39008. if (this.pointsCloud) {
  39009. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39010. }
  39011. if (defines.SPECULARTERM) {
  39012. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39013. }
  39014. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39015. // Diffuse
  39016. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39017. }
  39018. // Textures
  39019. if (scene.texturesEnabled) {
  39020. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39021. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39022. }
  39023. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39024. effect.setTexture("ambientSampler", this._ambientTexture);
  39025. }
  39026. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39027. effect.setTexture("opacitySampler", this._opacityTexture);
  39028. }
  39029. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39030. if (this._reflectionTexture.isCube) {
  39031. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39032. }
  39033. else {
  39034. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39035. }
  39036. }
  39037. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39038. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39039. }
  39040. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39041. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39042. }
  39043. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39044. effect.setTexture("specularSampler", this._specularTexture);
  39045. }
  39046. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39047. effect.setTexture("bumpSampler", this._bumpTexture);
  39048. }
  39049. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39050. var depth = 1.0;
  39051. if (this._refractionTexture.isCube) {
  39052. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39053. }
  39054. else {
  39055. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39056. }
  39057. }
  39058. }
  39059. // Clip plane
  39060. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39061. // Colors
  39062. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39063. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39064. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39065. }
  39066. if (mustRebind || !this.isFrozen) {
  39067. // Lights
  39068. if (scene.lightsEnabled && !this._disableLighting) {
  39069. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39070. }
  39071. // View
  39072. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39073. this.bindView(effect);
  39074. }
  39075. // Fog
  39076. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39077. // Morph targets
  39078. if (defines.NUM_MORPH_INFLUENCERS) {
  39079. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39080. }
  39081. // Log. depth
  39082. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39083. // image processing
  39084. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39085. this._imageProcessingConfiguration.bind(this._activeEffect);
  39086. }
  39087. }
  39088. this._uniformBuffer.update();
  39089. this._afterBind(mesh, this._activeEffect);
  39090. };
  39091. StandardMaterial.prototype.getAnimatables = function () {
  39092. var results = [];
  39093. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39094. results.push(this._diffuseTexture);
  39095. }
  39096. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39097. results.push(this._ambientTexture);
  39098. }
  39099. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39100. results.push(this._opacityTexture);
  39101. }
  39102. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39103. results.push(this._reflectionTexture);
  39104. }
  39105. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39106. results.push(this._emissiveTexture);
  39107. }
  39108. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39109. results.push(this._specularTexture);
  39110. }
  39111. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39112. results.push(this._bumpTexture);
  39113. }
  39114. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39115. results.push(this._lightmapTexture);
  39116. }
  39117. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39118. results.push(this._refractionTexture);
  39119. }
  39120. return results;
  39121. };
  39122. StandardMaterial.prototype.getActiveTextures = function () {
  39123. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39124. if (this._diffuseTexture) {
  39125. activeTextures.push(this._diffuseTexture);
  39126. }
  39127. if (this._ambientTexture) {
  39128. activeTextures.push(this._ambientTexture);
  39129. }
  39130. if (this._opacityTexture) {
  39131. activeTextures.push(this._opacityTexture);
  39132. }
  39133. if (this._reflectionTexture) {
  39134. activeTextures.push(this._reflectionTexture);
  39135. }
  39136. if (this._emissiveTexture) {
  39137. activeTextures.push(this._emissiveTexture);
  39138. }
  39139. if (this._specularTexture) {
  39140. activeTextures.push(this._specularTexture);
  39141. }
  39142. if (this._bumpTexture) {
  39143. activeTextures.push(this._bumpTexture);
  39144. }
  39145. if (this._lightmapTexture) {
  39146. activeTextures.push(this._lightmapTexture);
  39147. }
  39148. if (this._refractionTexture) {
  39149. activeTextures.push(this._refractionTexture);
  39150. }
  39151. return activeTextures;
  39152. };
  39153. StandardMaterial.prototype.hasTexture = function (texture) {
  39154. if (_super.prototype.hasTexture.call(this, texture)) {
  39155. return true;
  39156. }
  39157. if (this._diffuseTexture === texture) {
  39158. return true;
  39159. }
  39160. if (this._ambientTexture === texture) {
  39161. return true;
  39162. }
  39163. if (this._opacityTexture === texture) {
  39164. return true;
  39165. }
  39166. if (this._reflectionTexture === texture) {
  39167. return true;
  39168. }
  39169. if (this._emissiveTexture === texture) {
  39170. return true;
  39171. }
  39172. if (this._specularTexture === texture) {
  39173. return true;
  39174. }
  39175. if (this._bumpTexture === texture) {
  39176. return true;
  39177. }
  39178. if (this._lightmapTexture === texture) {
  39179. return true;
  39180. }
  39181. if (this._refractionTexture === texture) {
  39182. return true;
  39183. }
  39184. return false;
  39185. };
  39186. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39187. if (forceDisposeTextures) {
  39188. if (this._diffuseTexture) {
  39189. this._diffuseTexture.dispose();
  39190. }
  39191. if (this._ambientTexture) {
  39192. this._ambientTexture.dispose();
  39193. }
  39194. if (this._opacityTexture) {
  39195. this._opacityTexture.dispose();
  39196. }
  39197. if (this._reflectionTexture) {
  39198. this._reflectionTexture.dispose();
  39199. }
  39200. if (this._emissiveTexture) {
  39201. this._emissiveTexture.dispose();
  39202. }
  39203. if (this._specularTexture) {
  39204. this._specularTexture.dispose();
  39205. }
  39206. if (this._bumpTexture) {
  39207. this._bumpTexture.dispose();
  39208. }
  39209. if (this._lightmapTexture) {
  39210. this._lightmapTexture.dispose();
  39211. }
  39212. if (this._refractionTexture) {
  39213. this._refractionTexture.dispose();
  39214. }
  39215. }
  39216. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39217. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39218. }
  39219. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39220. };
  39221. StandardMaterial.prototype.clone = function (name) {
  39222. var _this = this;
  39223. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39224. result.name = name;
  39225. result.id = name;
  39226. return result;
  39227. };
  39228. StandardMaterial.prototype.serialize = function () {
  39229. return BABYLON.SerializationHelper.Serialize(this);
  39230. };
  39231. // Statics
  39232. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39233. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39234. };
  39235. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39236. get: function () {
  39237. return StandardMaterial._DiffuseTextureEnabled;
  39238. },
  39239. set: function (value) {
  39240. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39241. return;
  39242. }
  39243. StandardMaterial._DiffuseTextureEnabled = value;
  39244. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39245. },
  39246. enumerable: true,
  39247. configurable: true
  39248. });
  39249. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39250. get: function () {
  39251. return StandardMaterial._AmbientTextureEnabled;
  39252. },
  39253. set: function (value) {
  39254. if (StandardMaterial._AmbientTextureEnabled === value) {
  39255. return;
  39256. }
  39257. StandardMaterial._AmbientTextureEnabled = value;
  39258. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39259. },
  39260. enumerable: true,
  39261. configurable: true
  39262. });
  39263. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39264. get: function () {
  39265. return StandardMaterial._OpacityTextureEnabled;
  39266. },
  39267. set: function (value) {
  39268. if (StandardMaterial._OpacityTextureEnabled === value) {
  39269. return;
  39270. }
  39271. StandardMaterial._OpacityTextureEnabled = value;
  39272. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39273. },
  39274. enumerable: true,
  39275. configurable: true
  39276. });
  39277. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39278. get: function () {
  39279. return StandardMaterial._ReflectionTextureEnabled;
  39280. },
  39281. set: function (value) {
  39282. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39283. return;
  39284. }
  39285. StandardMaterial._ReflectionTextureEnabled = value;
  39286. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39287. },
  39288. enumerable: true,
  39289. configurable: true
  39290. });
  39291. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39292. get: function () {
  39293. return StandardMaterial._EmissiveTextureEnabled;
  39294. },
  39295. set: function (value) {
  39296. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39297. return;
  39298. }
  39299. StandardMaterial._EmissiveTextureEnabled = value;
  39300. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39301. },
  39302. enumerable: true,
  39303. configurable: true
  39304. });
  39305. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39306. get: function () {
  39307. return StandardMaterial._SpecularTextureEnabled;
  39308. },
  39309. set: function (value) {
  39310. if (StandardMaterial._SpecularTextureEnabled === value) {
  39311. return;
  39312. }
  39313. StandardMaterial._SpecularTextureEnabled = value;
  39314. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39315. },
  39316. enumerable: true,
  39317. configurable: true
  39318. });
  39319. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39320. get: function () {
  39321. return StandardMaterial._BumpTextureEnabled;
  39322. },
  39323. set: function (value) {
  39324. if (StandardMaterial._BumpTextureEnabled === value) {
  39325. return;
  39326. }
  39327. StandardMaterial._BumpTextureEnabled = value;
  39328. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39329. },
  39330. enumerable: true,
  39331. configurable: true
  39332. });
  39333. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39334. get: function () {
  39335. return StandardMaterial._LightmapTextureEnabled;
  39336. },
  39337. set: function (value) {
  39338. if (StandardMaterial._LightmapTextureEnabled === value) {
  39339. return;
  39340. }
  39341. StandardMaterial._LightmapTextureEnabled = value;
  39342. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39343. },
  39344. enumerable: true,
  39345. configurable: true
  39346. });
  39347. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39348. get: function () {
  39349. return StandardMaterial._RefractionTextureEnabled;
  39350. },
  39351. set: function (value) {
  39352. if (StandardMaterial._RefractionTextureEnabled === value) {
  39353. return;
  39354. }
  39355. StandardMaterial._RefractionTextureEnabled = value;
  39356. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39357. },
  39358. enumerable: true,
  39359. configurable: true
  39360. });
  39361. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39362. get: function () {
  39363. return StandardMaterial._ColorGradingTextureEnabled;
  39364. },
  39365. set: function (value) {
  39366. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39367. return;
  39368. }
  39369. StandardMaterial._ColorGradingTextureEnabled = value;
  39370. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39371. },
  39372. enumerable: true,
  39373. configurable: true
  39374. });
  39375. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39376. get: function () {
  39377. return StandardMaterial._FresnelEnabled;
  39378. },
  39379. set: function (value) {
  39380. if (StandardMaterial._FresnelEnabled === value) {
  39381. return;
  39382. }
  39383. StandardMaterial._FresnelEnabled = value;
  39384. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39385. },
  39386. enumerable: true,
  39387. configurable: true
  39388. });
  39389. // Flags used to enable or disable a type of texture for all Standard Materials
  39390. StandardMaterial._DiffuseTextureEnabled = true;
  39391. StandardMaterial._AmbientTextureEnabled = true;
  39392. StandardMaterial._OpacityTextureEnabled = true;
  39393. StandardMaterial._ReflectionTextureEnabled = true;
  39394. StandardMaterial._EmissiveTextureEnabled = true;
  39395. StandardMaterial._SpecularTextureEnabled = true;
  39396. StandardMaterial._BumpTextureEnabled = true;
  39397. StandardMaterial._LightmapTextureEnabled = true;
  39398. StandardMaterial._RefractionTextureEnabled = true;
  39399. StandardMaterial._ColorGradingTextureEnabled = true;
  39400. StandardMaterial._FresnelEnabled = true;
  39401. __decorate([
  39402. BABYLON.serializeAsTexture("diffuseTexture")
  39403. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39404. __decorate([
  39405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39406. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39407. __decorate([
  39408. BABYLON.serializeAsTexture("ambientTexture")
  39409. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39410. __decorate([
  39411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39412. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39413. __decorate([
  39414. BABYLON.serializeAsTexture("opacityTexture")
  39415. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39416. __decorate([
  39417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39418. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39419. __decorate([
  39420. BABYLON.serializeAsTexture("reflectionTexture")
  39421. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39422. __decorate([
  39423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39424. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39425. __decorate([
  39426. BABYLON.serializeAsTexture("emissiveTexture")
  39427. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39428. __decorate([
  39429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39430. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39431. __decorate([
  39432. BABYLON.serializeAsTexture("specularTexture")
  39433. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39434. __decorate([
  39435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39436. ], StandardMaterial.prototype, "specularTexture", void 0);
  39437. __decorate([
  39438. BABYLON.serializeAsTexture("bumpTexture")
  39439. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39440. __decorate([
  39441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39442. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39443. __decorate([
  39444. BABYLON.serializeAsTexture("lightmapTexture")
  39445. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39446. __decorate([
  39447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39448. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39449. __decorate([
  39450. BABYLON.serializeAsTexture("refractionTexture")
  39451. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39452. __decorate([
  39453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39454. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39455. __decorate([
  39456. BABYLON.serializeAsColor3("ambient")
  39457. ], StandardMaterial.prototype, "ambientColor", void 0);
  39458. __decorate([
  39459. BABYLON.serializeAsColor3("diffuse")
  39460. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39461. __decorate([
  39462. BABYLON.serializeAsColor3("specular")
  39463. ], StandardMaterial.prototype, "specularColor", void 0);
  39464. __decorate([
  39465. BABYLON.serializeAsColor3("emissive")
  39466. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39467. __decorate([
  39468. BABYLON.serialize()
  39469. ], StandardMaterial.prototype, "specularPower", void 0);
  39470. __decorate([
  39471. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39472. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39473. __decorate([
  39474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39475. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39476. __decorate([
  39477. BABYLON.serialize("useEmissiveAsIllumination")
  39478. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39479. __decorate([
  39480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39481. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39482. __decorate([
  39483. BABYLON.serialize("linkEmissiveWithDiffuse")
  39484. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39485. __decorate([
  39486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39487. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39488. __decorate([
  39489. BABYLON.serialize("useSpecularOverAlpha")
  39490. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39491. __decorate([
  39492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39493. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39494. __decorate([
  39495. BABYLON.serialize("useReflectionOverAlpha")
  39496. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39497. __decorate([
  39498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39499. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39500. __decorate([
  39501. BABYLON.serialize("disableLighting")
  39502. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39503. __decorate([
  39504. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39505. ], StandardMaterial.prototype, "disableLighting", void 0);
  39506. __decorate([
  39507. BABYLON.serialize("useParallax")
  39508. ], StandardMaterial.prototype, "_useParallax", void 0);
  39509. __decorate([
  39510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39511. ], StandardMaterial.prototype, "useParallax", void 0);
  39512. __decorate([
  39513. BABYLON.serialize("useParallaxOcclusion")
  39514. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39515. __decorate([
  39516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39517. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39518. __decorate([
  39519. BABYLON.serialize()
  39520. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39521. __decorate([
  39522. BABYLON.serialize("roughness")
  39523. ], StandardMaterial.prototype, "_roughness", void 0);
  39524. __decorate([
  39525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39526. ], StandardMaterial.prototype, "roughness", void 0);
  39527. __decorate([
  39528. BABYLON.serialize()
  39529. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39530. __decorate([
  39531. BABYLON.serialize()
  39532. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39533. __decorate([
  39534. BABYLON.serialize("useLightmapAsShadowmap")
  39535. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39536. __decorate([
  39537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39538. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39539. __decorate([
  39540. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39541. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39542. __decorate([
  39543. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39544. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39545. __decorate([
  39546. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39547. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39548. __decorate([
  39549. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39550. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39551. __decorate([
  39552. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39553. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39554. __decorate([
  39555. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39556. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39557. __decorate([
  39558. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39559. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39560. __decorate([
  39561. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39562. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39563. __decorate([
  39564. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39565. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39566. __decorate([
  39567. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39568. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39569. __decorate([
  39570. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39571. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39572. __decorate([
  39573. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39574. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39575. __decorate([
  39576. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39577. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39578. __decorate([
  39579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39580. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39581. __decorate([
  39582. BABYLON.serialize("maxSimultaneousLights")
  39583. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39584. __decorate([
  39585. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39586. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39587. __decorate([
  39588. BABYLON.serialize("invertNormalMapX")
  39589. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39590. __decorate([
  39591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39592. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39593. __decorate([
  39594. BABYLON.serialize("invertNormalMapY")
  39595. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39596. __decorate([
  39597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39598. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39599. __decorate([
  39600. BABYLON.serialize("twoSidedLighting")
  39601. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39602. __decorate([
  39603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39604. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39605. __decorate([
  39606. BABYLON.serialize()
  39607. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39608. return StandardMaterial;
  39609. }(BABYLON.PushMaterial));
  39610. BABYLON.StandardMaterial = StandardMaterial;
  39611. })(BABYLON || (BABYLON = {}));
  39612. //# sourceMappingURL=babylon.standardMaterial.js.map
  39613. var BABYLON;
  39614. (function (BABYLON) {
  39615. /**
  39616. * Manages the defines for the PBR Material.
  39617. */
  39618. var PBRMaterialDefines = /** @class */ (function (_super) {
  39619. __extends(PBRMaterialDefines, _super);
  39620. /**
  39621. * Initializes the PBR Material defines.
  39622. */
  39623. function PBRMaterialDefines() {
  39624. var _this = _super.call(this) || this;
  39625. _this.PBR = true;
  39626. _this.MAINUV1 = false;
  39627. _this.MAINUV2 = false;
  39628. _this.UV1 = false;
  39629. _this.UV2 = false;
  39630. _this.ALBEDO = false;
  39631. _this.ALBEDODIRECTUV = 0;
  39632. _this.VERTEXCOLOR = false;
  39633. _this.AMBIENT = false;
  39634. _this.AMBIENTDIRECTUV = 0;
  39635. _this.AMBIENTINGRAYSCALE = false;
  39636. _this.OPACITY = false;
  39637. _this.VERTEXALPHA = false;
  39638. _this.OPACITYDIRECTUV = 0;
  39639. _this.OPACITYRGB = false;
  39640. _this.ALPHATEST = false;
  39641. _this.DEPTHPREPASS = false;
  39642. _this.ALPHABLEND = false;
  39643. _this.ALPHAFROMALBEDO = false;
  39644. _this.ALPHATESTVALUE = 0.5;
  39645. _this.SPECULAROVERALPHA = false;
  39646. _this.RADIANCEOVERALPHA = false;
  39647. _this.ALPHAFRESNEL = false;
  39648. _this.LINEARALPHAFRESNEL = false;
  39649. _this.PREMULTIPLYALPHA = false;
  39650. _this.EMISSIVE = false;
  39651. _this.EMISSIVEDIRECTUV = 0;
  39652. _this.REFLECTIVITY = false;
  39653. _this.REFLECTIVITYDIRECTUV = 0;
  39654. _this.SPECULARTERM = false;
  39655. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39656. _this.MICROSURFACEAUTOMATIC = false;
  39657. _this.LODBASEDMICROSFURACE = false;
  39658. _this.MICROSURFACEMAP = false;
  39659. _this.MICROSURFACEMAPDIRECTUV = 0;
  39660. _this.METALLICWORKFLOW = false;
  39661. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39662. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39663. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39664. _this.AOSTOREINMETALMAPRED = false;
  39665. _this.ENVIRONMENTBRDF = false;
  39666. _this.NORMAL = false;
  39667. _this.TANGENT = false;
  39668. _this.BUMP = false;
  39669. _this.BUMPDIRECTUV = 0;
  39670. _this.PARALLAX = false;
  39671. _this.PARALLAXOCCLUSION = false;
  39672. _this.NORMALXYSCALE = true;
  39673. _this.LIGHTMAP = false;
  39674. _this.LIGHTMAPDIRECTUV = 0;
  39675. _this.USELIGHTMAPASSHADOWMAP = false;
  39676. _this.REFLECTION = false;
  39677. _this.REFLECTIONMAP_3D = false;
  39678. _this.REFLECTIONMAP_SPHERICAL = false;
  39679. _this.REFLECTIONMAP_PLANAR = false;
  39680. _this.REFLECTIONMAP_CUBIC = false;
  39681. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39682. _this.REFLECTIONMAP_PROJECTION = false;
  39683. _this.REFLECTIONMAP_SKYBOX = false;
  39684. _this.REFLECTIONMAP_EXPLICIT = false;
  39685. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39686. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39687. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39688. _this.INVERTCUBICMAP = false;
  39689. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39690. _this.USESPHERICALINVERTEX = false;
  39691. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39692. _this.LODINREFLECTIONALPHA = false;
  39693. _this.GAMMAREFLECTION = false;
  39694. _this.RADIANCEOCCLUSION = false;
  39695. _this.HORIZONOCCLUSION = false;
  39696. _this.REFRACTION = false;
  39697. _this.REFRACTIONMAP_3D = false;
  39698. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39699. _this.LODINREFRACTIONALPHA = false;
  39700. _this.GAMMAREFRACTION = false;
  39701. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39702. _this.INSTANCES = false;
  39703. _this.NUM_BONE_INFLUENCERS = 0;
  39704. _this.BonesPerMesh = 0;
  39705. _this.NONUNIFORMSCALING = false;
  39706. _this.MORPHTARGETS = false;
  39707. _this.MORPHTARGETS_NORMAL = false;
  39708. _this.MORPHTARGETS_TANGENT = false;
  39709. _this.NUM_MORPH_INFLUENCERS = 0;
  39710. _this.IMAGEPROCESSING = false;
  39711. _this.VIGNETTE = false;
  39712. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39713. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39714. _this.TONEMAPPING = false;
  39715. _this.CONTRAST = false;
  39716. _this.COLORCURVES = false;
  39717. _this.COLORGRADING = false;
  39718. _this.COLORGRADING3D = false;
  39719. _this.SAMPLER3DGREENDEPTH = false;
  39720. _this.SAMPLER3DBGRMAP = false;
  39721. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39722. _this.EXPOSURE = false;
  39723. _this.USEPHYSICALLIGHTFALLOFF = false;
  39724. _this.TWOSIDEDLIGHTING = false;
  39725. _this.SHADOWFLOAT = false;
  39726. _this.CLIPPLANE = false;
  39727. _this.POINTSIZE = false;
  39728. _this.FOG = false;
  39729. _this.LOGARITHMICDEPTH = false;
  39730. _this.FORCENORMALFORWARD = false;
  39731. _this.rebuild();
  39732. return _this;
  39733. }
  39734. /**
  39735. * Resets the PBR Material defines.
  39736. */
  39737. PBRMaterialDefines.prototype.reset = function () {
  39738. _super.prototype.reset.call(this);
  39739. this.ALPHATESTVALUE = 0.5;
  39740. this.PBR = true;
  39741. };
  39742. return PBRMaterialDefines;
  39743. }(BABYLON.MaterialDefines));
  39744. /**
  39745. * The Physically based material base class of BJS.
  39746. *
  39747. * This offers the main features of a standard PBR material.
  39748. * For more information, please refer to the documentation :
  39749. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39750. */
  39751. var PBRBaseMaterial = /** @class */ (function (_super) {
  39752. __extends(PBRBaseMaterial, _super);
  39753. /**
  39754. * Instantiates a new PBRMaterial instance.
  39755. *
  39756. * @param name The material name
  39757. * @param scene The scene the material will be use in.
  39758. */
  39759. function PBRBaseMaterial(name, scene) {
  39760. var _this = _super.call(this, name, scene) || this;
  39761. /**
  39762. * Intensity of the direct lights e.g. the four lights available in your scene.
  39763. * This impacts both the direct diffuse and specular highlights.
  39764. */
  39765. _this._directIntensity = 1.0;
  39766. /**
  39767. * Intensity of the emissive part of the material.
  39768. * This helps controlling the emissive effect without modifying the emissive color.
  39769. */
  39770. _this._emissiveIntensity = 1.0;
  39771. /**
  39772. * Intensity of the environment e.g. how much the environment will light the object
  39773. * either through harmonics for rough material or through the refelction for shiny ones.
  39774. */
  39775. _this._environmentIntensity = 1.0;
  39776. /**
  39777. * This is a special control allowing the reduction of the specular highlights coming from the
  39778. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39779. */
  39780. _this._specularIntensity = 1.0;
  39781. /**
  39782. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39783. */
  39784. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39785. /**
  39786. * Debug Control allowing disabling the bump map on this material.
  39787. */
  39788. _this._disableBumpMap = false;
  39789. /**
  39790. * AKA Occlusion Texture Intensity in other nomenclature.
  39791. */
  39792. _this._ambientTextureStrength = 1.0;
  39793. /**
  39794. * The color of a material in ambient lighting.
  39795. */
  39796. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39797. /**
  39798. * AKA Diffuse Color in other nomenclature.
  39799. */
  39800. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39801. /**
  39802. * AKA Specular Color in other nomenclature.
  39803. */
  39804. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39805. /**
  39806. * The color applied when light is reflected from a material.
  39807. */
  39808. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39809. /**
  39810. * The color applied when light is emitted from a material.
  39811. */
  39812. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39813. /**
  39814. * AKA Glossiness in other nomenclature.
  39815. */
  39816. _this._microSurface = 0.9;
  39817. /**
  39818. * source material index of refraction (IOR)' / 'destination material IOR.
  39819. */
  39820. _this._indexOfRefraction = 0.66;
  39821. /**
  39822. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39823. */
  39824. _this._invertRefractionY = false;
  39825. /**
  39826. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39827. * Materials half opaque for instance using refraction could benefit from this control.
  39828. */
  39829. _this._linkRefractionWithTransparency = false;
  39830. /**
  39831. * Specifies that the material will use the light map as a show map.
  39832. */
  39833. _this._useLightmapAsShadowmap = false;
  39834. /**
  39835. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39836. * makes the reflect vector face the model (under horizon).
  39837. */
  39838. _this._useHorizonOcclusion = true;
  39839. /**
  39840. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39841. * too much the area relying on ambient texture to define their ambient occlusion.
  39842. */
  39843. _this._useRadianceOcclusion = true;
  39844. /**
  39845. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39846. */
  39847. _this._useAlphaFromAlbedoTexture = false;
  39848. /**
  39849. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39850. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39851. */
  39852. _this._useSpecularOverAlpha = true;
  39853. /**
  39854. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39855. */
  39856. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39857. /**
  39858. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39859. */
  39860. _this._useRoughnessFromMetallicTextureAlpha = true;
  39861. /**
  39862. * Specifies if the metallic texture contains the roughness information in its green channel.
  39863. */
  39864. _this._useRoughnessFromMetallicTextureGreen = false;
  39865. /**
  39866. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39867. */
  39868. _this._useMetallnessFromMetallicTextureBlue = false;
  39869. /**
  39870. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39871. */
  39872. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39873. /**
  39874. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39875. */
  39876. _this._useAmbientInGrayScale = false;
  39877. /**
  39878. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39879. * The material will try to infer what glossiness each pixel should be.
  39880. */
  39881. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39882. /**
  39883. * BJS is using an harcoded light falloff based on a manually sets up range.
  39884. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39885. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39886. */
  39887. _this._usePhysicalLightFalloff = true;
  39888. /**
  39889. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39890. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39891. */
  39892. _this._useRadianceOverAlpha = true;
  39893. /**
  39894. * Allows using the bump map in parallax mode.
  39895. */
  39896. _this._useParallax = false;
  39897. /**
  39898. * Allows using the bump map in parallax occlusion mode.
  39899. */
  39900. _this._useParallaxOcclusion = false;
  39901. /**
  39902. * Controls the scale bias of the parallax mode.
  39903. */
  39904. _this._parallaxScaleBias = 0.05;
  39905. /**
  39906. * If sets to true, disables all the lights affecting the material.
  39907. */
  39908. _this._disableLighting = false;
  39909. /**
  39910. * Number of Simultaneous lights allowed on the material.
  39911. */
  39912. _this._maxSimultaneousLights = 4;
  39913. /**
  39914. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39915. */
  39916. _this._invertNormalMapX = false;
  39917. /**
  39918. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39919. */
  39920. _this._invertNormalMapY = false;
  39921. /**
  39922. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39923. */
  39924. _this._twoSidedLighting = false;
  39925. /**
  39926. * Defines the alpha limits in alpha test mode.
  39927. */
  39928. _this._alphaCutOff = 0.4;
  39929. /**
  39930. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39931. */
  39932. _this._forceAlphaTest = false;
  39933. /**
  39934. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39935. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39936. */
  39937. _this._useAlphaFresnel = false;
  39938. /**
  39939. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39940. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39941. */
  39942. _this._useLinearAlphaFresnel = false;
  39943. /**
  39944. * The transparency mode of the material.
  39945. */
  39946. _this._transparencyMode = null;
  39947. /**
  39948. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39949. * from cos thetav and roughness:
  39950. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39951. */
  39952. _this._environmentBRDFTexture = null;
  39953. /**
  39954. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39955. */
  39956. _this._forceIrradianceInFragment = false;
  39957. /**
  39958. * Force normal to face away from face.
  39959. */
  39960. _this._forceNormalForward = false;
  39961. /**
  39962. * Force metallic workflow.
  39963. */
  39964. _this._forceMetallicWorkflow = false;
  39965. /**
  39966. * Stores the available render targets.
  39967. */
  39968. _this._renderTargets = new BABYLON.SmartArray(16);
  39969. /**
  39970. * Sets the global ambient color for the material used in lighting calculations.
  39971. */
  39972. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39973. // Setup the default processing configuration to the scene.
  39974. _this._attachImageProcessingConfiguration(null);
  39975. _this.getRenderTargetTextures = function () {
  39976. _this._renderTargets.reset();
  39977. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39978. _this._renderTargets.push(_this._reflectionTexture);
  39979. }
  39980. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39981. _this._renderTargets.push(_this._refractionTexture);
  39982. }
  39983. return _this._renderTargets;
  39984. };
  39985. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39986. return _this;
  39987. }
  39988. /**
  39989. * Attaches a new image processing configuration to the PBR Material.
  39990. * @param configuration
  39991. */
  39992. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39993. var _this = this;
  39994. if (configuration === this._imageProcessingConfiguration) {
  39995. return;
  39996. }
  39997. // Detaches observer.
  39998. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39999. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40000. }
  40001. // Pick the scene configuration if needed.
  40002. if (!configuration) {
  40003. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40004. }
  40005. else {
  40006. this._imageProcessingConfiguration = configuration;
  40007. }
  40008. // Attaches observer.
  40009. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40010. _this._markAllSubMeshesAsImageProcessingDirty();
  40011. });
  40012. };
  40013. /**
  40014. * Gets the name of the material class.
  40015. */
  40016. PBRBaseMaterial.prototype.getClassName = function () {
  40017. return "PBRBaseMaterial";
  40018. };
  40019. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40020. /**
  40021. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40022. */
  40023. get: function () {
  40024. return this._useLogarithmicDepth;
  40025. },
  40026. /**
  40027. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40028. */
  40029. set: function (value) {
  40030. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40031. },
  40032. enumerable: true,
  40033. configurable: true
  40034. });
  40035. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40036. /**
  40037. * Gets the current transparency mode.
  40038. */
  40039. get: function () {
  40040. return this._transparencyMode;
  40041. },
  40042. /**
  40043. * Sets the transparency mode of the material.
  40044. */
  40045. set: function (value) {
  40046. if (this._transparencyMode === value) {
  40047. return;
  40048. }
  40049. this._transparencyMode = value;
  40050. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40051. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40052. },
  40053. enumerable: true,
  40054. configurable: true
  40055. });
  40056. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40057. /**
  40058. * Returns true if alpha blending should be disabled.
  40059. */
  40060. get: function () {
  40061. return (this._linkRefractionWithTransparency ||
  40062. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40063. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40064. },
  40065. enumerable: true,
  40066. configurable: true
  40067. });
  40068. /**
  40069. * Specifies whether or not this material should be rendered in alpha blend mode.
  40070. */
  40071. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40072. if (this._disableAlphaBlending) {
  40073. return false;
  40074. }
  40075. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40076. };
  40077. /**
  40078. * Specifies if the mesh will require alpha blending.
  40079. * @param mesh - BJS mesh.
  40080. */
  40081. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40082. if (this._disableAlphaBlending) {
  40083. return false;
  40084. }
  40085. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40086. };
  40087. /**
  40088. * Specifies whether or not this material should be rendered in alpha test mode.
  40089. */
  40090. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40091. if (this._forceAlphaTest) {
  40092. return true;
  40093. }
  40094. if (this._linkRefractionWithTransparency) {
  40095. return false;
  40096. }
  40097. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40098. };
  40099. /**
  40100. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40101. */
  40102. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40103. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40104. };
  40105. /**
  40106. * Gets the texture used for the alpha test.
  40107. */
  40108. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40109. return this._albedoTexture;
  40110. };
  40111. /**
  40112. * Specifies that the submesh is ready to be used.
  40113. * @param mesh - BJS mesh.
  40114. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40115. * @param useInstances - Specifies that instances should be used.
  40116. * @returns - boolean indicating that the submesh is ready or not.
  40117. */
  40118. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40119. if (subMesh.effect && this.isFrozen) {
  40120. if (this._wasPreviouslyReady) {
  40121. return true;
  40122. }
  40123. }
  40124. if (!subMesh._materialDefines) {
  40125. subMesh._materialDefines = new PBRMaterialDefines();
  40126. }
  40127. var defines = subMesh._materialDefines;
  40128. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40129. if (defines._renderId === this.getScene().getRenderId()) {
  40130. return true;
  40131. }
  40132. }
  40133. var scene = this.getScene();
  40134. var engine = scene.getEngine();
  40135. if (defines._areTexturesDirty) {
  40136. if (scene.texturesEnabled) {
  40137. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40138. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40139. return false;
  40140. }
  40141. }
  40142. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40143. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40144. return false;
  40145. }
  40146. }
  40147. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40148. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40149. return false;
  40150. }
  40151. }
  40152. var reflectionTexture = this._getReflectionTexture();
  40153. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40154. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40155. return false;
  40156. }
  40157. }
  40158. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40159. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40160. return false;
  40161. }
  40162. }
  40163. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40164. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40165. return false;
  40166. }
  40167. }
  40168. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40169. if (this._metallicTexture) {
  40170. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40171. return false;
  40172. }
  40173. }
  40174. else if (this._reflectivityTexture) {
  40175. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40176. return false;
  40177. }
  40178. }
  40179. if (this._microSurfaceTexture) {
  40180. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40181. return false;
  40182. }
  40183. }
  40184. }
  40185. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40186. // Bump texture cannot be not blocking.
  40187. if (!this._bumpTexture.isReady()) {
  40188. return false;
  40189. }
  40190. }
  40191. var refractionTexture = this._getRefractionTexture();
  40192. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40193. if (!refractionTexture.isReadyOrNotBlocking()) {
  40194. return false;
  40195. }
  40196. }
  40197. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40198. // This is blocking.
  40199. if (!this._environmentBRDFTexture.isReady()) {
  40200. return false;
  40201. }
  40202. }
  40203. }
  40204. }
  40205. if (defines._areImageProcessingDirty) {
  40206. if (!this._imageProcessingConfiguration.isReady()) {
  40207. return false;
  40208. }
  40209. }
  40210. if (!engine.getCaps().standardDerivatives) {
  40211. var bufferMesh = null;
  40212. if (mesh.getClassName() === "InstancedMesh") {
  40213. bufferMesh = mesh.sourceMesh;
  40214. }
  40215. else if (mesh.getClassName() === "Mesh") {
  40216. bufferMesh = mesh;
  40217. }
  40218. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40219. bufferMesh.createNormals(true);
  40220. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40221. }
  40222. }
  40223. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40224. if (effect) {
  40225. scene.resetCachedMaterial();
  40226. subMesh.setEffect(effect, defines);
  40227. this.buildUniformLayout();
  40228. }
  40229. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40230. return false;
  40231. }
  40232. defines._renderId = scene.getRenderId();
  40233. this._wasPreviouslyReady = true;
  40234. return true;
  40235. };
  40236. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40237. if (onCompiled === void 0) { onCompiled = null; }
  40238. if (onError === void 0) { onError = null; }
  40239. if (useInstances === void 0) { useInstances = null; }
  40240. if (useClipPlane === void 0) { useClipPlane = null; }
  40241. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40242. if (!defines.isDirty) {
  40243. return null;
  40244. }
  40245. defines.markAsProcessed();
  40246. var scene = this.getScene();
  40247. var engine = scene.getEngine();
  40248. // Fallbacks
  40249. var fallbacks = new BABYLON.EffectFallbacks();
  40250. var fallbackRank = 0;
  40251. if (defines.USESPHERICALINVERTEX) {
  40252. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40253. }
  40254. if (defines.FOG) {
  40255. fallbacks.addFallback(fallbackRank, "FOG");
  40256. }
  40257. if (defines.POINTSIZE) {
  40258. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40259. }
  40260. if (defines.LOGARITHMICDEPTH) {
  40261. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40262. }
  40263. if (defines.PARALLAX) {
  40264. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40265. }
  40266. if (defines.PARALLAXOCCLUSION) {
  40267. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40268. }
  40269. if (defines.ENVIRONMENTBRDF) {
  40270. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40271. }
  40272. if (defines.TANGENT) {
  40273. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40274. }
  40275. if (defines.BUMP) {
  40276. fallbacks.addFallback(fallbackRank++, "BUMP");
  40277. }
  40278. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40279. if (defines.SPECULARTERM) {
  40280. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40281. }
  40282. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40283. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40284. }
  40285. if (defines.LIGHTMAP) {
  40286. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40287. }
  40288. if (defines.NORMAL) {
  40289. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40290. }
  40291. if (defines.AMBIENT) {
  40292. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40293. }
  40294. if (defines.EMISSIVE) {
  40295. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40296. }
  40297. if (defines.VERTEXCOLOR) {
  40298. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40299. }
  40300. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40301. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40302. }
  40303. if (defines.MORPHTARGETS) {
  40304. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40305. }
  40306. //Attributes
  40307. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40308. if (defines.NORMAL) {
  40309. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40310. }
  40311. if (defines.TANGENT) {
  40312. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40313. }
  40314. if (defines.UV1) {
  40315. attribs.push(BABYLON.VertexBuffer.UVKind);
  40316. }
  40317. if (defines.UV2) {
  40318. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40319. }
  40320. if (defines.VERTEXCOLOR) {
  40321. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40322. }
  40323. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40324. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40325. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40326. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40327. "vFogInfos", "vFogColor", "pointSize",
  40328. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40329. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40330. "mBones",
  40331. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40332. "vLightingIntensity",
  40333. "logarithmicDepthConstant",
  40334. "vSphericalX", "vSphericalY", "vSphericalZ",
  40335. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40336. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40337. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40338. "vTangentSpaceParams"
  40339. ];
  40340. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40341. "bumpSampler", "lightmapSampler", "opacitySampler",
  40342. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40343. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40344. "microSurfaceSampler", "environmentBrdfSampler"];
  40345. var uniformBuffers = ["Material", "Scene"];
  40346. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40347. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40348. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40349. uniformsNames: uniforms,
  40350. uniformBuffersNames: uniformBuffers,
  40351. samplers: samplers,
  40352. defines: defines,
  40353. maxSimultaneousLights: this._maxSimultaneousLights
  40354. });
  40355. var join = defines.toString();
  40356. return engine.createEffect("pbr", {
  40357. attributes: attribs,
  40358. uniformsNames: uniforms,
  40359. uniformBuffersNames: uniformBuffers,
  40360. samplers: samplers,
  40361. defines: join,
  40362. fallbacks: fallbacks,
  40363. onCompiled: onCompiled,
  40364. onError: onError,
  40365. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40366. }, engine);
  40367. };
  40368. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40369. if (useInstances === void 0) { useInstances = null; }
  40370. if (useClipPlane === void 0) { useClipPlane = null; }
  40371. var scene = this.getScene();
  40372. var engine = scene.getEngine();
  40373. // Lights
  40374. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40375. defines._needNormals = true;
  40376. // Textures
  40377. if (defines._areTexturesDirty) {
  40378. defines._needUVs = false;
  40379. if (scene.texturesEnabled) {
  40380. if (scene.getEngine().getCaps().textureLOD) {
  40381. defines.LODBASEDMICROSFURACE = true;
  40382. }
  40383. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40384. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40385. }
  40386. else {
  40387. defines.ALBEDO = false;
  40388. }
  40389. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40390. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40391. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40392. }
  40393. else {
  40394. defines.AMBIENT = false;
  40395. }
  40396. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40397. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40398. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40399. }
  40400. else {
  40401. defines.OPACITY = false;
  40402. }
  40403. var reflectionTexture = this._getReflectionTexture();
  40404. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40405. defines.REFLECTION = true;
  40406. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40407. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40408. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40409. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40410. defines.INVERTCUBICMAP = true;
  40411. }
  40412. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40413. switch (reflectionTexture.coordinatesMode) {
  40414. case BABYLON.Texture.CUBIC_MODE:
  40415. case BABYLON.Texture.INVCUBIC_MODE:
  40416. defines.REFLECTIONMAP_CUBIC = true;
  40417. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40418. break;
  40419. case BABYLON.Texture.EXPLICIT_MODE:
  40420. defines.REFLECTIONMAP_EXPLICIT = true;
  40421. break;
  40422. case BABYLON.Texture.PLANAR_MODE:
  40423. defines.REFLECTIONMAP_PLANAR = true;
  40424. break;
  40425. case BABYLON.Texture.PROJECTION_MODE:
  40426. defines.REFLECTIONMAP_PROJECTION = true;
  40427. break;
  40428. case BABYLON.Texture.SKYBOX_MODE:
  40429. defines.REFLECTIONMAP_SKYBOX = true;
  40430. break;
  40431. case BABYLON.Texture.SPHERICAL_MODE:
  40432. defines.REFLECTIONMAP_SPHERICAL = true;
  40433. break;
  40434. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40435. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40436. break;
  40437. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40438. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40439. break;
  40440. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40441. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40442. break;
  40443. }
  40444. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40445. if (reflectionTexture.sphericalPolynomial) {
  40446. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40447. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40448. defines.USESPHERICALINVERTEX = false;
  40449. }
  40450. else {
  40451. defines.USESPHERICALINVERTEX = true;
  40452. }
  40453. }
  40454. }
  40455. }
  40456. else {
  40457. defines.REFLECTION = false;
  40458. defines.REFLECTIONMAP_3D = false;
  40459. defines.REFLECTIONMAP_SPHERICAL = false;
  40460. defines.REFLECTIONMAP_PLANAR = false;
  40461. defines.REFLECTIONMAP_CUBIC = false;
  40462. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40463. defines.REFLECTIONMAP_PROJECTION = false;
  40464. defines.REFLECTIONMAP_SKYBOX = false;
  40465. defines.REFLECTIONMAP_EXPLICIT = false;
  40466. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40467. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40468. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40469. defines.INVERTCUBICMAP = false;
  40470. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40471. defines.USESPHERICALINVERTEX = false;
  40472. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40473. defines.LODINREFLECTIONALPHA = false;
  40474. defines.GAMMAREFLECTION = false;
  40475. }
  40476. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40477. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40478. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40479. }
  40480. else {
  40481. defines.LIGHTMAP = false;
  40482. }
  40483. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40485. }
  40486. else {
  40487. defines.EMISSIVE = false;
  40488. }
  40489. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40490. if (this._metallicTexture) {
  40491. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40492. defines.METALLICWORKFLOW = true;
  40493. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40494. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40495. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40496. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40497. }
  40498. else if (this._reflectivityTexture) {
  40499. defines.METALLICWORKFLOW = false;
  40500. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40501. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40502. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40503. }
  40504. else {
  40505. defines.METALLICWORKFLOW = false;
  40506. defines.REFLECTIVITY = false;
  40507. }
  40508. if (this._microSurfaceTexture) {
  40509. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40510. }
  40511. else {
  40512. defines.MICROSURFACEMAP = false;
  40513. }
  40514. }
  40515. else {
  40516. defines.REFLECTIVITY = false;
  40517. defines.MICROSURFACEMAP = false;
  40518. }
  40519. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40520. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40521. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40522. defines.PARALLAX = true;
  40523. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40524. }
  40525. else {
  40526. defines.PARALLAX = false;
  40527. }
  40528. }
  40529. else {
  40530. defines.BUMP = false;
  40531. }
  40532. var refractionTexture = this._getRefractionTexture();
  40533. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40534. defines.REFRACTION = true;
  40535. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40536. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40537. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40538. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40539. if (this._linkRefractionWithTransparency) {
  40540. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40541. }
  40542. }
  40543. else {
  40544. defines.REFRACTION = false;
  40545. }
  40546. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40547. defines.ENVIRONMENTBRDF = true;
  40548. }
  40549. else {
  40550. defines.ENVIRONMENTBRDF = false;
  40551. }
  40552. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40553. defines.ALPHAFROMALBEDO = true;
  40554. }
  40555. else {
  40556. defines.ALPHAFROMALBEDO = false;
  40557. }
  40558. }
  40559. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40560. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40561. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40562. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40563. defines.METALLICWORKFLOW = true;
  40564. }
  40565. else {
  40566. defines.METALLICWORKFLOW = false;
  40567. }
  40568. if (!this.backFaceCulling && this._twoSidedLighting) {
  40569. defines.TWOSIDEDLIGHTING = true;
  40570. }
  40571. else {
  40572. defines.TWOSIDEDLIGHTING = false;
  40573. }
  40574. defines.ALPHATESTVALUE = this._alphaCutOff;
  40575. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40576. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40577. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40578. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40579. }
  40580. if (defines._areImageProcessingDirty) {
  40581. this._imageProcessingConfiguration.prepareDefines(defines);
  40582. }
  40583. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40584. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40585. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40586. // Misc.
  40587. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40588. // Values that need to be evaluated on every frame
  40589. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40590. // Attribs
  40591. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40592. };
  40593. /**
  40594. * Force shader compilation
  40595. */
  40596. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40597. var _this = this;
  40598. var localOptions = __assign({ clipPlane: false }, options);
  40599. var defines = new PBRMaterialDefines();
  40600. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40601. if (effect.isReady()) {
  40602. if (onCompiled) {
  40603. onCompiled(this);
  40604. }
  40605. }
  40606. else {
  40607. effect.onCompileObservable.add(function () {
  40608. if (onCompiled) {
  40609. onCompiled(_this);
  40610. }
  40611. });
  40612. }
  40613. };
  40614. /**
  40615. * Initializes the uniform buffer layout for the shader.
  40616. */
  40617. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40618. // Order is important !
  40619. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40620. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40621. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40622. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40623. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40624. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40625. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40626. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40627. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40628. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40629. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40630. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40631. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40632. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40633. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40634. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40635. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40636. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40637. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40638. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40639. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40640. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40641. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40642. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40643. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40644. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40645. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40646. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40647. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40648. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40649. this._uniformBuffer.addUniform("pointSize", 1);
  40650. this._uniformBuffer.create();
  40651. };
  40652. /**
  40653. * Unbinds the textures.
  40654. */
  40655. PBRBaseMaterial.prototype.unbind = function () {
  40656. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40657. this._uniformBuffer.setTexture("reflectionSampler", null);
  40658. }
  40659. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40660. this._uniformBuffer.setTexture("refractionSampler", null);
  40661. }
  40662. _super.prototype.unbind.call(this);
  40663. };
  40664. /**
  40665. * Binds to the world matrix.
  40666. * @param world - The world matrix.
  40667. */
  40668. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40669. this._activeEffect.setMatrix("world", world);
  40670. };
  40671. /**
  40672. * Binds the submesh data.
  40673. * @param world - The world matrix.
  40674. * @param mesh - The BJS mesh.
  40675. * @param subMesh - A submesh of the BJS mesh.
  40676. */
  40677. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40678. var scene = this.getScene();
  40679. var defines = subMesh._materialDefines;
  40680. if (!defines) {
  40681. return;
  40682. }
  40683. var effect = subMesh.effect;
  40684. if (!effect) {
  40685. return;
  40686. }
  40687. this._activeEffect = effect;
  40688. // Matrices
  40689. this.bindOnlyWorldMatrix(world);
  40690. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40691. // Bones
  40692. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40693. var reflectionTexture = null;
  40694. if (mustRebind) {
  40695. this._uniformBuffer.bindToEffect(effect, "Material");
  40696. this.bindViewProjection(effect);
  40697. reflectionTexture = this._getReflectionTexture();
  40698. var refractionTexture = this._getRefractionTexture();
  40699. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40700. // Texture uniforms
  40701. if (scene.texturesEnabled) {
  40702. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40703. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40704. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40705. }
  40706. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40707. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40708. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40709. }
  40710. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40711. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40712. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40713. }
  40714. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40715. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40716. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40717. if (reflectionTexture.boundingBoxSize) {
  40718. var cubeTexture = reflectionTexture;
  40719. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40720. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40721. }
  40722. var polynomials = reflectionTexture.sphericalPolynomial;
  40723. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40724. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40725. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40726. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40727. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40728. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40729. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40730. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40731. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40732. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40733. }
  40734. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40735. }
  40736. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40737. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40738. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40739. }
  40740. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40741. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40742. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40743. }
  40744. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40745. if (this._metallicTexture) {
  40746. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40747. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40748. }
  40749. else if (this._reflectivityTexture) {
  40750. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40751. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40752. }
  40753. if (this._microSurfaceTexture) {
  40754. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40755. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40756. }
  40757. }
  40758. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40759. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40760. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40761. if (scene._mirroredCameraPosition) {
  40762. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40763. }
  40764. else {
  40765. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40766. }
  40767. }
  40768. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40769. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40770. var depth = 1.0;
  40771. if (!refractionTexture.isCube) {
  40772. if (refractionTexture.depth) {
  40773. depth = refractionTexture.depth;
  40774. }
  40775. }
  40776. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40777. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40778. }
  40779. }
  40780. // Point size
  40781. if (this.pointsCloud) {
  40782. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40783. }
  40784. // Colors
  40785. if (defines.METALLICWORKFLOW) {
  40786. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40787. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40788. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40789. }
  40790. else {
  40791. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40792. }
  40793. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40794. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40795. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40796. // Misc
  40797. this._lightingInfos.x = this._directIntensity;
  40798. this._lightingInfos.y = this._emissiveIntensity;
  40799. this._lightingInfos.z = this._environmentIntensity;
  40800. this._lightingInfos.w = this._specularIntensity;
  40801. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40802. }
  40803. // Textures
  40804. if (scene.texturesEnabled) {
  40805. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40806. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40807. }
  40808. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40809. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40810. }
  40811. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40812. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40813. }
  40814. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40815. if (defines.LODBASEDMICROSFURACE) {
  40816. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40817. }
  40818. else {
  40819. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40820. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40821. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40822. }
  40823. }
  40824. if (defines.ENVIRONMENTBRDF) {
  40825. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40826. }
  40827. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40828. if (defines.LODBASEDMICROSFURACE) {
  40829. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40830. }
  40831. else {
  40832. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40833. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40834. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40835. }
  40836. }
  40837. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40838. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40839. }
  40840. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40841. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40842. }
  40843. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40844. if (this._metallicTexture) {
  40845. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40846. }
  40847. else if (this._reflectivityTexture) {
  40848. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40849. }
  40850. if (this._microSurfaceTexture) {
  40851. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40852. }
  40853. }
  40854. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40855. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40856. }
  40857. }
  40858. // Clip plane
  40859. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40860. // Colors
  40861. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40862. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40863. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40864. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40865. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40866. }
  40867. if (mustRebind || !this.isFrozen) {
  40868. // Lights
  40869. if (scene.lightsEnabled && !this._disableLighting) {
  40870. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40871. }
  40872. // View
  40873. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40874. this.bindView(effect);
  40875. }
  40876. // Fog
  40877. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40878. // Morph targets
  40879. if (defines.NUM_MORPH_INFLUENCERS) {
  40880. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40881. }
  40882. // image processing
  40883. this._imageProcessingConfiguration.bind(this._activeEffect);
  40884. // Log. depth
  40885. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40886. }
  40887. this._uniformBuffer.update();
  40888. this._afterBind(mesh);
  40889. };
  40890. /**
  40891. * Returns the animatable textures.
  40892. * @returns - Array of animatable textures.
  40893. */
  40894. PBRBaseMaterial.prototype.getAnimatables = function () {
  40895. var results = [];
  40896. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40897. results.push(this._albedoTexture);
  40898. }
  40899. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40900. results.push(this._ambientTexture);
  40901. }
  40902. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40903. results.push(this._opacityTexture);
  40904. }
  40905. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40906. results.push(this._reflectionTexture);
  40907. }
  40908. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40909. results.push(this._emissiveTexture);
  40910. }
  40911. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40912. results.push(this._metallicTexture);
  40913. }
  40914. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40915. results.push(this._reflectivityTexture);
  40916. }
  40917. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40918. results.push(this._bumpTexture);
  40919. }
  40920. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40921. results.push(this._lightmapTexture);
  40922. }
  40923. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40924. results.push(this._refractionTexture);
  40925. }
  40926. return results;
  40927. };
  40928. /**
  40929. * Returns the texture used for reflections.
  40930. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40931. */
  40932. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40933. if (this._reflectionTexture) {
  40934. return this._reflectionTexture;
  40935. }
  40936. return this.getScene().environmentTexture;
  40937. };
  40938. /**
  40939. * Returns the texture used for refraction or null if none is used.
  40940. * @returns - Refection texture if present. If no refraction texture and refraction
  40941. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40942. */
  40943. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40944. if (this._refractionTexture) {
  40945. return this._refractionTexture;
  40946. }
  40947. if (this._linkRefractionWithTransparency) {
  40948. return this.getScene().environmentTexture;
  40949. }
  40950. return null;
  40951. };
  40952. /**
  40953. * Disposes the resources of the material.
  40954. * @param forceDisposeEffect - Forces the disposal of effects.
  40955. * @param forceDisposeTextures - Forces the disposal of all textures.
  40956. */
  40957. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40958. if (forceDisposeTextures) {
  40959. if (this._albedoTexture) {
  40960. this._albedoTexture.dispose();
  40961. }
  40962. if (this._ambientTexture) {
  40963. this._ambientTexture.dispose();
  40964. }
  40965. if (this._opacityTexture) {
  40966. this._opacityTexture.dispose();
  40967. }
  40968. if (this._reflectionTexture) {
  40969. this._reflectionTexture.dispose();
  40970. }
  40971. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40972. this._environmentBRDFTexture.dispose();
  40973. }
  40974. if (this._emissiveTexture) {
  40975. this._emissiveTexture.dispose();
  40976. }
  40977. if (this._metallicTexture) {
  40978. this._metallicTexture.dispose();
  40979. }
  40980. if (this._reflectivityTexture) {
  40981. this._reflectivityTexture.dispose();
  40982. }
  40983. if (this._bumpTexture) {
  40984. this._bumpTexture.dispose();
  40985. }
  40986. if (this._lightmapTexture) {
  40987. this._lightmapTexture.dispose();
  40988. }
  40989. if (this._refractionTexture) {
  40990. this._refractionTexture.dispose();
  40991. }
  40992. }
  40993. this._renderTargets.dispose();
  40994. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40995. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40996. }
  40997. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40998. };
  40999. /**
  41000. * Stores the reflectivity values based on metallic roughness workflow.
  41001. */
  41002. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41003. __decorate([
  41004. BABYLON.serializeAsImageProcessingConfiguration()
  41005. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41006. __decorate([
  41007. BABYLON.serialize()
  41008. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41009. __decorate([
  41010. BABYLON.serialize()
  41011. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41012. return PBRBaseMaterial;
  41013. }(BABYLON.PushMaterial));
  41014. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41015. })(BABYLON || (BABYLON = {}));
  41016. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41017. var BABYLON;
  41018. (function (BABYLON) {
  41019. /**
  41020. * The Physically based simple base material of BJS.
  41021. *
  41022. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41023. * It is used as the base class for both the specGloss and metalRough conventions.
  41024. */
  41025. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41026. __extends(PBRBaseSimpleMaterial, _super);
  41027. /**
  41028. * Instantiates a new PBRMaterial instance.
  41029. *
  41030. * @param name The material name
  41031. * @param scene The scene the material will be use in.
  41032. */
  41033. function PBRBaseSimpleMaterial(name, scene) {
  41034. var _this = _super.call(this, name, scene) || this;
  41035. /**
  41036. * Number of Simultaneous lights allowed on the material.
  41037. */
  41038. _this.maxSimultaneousLights = 4;
  41039. /**
  41040. * If sets to true, disables all the lights affecting the material.
  41041. */
  41042. _this.disableLighting = false;
  41043. /**
  41044. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41045. */
  41046. _this.invertNormalMapX = false;
  41047. /**
  41048. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41049. */
  41050. _this.invertNormalMapY = false;
  41051. /**
  41052. * Emissivie color used to self-illuminate the model.
  41053. */
  41054. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41055. /**
  41056. * Occlusion Channel Strenght.
  41057. */
  41058. _this.occlusionStrength = 1.0;
  41059. _this.useLightmapAsShadowmap = false;
  41060. _this._useAlphaFromAlbedoTexture = true;
  41061. _this._useAmbientInGrayScale = true;
  41062. return _this;
  41063. }
  41064. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41065. /**
  41066. * Gets the current double sided mode.
  41067. */
  41068. get: function () {
  41069. return this._twoSidedLighting;
  41070. },
  41071. /**
  41072. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41073. */
  41074. set: function (value) {
  41075. if (this._twoSidedLighting === value) {
  41076. return;
  41077. }
  41078. this._twoSidedLighting = value;
  41079. this.backFaceCulling = !value;
  41080. this._markAllSubMeshesAsTexturesDirty();
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. /**
  41086. * Return the active textures of the material.
  41087. */
  41088. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41089. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41090. if (this.environmentTexture) {
  41091. activeTextures.push(this.environmentTexture);
  41092. }
  41093. if (this.normalTexture) {
  41094. activeTextures.push(this.normalTexture);
  41095. }
  41096. if (this.emissiveTexture) {
  41097. activeTextures.push(this.emissiveTexture);
  41098. }
  41099. if (this.occlusionTexture) {
  41100. activeTextures.push(this.occlusionTexture);
  41101. }
  41102. if (this.lightmapTexture) {
  41103. activeTextures.push(this.lightmapTexture);
  41104. }
  41105. return activeTextures;
  41106. };
  41107. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41108. if (_super.prototype.hasTexture.call(this, texture)) {
  41109. return true;
  41110. }
  41111. if (this.lightmapTexture === texture) {
  41112. return true;
  41113. }
  41114. return false;
  41115. };
  41116. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41117. return "PBRBaseSimpleMaterial";
  41118. };
  41119. __decorate([
  41120. BABYLON.serialize(),
  41121. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41122. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41123. __decorate([
  41124. BABYLON.serialize(),
  41125. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41126. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41127. __decorate([
  41128. BABYLON.serializeAsTexture(),
  41129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41130. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41131. __decorate([
  41132. BABYLON.serialize(),
  41133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41134. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41135. __decorate([
  41136. BABYLON.serialize(),
  41137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41138. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41139. __decorate([
  41140. BABYLON.serializeAsTexture(),
  41141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41142. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41143. __decorate([
  41144. BABYLON.serializeAsColor3("emissive"),
  41145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41146. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41147. __decorate([
  41148. BABYLON.serializeAsTexture(),
  41149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41150. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41151. __decorate([
  41152. BABYLON.serialize(),
  41153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41154. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41155. __decorate([
  41156. BABYLON.serializeAsTexture(),
  41157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41158. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41159. __decorate([
  41160. BABYLON.serialize(),
  41161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41162. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41163. __decorate([
  41164. BABYLON.serialize()
  41165. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41166. __decorate([
  41167. BABYLON.serializeAsTexture(),
  41168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41169. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41170. __decorate([
  41171. BABYLON.serialize(),
  41172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41173. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41174. return PBRBaseSimpleMaterial;
  41175. }(BABYLON.PBRBaseMaterial));
  41176. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41177. })(BABYLON || (BABYLON = {}));
  41178. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41179. var BABYLON;
  41180. (function (BABYLON) {
  41181. /**
  41182. * The Physically based material of BJS.
  41183. *
  41184. * This offers the main features of a standard PBR material.
  41185. * For more information, please refer to the documentation :
  41186. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41187. */
  41188. var PBRMaterial = /** @class */ (function (_super) {
  41189. __extends(PBRMaterial, _super);
  41190. /**
  41191. * Instantiates a new PBRMaterial instance.
  41192. *
  41193. * @param name The material name
  41194. * @param scene The scene the material will be use in.
  41195. */
  41196. function PBRMaterial(name, scene) {
  41197. var _this = _super.call(this, name, scene) || this;
  41198. /**
  41199. * Intensity of the direct lights e.g. the four lights available in your scene.
  41200. * This impacts both the direct diffuse and specular highlights.
  41201. */
  41202. _this.directIntensity = 1.0;
  41203. /**
  41204. * Intensity of the emissive part of the material.
  41205. * This helps controlling the emissive effect without modifying the emissive color.
  41206. */
  41207. _this.emissiveIntensity = 1.0;
  41208. /**
  41209. * Intensity of the environment e.g. how much the environment will light the object
  41210. * either through harmonics for rough material or through the refelction for shiny ones.
  41211. */
  41212. _this.environmentIntensity = 1.0;
  41213. /**
  41214. * This is a special control allowing the reduction of the specular highlights coming from the
  41215. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41216. */
  41217. _this.specularIntensity = 1.0;
  41218. /**
  41219. * Debug Control allowing disabling the bump map on this material.
  41220. */
  41221. _this.disableBumpMap = false;
  41222. /**
  41223. * AKA Occlusion Texture Intensity in other nomenclature.
  41224. */
  41225. _this.ambientTextureStrength = 1.0;
  41226. /**
  41227. * The color of a material in ambient lighting.
  41228. */
  41229. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41230. /**
  41231. * AKA Diffuse Color in other nomenclature.
  41232. */
  41233. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41234. /**
  41235. * AKA Specular Color in other nomenclature.
  41236. */
  41237. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41238. /**
  41239. * The color reflected from the material.
  41240. */
  41241. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41242. /**
  41243. * The color emitted from the material.
  41244. */
  41245. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41246. /**
  41247. * AKA Glossiness in other nomenclature.
  41248. */
  41249. _this.microSurface = 1.0;
  41250. /**
  41251. * source material index of refraction (IOR)' / 'destination material IOR.
  41252. */
  41253. _this.indexOfRefraction = 0.66;
  41254. /**
  41255. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41256. */
  41257. _this.invertRefractionY = false;
  41258. /**
  41259. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41260. * Materials half opaque for instance using refraction could benefit from this control.
  41261. */
  41262. _this.linkRefractionWithTransparency = false;
  41263. _this.useLightmapAsShadowmap = false;
  41264. /**
  41265. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41266. */
  41267. _this.useAlphaFromAlbedoTexture = false;
  41268. /**
  41269. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41270. */
  41271. _this.forceAlphaTest = false;
  41272. /**
  41273. * Defines the alpha limits in alpha test mode.
  41274. */
  41275. _this.alphaCutOff = 0.4;
  41276. /**
  41277. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41278. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41279. */
  41280. _this.useSpecularOverAlpha = true;
  41281. /**
  41282. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41283. */
  41284. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41285. /**
  41286. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41287. */
  41288. _this.useRoughnessFromMetallicTextureAlpha = true;
  41289. /**
  41290. * Specifies if the metallic texture contains the roughness information in its green channel.
  41291. */
  41292. _this.useRoughnessFromMetallicTextureGreen = false;
  41293. /**
  41294. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41295. */
  41296. _this.useMetallnessFromMetallicTextureBlue = false;
  41297. /**
  41298. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41299. */
  41300. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41301. /**
  41302. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41303. */
  41304. _this.useAmbientInGrayScale = false;
  41305. /**
  41306. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41307. * The material will try to infer what glossiness each pixel should be.
  41308. */
  41309. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41310. /**
  41311. * BJS is using an harcoded light falloff based on a manually sets up range.
  41312. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41313. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41314. */
  41315. _this.usePhysicalLightFalloff = true;
  41316. /**
  41317. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41318. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41319. */
  41320. _this.useRadianceOverAlpha = true;
  41321. /**
  41322. * Allows using the bump map in parallax mode.
  41323. */
  41324. _this.useParallax = false;
  41325. /**
  41326. * Allows using the bump map in parallax occlusion mode.
  41327. */
  41328. _this.useParallaxOcclusion = false;
  41329. /**
  41330. * Controls the scale bias of the parallax mode.
  41331. */
  41332. _this.parallaxScaleBias = 0.05;
  41333. /**
  41334. * If sets to true, disables all the lights affecting the material.
  41335. */
  41336. _this.disableLighting = false;
  41337. /**
  41338. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41339. */
  41340. _this.forceIrradianceInFragment = false;
  41341. /**
  41342. * Number of Simultaneous lights allowed on the material.
  41343. */
  41344. _this.maxSimultaneousLights = 4;
  41345. /**
  41346. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41347. */
  41348. _this.invertNormalMapX = false;
  41349. /**
  41350. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41351. */
  41352. _this.invertNormalMapY = false;
  41353. /**
  41354. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41355. */
  41356. _this.twoSidedLighting = false;
  41357. /**
  41358. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41359. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41360. */
  41361. _this.useAlphaFresnel = false;
  41362. /**
  41363. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41364. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41365. */
  41366. _this.useLinearAlphaFresnel = false;
  41367. /**
  41368. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41369. * And/Or occlude the blended part.
  41370. */
  41371. _this.environmentBRDFTexture = null;
  41372. /**
  41373. * Force normal to face away from face.
  41374. */
  41375. _this.forceNormalForward = false;
  41376. /**
  41377. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41378. * makes the reflect vector face the model (under horizon).
  41379. */
  41380. _this.useHorizonOcclusion = true;
  41381. /**
  41382. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41383. * too much the area relying on ambient texture to define their ambient occlusion.
  41384. */
  41385. _this.useRadianceOcclusion = true;
  41386. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41387. return _this;
  41388. }
  41389. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41390. /**
  41391. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41392. */
  41393. get: function () {
  41394. return this._PBRMATERIAL_OPAQUE;
  41395. },
  41396. enumerable: true,
  41397. configurable: true
  41398. });
  41399. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41400. /**
  41401. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41402. */
  41403. get: function () {
  41404. return this._PBRMATERIAL_ALPHATEST;
  41405. },
  41406. enumerable: true,
  41407. configurable: true
  41408. });
  41409. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41410. /**
  41411. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41412. */
  41413. get: function () {
  41414. return this._PBRMATERIAL_ALPHABLEND;
  41415. },
  41416. enumerable: true,
  41417. configurable: true
  41418. });
  41419. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41420. /**
  41421. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41422. * They are also discarded below the alpha cutoff threshold to improve performances.
  41423. */
  41424. get: function () {
  41425. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41426. },
  41427. enumerable: true,
  41428. configurable: true
  41429. });
  41430. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41431. /**
  41432. * Gets the image processing configuration used either in this material.
  41433. */
  41434. get: function () {
  41435. return this._imageProcessingConfiguration;
  41436. },
  41437. /**
  41438. * Sets the Default image processing configuration used either in the this material.
  41439. *
  41440. * If sets to null, the scene one is in use.
  41441. */
  41442. set: function (value) {
  41443. this._attachImageProcessingConfiguration(value);
  41444. // Ensure the effect will be rebuilt.
  41445. this._markAllSubMeshesAsTexturesDirty();
  41446. },
  41447. enumerable: true,
  41448. configurable: true
  41449. });
  41450. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41451. /**
  41452. * Gets wether the color curves effect is enabled.
  41453. */
  41454. get: function () {
  41455. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41456. },
  41457. /**
  41458. * Sets wether the color curves effect is enabled.
  41459. */
  41460. set: function (value) {
  41461. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41462. },
  41463. enumerable: true,
  41464. configurable: true
  41465. });
  41466. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41467. /**
  41468. * Gets wether the color grading effect is enabled.
  41469. */
  41470. get: function () {
  41471. return this.imageProcessingConfiguration.colorGradingEnabled;
  41472. },
  41473. /**
  41474. * Gets wether the color grading effect is enabled.
  41475. */
  41476. set: function (value) {
  41477. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41478. },
  41479. enumerable: true,
  41480. configurable: true
  41481. });
  41482. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41483. /**
  41484. * Gets wether tonemapping is enabled or not.
  41485. */
  41486. get: function () {
  41487. return this._imageProcessingConfiguration.toneMappingEnabled;
  41488. },
  41489. /**
  41490. * Sets wether tonemapping is enabled or not
  41491. */
  41492. set: function (value) {
  41493. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41494. },
  41495. enumerable: true,
  41496. configurable: true
  41497. });
  41498. ;
  41499. ;
  41500. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41501. /**
  41502. * The camera exposure used on this material.
  41503. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41504. * This corresponds to a photographic exposure.
  41505. */
  41506. get: function () {
  41507. return this._imageProcessingConfiguration.exposure;
  41508. },
  41509. /**
  41510. * The camera exposure used on this material.
  41511. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41512. * This corresponds to a photographic exposure.
  41513. */
  41514. set: function (value) {
  41515. this._imageProcessingConfiguration.exposure = value;
  41516. },
  41517. enumerable: true,
  41518. configurable: true
  41519. });
  41520. ;
  41521. ;
  41522. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41523. /**
  41524. * Gets The camera contrast used on this material.
  41525. */
  41526. get: function () {
  41527. return this._imageProcessingConfiguration.contrast;
  41528. },
  41529. /**
  41530. * Sets The camera contrast used on this material.
  41531. */
  41532. set: function (value) {
  41533. this._imageProcessingConfiguration.contrast = value;
  41534. },
  41535. enumerable: true,
  41536. configurable: true
  41537. });
  41538. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41539. /**
  41540. * Gets the Color Grading 2D Lookup Texture.
  41541. */
  41542. get: function () {
  41543. return this._imageProcessingConfiguration.colorGradingTexture;
  41544. },
  41545. /**
  41546. * Sets the Color Grading 2D Lookup Texture.
  41547. */
  41548. set: function (value) {
  41549. this._imageProcessingConfiguration.colorGradingTexture = value;
  41550. },
  41551. enumerable: true,
  41552. configurable: true
  41553. });
  41554. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41555. /**
  41556. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41557. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41558. * 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;
  41559. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41560. */
  41561. get: function () {
  41562. return this._imageProcessingConfiguration.colorCurves;
  41563. },
  41564. /**
  41565. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41566. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41567. * 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;
  41568. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41569. */
  41570. set: function (value) {
  41571. this._imageProcessingConfiguration.colorCurves = value;
  41572. },
  41573. enumerable: true,
  41574. configurable: true
  41575. });
  41576. /**
  41577. * Returns the name of this material class.
  41578. */
  41579. PBRMaterial.prototype.getClassName = function () {
  41580. return "PBRMaterial";
  41581. };
  41582. /**
  41583. * Returns an array of the actively used textures.
  41584. * @returns - Array of BaseTextures
  41585. */
  41586. PBRMaterial.prototype.getActiveTextures = function () {
  41587. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41588. if (this._albedoTexture) {
  41589. activeTextures.push(this._albedoTexture);
  41590. }
  41591. if (this._ambientTexture) {
  41592. activeTextures.push(this._ambientTexture);
  41593. }
  41594. if (this._opacityTexture) {
  41595. activeTextures.push(this._opacityTexture);
  41596. }
  41597. if (this._reflectionTexture) {
  41598. activeTextures.push(this._reflectionTexture);
  41599. }
  41600. if (this._emissiveTexture) {
  41601. activeTextures.push(this._emissiveTexture);
  41602. }
  41603. if (this._reflectivityTexture) {
  41604. activeTextures.push(this._reflectivityTexture);
  41605. }
  41606. if (this._metallicTexture) {
  41607. activeTextures.push(this._metallicTexture);
  41608. }
  41609. if (this._microSurfaceTexture) {
  41610. activeTextures.push(this._microSurfaceTexture);
  41611. }
  41612. if (this._bumpTexture) {
  41613. activeTextures.push(this._bumpTexture);
  41614. }
  41615. if (this._lightmapTexture) {
  41616. activeTextures.push(this._lightmapTexture);
  41617. }
  41618. if (this._refractionTexture) {
  41619. activeTextures.push(this._refractionTexture);
  41620. }
  41621. return activeTextures;
  41622. };
  41623. /**
  41624. * Checks to see if a texture is used in the material.
  41625. * @param texture - Base texture to use.
  41626. * @returns - Boolean specifying if a texture is used in the material.
  41627. */
  41628. PBRMaterial.prototype.hasTexture = function (texture) {
  41629. if (_super.prototype.hasTexture.call(this, texture)) {
  41630. return true;
  41631. }
  41632. if (this._albedoTexture === texture) {
  41633. return true;
  41634. }
  41635. if (this._ambientTexture === texture) {
  41636. return true;
  41637. }
  41638. if (this._opacityTexture === texture) {
  41639. return true;
  41640. }
  41641. if (this._reflectionTexture === texture) {
  41642. return true;
  41643. }
  41644. if (this._reflectivityTexture === texture) {
  41645. return true;
  41646. }
  41647. if (this._metallicTexture === texture) {
  41648. return true;
  41649. }
  41650. if (this._microSurfaceTexture === texture) {
  41651. return true;
  41652. }
  41653. if (this._bumpTexture === texture) {
  41654. return true;
  41655. }
  41656. if (this._lightmapTexture === texture) {
  41657. return true;
  41658. }
  41659. if (this._refractionTexture === texture) {
  41660. return true;
  41661. }
  41662. return false;
  41663. };
  41664. /**
  41665. * Makes a duplicate of the current material.
  41666. * @param name - name to use for the new material.
  41667. */
  41668. PBRMaterial.prototype.clone = function (name) {
  41669. var _this = this;
  41670. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41671. clone.id = name;
  41672. clone.name = name;
  41673. return clone;
  41674. };
  41675. /**
  41676. * Serializes this PBR Material.
  41677. * @returns - An object with the serialized material.
  41678. */
  41679. PBRMaterial.prototype.serialize = function () {
  41680. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41681. serializationObject.customType = "BABYLON.PBRMaterial";
  41682. return serializationObject;
  41683. };
  41684. // Statics
  41685. /**
  41686. * Parses a PBR Material from a serialized object.
  41687. * @param source - Serialized object.
  41688. * @param scene - BJS scene instance.
  41689. * @param rootUrl - url for the scene object
  41690. * @returns - PBRMaterial
  41691. */
  41692. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41693. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41694. };
  41695. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41696. /**
  41697. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41698. */
  41699. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41700. /**
  41701. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41702. */
  41703. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41704. /**
  41705. * 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.
  41706. * They are also discarded below the alpha cutoff threshold to improve performances.
  41707. */
  41708. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41709. __decorate([
  41710. BABYLON.serialize(),
  41711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41712. ], PBRMaterial.prototype, "directIntensity", void 0);
  41713. __decorate([
  41714. BABYLON.serialize(),
  41715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41716. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41717. __decorate([
  41718. BABYLON.serialize(),
  41719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41720. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41721. __decorate([
  41722. BABYLON.serialize(),
  41723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41724. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41725. __decorate([
  41726. BABYLON.serialize(),
  41727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41728. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41729. __decorate([
  41730. BABYLON.serializeAsTexture(),
  41731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41732. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41733. __decorate([
  41734. BABYLON.serializeAsTexture(),
  41735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41736. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41737. __decorate([
  41738. BABYLON.serialize(),
  41739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41740. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41741. __decorate([
  41742. BABYLON.serializeAsTexture(),
  41743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41744. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41745. __decorate([
  41746. BABYLON.serializeAsTexture(),
  41747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41748. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41749. __decorate([
  41750. BABYLON.serializeAsTexture(),
  41751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41752. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41753. __decorate([
  41754. BABYLON.serializeAsTexture(),
  41755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41756. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41757. __decorate([
  41758. BABYLON.serializeAsTexture(),
  41759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41760. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41761. __decorate([
  41762. BABYLON.serialize(),
  41763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41764. ], PBRMaterial.prototype, "metallic", void 0);
  41765. __decorate([
  41766. BABYLON.serialize(),
  41767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41768. ], PBRMaterial.prototype, "roughness", void 0);
  41769. __decorate([
  41770. BABYLON.serializeAsTexture(),
  41771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41772. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41773. __decorate([
  41774. BABYLON.serializeAsTexture(),
  41775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41776. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41777. __decorate([
  41778. BABYLON.serializeAsTexture(),
  41779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41780. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41781. __decorate([
  41782. BABYLON.serializeAsTexture(),
  41783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41784. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41785. __decorate([
  41786. BABYLON.serializeAsColor3("ambient"),
  41787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41788. ], PBRMaterial.prototype, "ambientColor", void 0);
  41789. __decorate([
  41790. BABYLON.serializeAsColor3("albedo"),
  41791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41792. ], PBRMaterial.prototype, "albedoColor", void 0);
  41793. __decorate([
  41794. BABYLON.serializeAsColor3("reflectivity"),
  41795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41796. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41797. __decorate([
  41798. BABYLON.serializeAsColor3("reflection"),
  41799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41800. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41801. __decorate([
  41802. BABYLON.serializeAsColor3("emissive"),
  41803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41804. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41805. __decorate([
  41806. BABYLON.serialize(),
  41807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41808. ], PBRMaterial.prototype, "microSurface", void 0);
  41809. __decorate([
  41810. BABYLON.serialize(),
  41811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41812. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41813. __decorate([
  41814. BABYLON.serialize(),
  41815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41816. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41817. __decorate([
  41818. BABYLON.serialize(),
  41819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41820. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41821. __decorate([
  41822. BABYLON.serialize(),
  41823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41824. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41825. __decorate([
  41826. BABYLON.serialize(),
  41827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41828. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41829. __decorate([
  41830. BABYLON.serialize(),
  41831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41832. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41833. __decorate([
  41834. BABYLON.serialize(),
  41835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41836. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41837. __decorate([
  41838. BABYLON.serialize(),
  41839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41840. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41841. __decorate([
  41842. BABYLON.serialize(),
  41843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41844. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41845. __decorate([
  41846. BABYLON.serialize(),
  41847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41848. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41849. __decorate([
  41850. BABYLON.serialize(),
  41851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41852. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41853. __decorate([
  41854. BABYLON.serialize(),
  41855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41856. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41857. __decorate([
  41858. BABYLON.serialize(),
  41859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41860. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41861. __decorate([
  41862. BABYLON.serialize(),
  41863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41864. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41865. __decorate([
  41866. BABYLON.serialize(),
  41867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41868. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41869. __decorate([
  41870. BABYLON.serialize(),
  41871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41872. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41873. __decorate([
  41874. BABYLON.serialize(),
  41875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41876. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41877. __decorate([
  41878. BABYLON.serialize(),
  41879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41880. ], PBRMaterial.prototype, "useParallax", void 0);
  41881. __decorate([
  41882. BABYLON.serialize(),
  41883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41884. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41885. __decorate([
  41886. BABYLON.serialize(),
  41887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41888. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41889. __decorate([
  41890. BABYLON.serialize(),
  41891. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41892. ], PBRMaterial.prototype, "disableLighting", void 0);
  41893. __decorate([
  41894. BABYLON.serialize(),
  41895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41896. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41897. __decorate([
  41898. BABYLON.serialize(),
  41899. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41900. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41901. __decorate([
  41902. BABYLON.serialize(),
  41903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41904. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41905. __decorate([
  41906. BABYLON.serialize(),
  41907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41908. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41909. __decorate([
  41910. BABYLON.serialize(),
  41911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41912. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41913. __decorate([
  41914. BABYLON.serialize(),
  41915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41916. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41917. __decorate([
  41918. BABYLON.serialize(),
  41919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41920. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41921. __decorate([
  41922. BABYLON.serializeAsTexture(),
  41923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41924. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41925. __decorate([
  41926. BABYLON.serialize(),
  41927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41928. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41929. __decorate([
  41930. BABYLON.serialize(),
  41931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41932. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41933. __decorate([
  41934. BABYLON.serialize(),
  41935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41936. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41937. return PBRMaterial;
  41938. }(BABYLON.PBRBaseMaterial));
  41939. BABYLON.PBRMaterial = PBRMaterial;
  41940. })(BABYLON || (BABYLON = {}));
  41941. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41942. var BABYLON;
  41943. (function (BABYLON) {
  41944. /**
  41945. * The PBR material of BJS following the metal roughness convention.
  41946. *
  41947. * This fits to the PBR convention in the GLTF definition:
  41948. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41949. */
  41950. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41951. __extends(PBRMetallicRoughnessMaterial, _super);
  41952. /**
  41953. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41954. *
  41955. * @param name The material name
  41956. * @param scene The scene the material will be use in.
  41957. */
  41958. function PBRMetallicRoughnessMaterial(name, scene) {
  41959. var _this = _super.call(this, name, scene) || this;
  41960. _this._useRoughnessFromMetallicTextureAlpha = false;
  41961. _this._useRoughnessFromMetallicTextureGreen = true;
  41962. _this._useMetallnessFromMetallicTextureBlue = true;
  41963. _this._forceMetallicWorkflow = true;
  41964. return _this;
  41965. }
  41966. /**
  41967. * Return the currrent class name of the material.
  41968. */
  41969. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41970. return "PBRMetallicRoughnessMaterial";
  41971. };
  41972. /**
  41973. * Return the active textures of the material.
  41974. */
  41975. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41976. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41977. if (this.baseTexture) {
  41978. activeTextures.push(this.baseTexture);
  41979. }
  41980. if (this.metallicRoughnessTexture) {
  41981. activeTextures.push(this.metallicRoughnessTexture);
  41982. }
  41983. return activeTextures;
  41984. };
  41985. /**
  41986. * Checks to see if a texture is used in the material.
  41987. * @param texture - Base texture to use.
  41988. * @returns - Boolean specifying if a texture is used in the material.
  41989. */
  41990. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41991. if (_super.prototype.hasTexture.call(this, texture)) {
  41992. return true;
  41993. }
  41994. if (this.baseTexture === texture) {
  41995. return true;
  41996. }
  41997. if (this.metallicRoughnessTexture === texture) {
  41998. return true;
  41999. }
  42000. return false;
  42001. };
  42002. /**
  42003. * Makes a duplicate of the current material.
  42004. * @param name - name to use for the new material.
  42005. */
  42006. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42007. var _this = this;
  42008. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42009. clone.id = name;
  42010. clone.name = name;
  42011. return clone;
  42012. };
  42013. /**
  42014. * Serialize the material to a parsable JSON object.
  42015. */
  42016. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42017. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42018. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42019. return serializationObject;
  42020. };
  42021. /**
  42022. * Parses a JSON object correponding to the serialize function.
  42023. */
  42024. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42025. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42026. };
  42027. __decorate([
  42028. BABYLON.serializeAsColor3(),
  42029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42030. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42031. __decorate([
  42032. BABYLON.serializeAsTexture(),
  42033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42034. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42035. __decorate([
  42036. BABYLON.serialize(),
  42037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42038. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42039. __decorate([
  42040. BABYLON.serialize(),
  42041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42042. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42043. __decorate([
  42044. BABYLON.serializeAsTexture(),
  42045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42046. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42047. return PBRMetallicRoughnessMaterial;
  42048. }(BABYLON.PBRBaseSimpleMaterial));
  42049. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42050. })(BABYLON || (BABYLON = {}));
  42051. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42052. var BABYLON;
  42053. (function (BABYLON) {
  42054. /**
  42055. * The PBR material of BJS following the specular glossiness convention.
  42056. *
  42057. * This fits to the PBR convention in the GLTF definition:
  42058. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42059. */
  42060. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42061. __extends(PBRSpecularGlossinessMaterial, _super);
  42062. /**
  42063. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42064. *
  42065. * @param name The material name
  42066. * @param scene The scene the material will be use in.
  42067. */
  42068. function PBRSpecularGlossinessMaterial(name, scene) {
  42069. var _this = _super.call(this, name, scene) || this;
  42070. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42071. return _this;
  42072. }
  42073. /**
  42074. * Return the currrent class name of the material.
  42075. */
  42076. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42077. return "PBRSpecularGlossinessMaterial";
  42078. };
  42079. /**
  42080. * Return the active textures of the material.
  42081. */
  42082. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42083. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42084. if (this.diffuseTexture) {
  42085. activeTextures.push(this.diffuseTexture);
  42086. }
  42087. if (this.specularGlossinessTexture) {
  42088. activeTextures.push(this.specularGlossinessTexture);
  42089. }
  42090. return activeTextures;
  42091. };
  42092. /**
  42093. * Checks to see if a texture is used in the material.
  42094. * @param texture - Base texture to use.
  42095. * @returns - Boolean specifying if a texture is used in the material.
  42096. */
  42097. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42098. if (_super.prototype.hasTexture.call(this, texture)) {
  42099. return true;
  42100. }
  42101. if (this.diffuseTexture === texture) {
  42102. return true;
  42103. }
  42104. if (this.specularGlossinessTexture === texture) {
  42105. return true;
  42106. }
  42107. return false;
  42108. };
  42109. /**
  42110. * Makes a duplicate of the current material.
  42111. * @param name - name to use for the new material.
  42112. */
  42113. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42114. var _this = this;
  42115. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42116. clone.id = name;
  42117. clone.name = name;
  42118. return clone;
  42119. };
  42120. /**
  42121. * Serialize the material to a parsable JSON object.
  42122. */
  42123. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42124. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42125. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42126. return serializationObject;
  42127. };
  42128. /**
  42129. * Parses a JSON object correponding to the serialize function.
  42130. */
  42131. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42132. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42133. };
  42134. __decorate([
  42135. BABYLON.serializeAsColor3("diffuse"),
  42136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42137. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42138. __decorate([
  42139. BABYLON.serializeAsTexture(),
  42140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42141. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42142. __decorate([
  42143. BABYLON.serializeAsColor3("specular"),
  42144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42145. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42146. __decorate([
  42147. BABYLON.serialize(),
  42148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42149. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42150. __decorate([
  42151. BABYLON.serializeAsTexture(),
  42152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42153. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42154. return PBRSpecularGlossinessMaterial;
  42155. }(BABYLON.PBRBaseSimpleMaterial));
  42156. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42157. })(BABYLON || (BABYLON = {}));
  42158. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42159. var BABYLON;
  42160. (function (BABYLON) {
  42161. BABYLON.CameraInputTypes = {};
  42162. var CameraInputsManager = /** @class */ (function () {
  42163. function CameraInputsManager(camera) {
  42164. this.attached = {};
  42165. this.camera = camera;
  42166. this.checkInputs = function () { };
  42167. }
  42168. /**
  42169. * Add an input method to a camera.
  42170. * builtin inputs example: camera.inputs.addGamepad();
  42171. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42172. * @param input camera input method
  42173. */
  42174. CameraInputsManager.prototype.add = function (input) {
  42175. var type = input.getSimpleName();
  42176. if (this.attached[type]) {
  42177. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42178. return;
  42179. }
  42180. this.attached[type] = input;
  42181. input.camera = this.camera;
  42182. //for checkInputs, we are dynamically creating a function
  42183. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42184. if (input.checkInputs) {
  42185. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42186. }
  42187. if (this.attachedElement) {
  42188. input.attachControl(this.attachedElement);
  42189. }
  42190. };
  42191. /**
  42192. * Remove a specific input method from a camera
  42193. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42194. * @param inputToRemove camera input method
  42195. */
  42196. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42197. for (var cam in this.attached) {
  42198. var input = this.attached[cam];
  42199. if (input === inputToRemove) {
  42200. input.detachControl(this.attachedElement);
  42201. input.camera = null;
  42202. delete this.attached[cam];
  42203. this.rebuildInputCheck();
  42204. }
  42205. }
  42206. };
  42207. CameraInputsManager.prototype.removeByType = function (inputType) {
  42208. for (var cam in this.attached) {
  42209. var input = this.attached[cam];
  42210. if (input.getClassName() === inputType) {
  42211. input.detachControl(this.attachedElement);
  42212. input.camera = null;
  42213. delete this.attached[cam];
  42214. this.rebuildInputCheck();
  42215. }
  42216. }
  42217. };
  42218. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42219. var current = this.checkInputs;
  42220. return function () {
  42221. current();
  42222. fn();
  42223. };
  42224. };
  42225. CameraInputsManager.prototype.attachInput = function (input) {
  42226. if (this.attachedElement) {
  42227. input.attachControl(this.attachedElement, this.noPreventDefault);
  42228. }
  42229. };
  42230. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42231. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42232. if (this.attachedElement) {
  42233. return;
  42234. }
  42235. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42236. this.attachedElement = element;
  42237. this.noPreventDefault = noPreventDefault;
  42238. for (var cam in this.attached) {
  42239. this.attached[cam].attachControl(element, noPreventDefault);
  42240. }
  42241. };
  42242. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42243. if (disconnect === void 0) { disconnect = false; }
  42244. if (this.attachedElement !== element) {
  42245. return;
  42246. }
  42247. for (var cam in this.attached) {
  42248. this.attached[cam].detachControl(element);
  42249. if (disconnect) {
  42250. this.attached[cam].camera = null;
  42251. }
  42252. }
  42253. this.attachedElement = null;
  42254. };
  42255. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42256. this.checkInputs = function () { };
  42257. for (var cam in this.attached) {
  42258. var input = this.attached[cam];
  42259. if (input.checkInputs) {
  42260. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42261. }
  42262. }
  42263. };
  42264. /**
  42265. * Remove all attached input methods from a camera
  42266. */
  42267. CameraInputsManager.prototype.clear = function () {
  42268. if (this.attachedElement) {
  42269. this.detachElement(this.attachedElement, true);
  42270. }
  42271. this.attached = {};
  42272. this.attachedElement = null;
  42273. this.checkInputs = function () { };
  42274. };
  42275. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42276. var inputs = {};
  42277. for (var cam in this.attached) {
  42278. var input = this.attached[cam];
  42279. var res = BABYLON.SerializationHelper.Serialize(input);
  42280. inputs[input.getClassName()] = res;
  42281. }
  42282. serializedCamera.inputsmgr = inputs;
  42283. };
  42284. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42285. var parsedInputs = parsedCamera.inputsmgr;
  42286. if (parsedInputs) {
  42287. this.clear();
  42288. for (var n in parsedInputs) {
  42289. var construct = BABYLON.CameraInputTypes[n];
  42290. if (construct) {
  42291. var parsedinput = parsedInputs[n];
  42292. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42293. this.add(input);
  42294. }
  42295. }
  42296. }
  42297. else {
  42298. //2016-03-08 this part is for managing backward compatibility
  42299. for (var n in this.attached) {
  42300. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42301. if (construct) {
  42302. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42303. this.remove(this.attached[n]);
  42304. this.add(input);
  42305. }
  42306. }
  42307. }
  42308. };
  42309. return CameraInputsManager;
  42310. }());
  42311. BABYLON.CameraInputsManager = CameraInputsManager;
  42312. })(BABYLON || (BABYLON = {}));
  42313. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42314. var BABYLON;
  42315. (function (BABYLON) {
  42316. var TargetCamera = /** @class */ (function (_super) {
  42317. __extends(TargetCamera, _super);
  42318. function TargetCamera(name, position, scene) {
  42319. var _this = _super.call(this, name, position, scene) || this;
  42320. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42321. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42322. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42323. _this.speed = 2.0;
  42324. _this.noRotationConstraint = false;
  42325. _this.lockedTarget = null;
  42326. _this._currentTarget = BABYLON.Vector3.Zero();
  42327. _this._viewMatrix = BABYLON.Matrix.Zero();
  42328. _this._camMatrix = BABYLON.Matrix.Zero();
  42329. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42330. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42331. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42332. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42333. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42334. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42335. _this._tempMatrix = BABYLON.Matrix.Zero();
  42336. return _this;
  42337. }
  42338. TargetCamera.prototype.getFrontPosition = function (distance) {
  42339. this.getWorldMatrix();
  42340. var direction = this.getTarget().subtract(this.position);
  42341. direction.normalize();
  42342. direction.scaleInPlace(distance);
  42343. return this.globalPosition.add(direction);
  42344. };
  42345. TargetCamera.prototype._getLockedTargetPosition = function () {
  42346. if (!this.lockedTarget) {
  42347. return null;
  42348. }
  42349. if (this.lockedTarget.absolutePosition) {
  42350. this.lockedTarget.computeWorldMatrix();
  42351. }
  42352. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42353. };
  42354. TargetCamera.prototype.storeState = function () {
  42355. this._storedPosition = this.position.clone();
  42356. this._storedRotation = this.rotation.clone();
  42357. if (this.rotationQuaternion) {
  42358. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42359. }
  42360. return _super.prototype.storeState.call(this);
  42361. };
  42362. /**
  42363. * Restored camera state. You must call storeState() first
  42364. */
  42365. TargetCamera.prototype._restoreStateValues = function () {
  42366. if (!_super.prototype._restoreStateValues.call(this)) {
  42367. return false;
  42368. }
  42369. this.position = this._storedPosition.clone();
  42370. this.rotation = this._storedRotation.clone();
  42371. if (this.rotationQuaternion) {
  42372. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42373. }
  42374. this.cameraDirection.copyFromFloats(0, 0, 0);
  42375. this.cameraRotation.copyFromFloats(0, 0);
  42376. return true;
  42377. };
  42378. // Cache
  42379. TargetCamera.prototype._initCache = function () {
  42380. _super.prototype._initCache.call(this);
  42381. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42382. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42383. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42384. };
  42385. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42386. if (!ignoreParentClass) {
  42387. _super.prototype._updateCache.call(this);
  42388. }
  42389. var lockedTargetPosition = this._getLockedTargetPosition();
  42390. if (!lockedTargetPosition) {
  42391. this._cache.lockedTarget = null;
  42392. }
  42393. else {
  42394. if (!this._cache.lockedTarget) {
  42395. this._cache.lockedTarget = lockedTargetPosition.clone();
  42396. }
  42397. else {
  42398. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42399. }
  42400. }
  42401. this._cache.rotation.copyFrom(this.rotation);
  42402. if (this.rotationQuaternion)
  42403. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42404. };
  42405. // Synchronized
  42406. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42407. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42408. return false;
  42409. }
  42410. var lockedTargetPosition = this._getLockedTargetPosition();
  42411. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42412. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42413. };
  42414. // Methods
  42415. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42416. var engine = this.getEngine();
  42417. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42418. };
  42419. // Target
  42420. TargetCamera.prototype.setTarget = function (target) {
  42421. this.upVector.normalize();
  42422. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42423. this._camMatrix.invert();
  42424. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42425. var vDir = target.subtract(this.position);
  42426. if (vDir.x >= 0.0) {
  42427. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42428. }
  42429. else {
  42430. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42431. }
  42432. this.rotation.z = 0;
  42433. if (isNaN(this.rotation.x)) {
  42434. this.rotation.x = 0;
  42435. }
  42436. if (isNaN(this.rotation.y)) {
  42437. this.rotation.y = 0;
  42438. }
  42439. if (isNaN(this.rotation.z)) {
  42440. this.rotation.z = 0;
  42441. }
  42442. if (this.rotationQuaternion) {
  42443. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42444. }
  42445. };
  42446. /**
  42447. * Return the current target position of the camera. This value is expressed in local space.
  42448. */
  42449. TargetCamera.prototype.getTarget = function () {
  42450. return this._currentTarget;
  42451. };
  42452. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42453. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42454. };
  42455. TargetCamera.prototype._updatePosition = function () {
  42456. if (this.parent) {
  42457. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42458. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42459. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42460. return;
  42461. }
  42462. this.position.addInPlace(this.cameraDirection);
  42463. };
  42464. TargetCamera.prototype._checkInputs = function () {
  42465. var needToMove = this._decideIfNeedsToMove();
  42466. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42467. // Move
  42468. if (needToMove) {
  42469. this._updatePosition();
  42470. }
  42471. // Rotate
  42472. if (needToRotate) {
  42473. this.rotation.x += this.cameraRotation.x;
  42474. this.rotation.y += this.cameraRotation.y;
  42475. //rotate, if quaternion is set and rotation was used
  42476. if (this.rotationQuaternion) {
  42477. var len = this.rotation.lengthSquared();
  42478. if (len) {
  42479. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42480. }
  42481. }
  42482. if (!this.noRotationConstraint) {
  42483. var limit = (Math.PI / 2) * 0.95;
  42484. if (this.rotation.x > limit)
  42485. this.rotation.x = limit;
  42486. if (this.rotation.x < -limit)
  42487. this.rotation.x = -limit;
  42488. }
  42489. }
  42490. // Inertia
  42491. if (needToMove) {
  42492. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42493. this.cameraDirection.x = 0;
  42494. }
  42495. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42496. this.cameraDirection.y = 0;
  42497. }
  42498. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42499. this.cameraDirection.z = 0;
  42500. }
  42501. this.cameraDirection.scaleInPlace(this.inertia);
  42502. }
  42503. if (needToRotate) {
  42504. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42505. this.cameraRotation.x = 0;
  42506. }
  42507. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42508. this.cameraRotation.y = 0;
  42509. }
  42510. this.cameraRotation.scaleInPlace(this.inertia);
  42511. }
  42512. _super.prototype._checkInputs.call(this);
  42513. };
  42514. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42515. if (this.rotationQuaternion) {
  42516. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42517. }
  42518. else {
  42519. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42520. }
  42521. //update the up vector!
  42522. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42523. };
  42524. TargetCamera.prototype._getViewMatrix = function () {
  42525. if (this.lockedTarget) {
  42526. this.setTarget(this._getLockedTargetPosition());
  42527. }
  42528. // Compute
  42529. this._updateCameraRotationMatrix();
  42530. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42531. // Computing target and final matrix
  42532. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42533. if (this.getScene().useRightHandedSystem) {
  42534. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42535. }
  42536. else {
  42537. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42538. }
  42539. return this._viewMatrix;
  42540. };
  42541. /**
  42542. * @override
  42543. * Override Camera.createRigCamera
  42544. */
  42545. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42546. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42547. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42548. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42549. if (!this.rotationQuaternion) {
  42550. this.rotationQuaternion = new BABYLON.Quaternion();
  42551. }
  42552. rigCamera._cameraRigParams = {};
  42553. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42554. }
  42555. return rigCamera;
  42556. }
  42557. return null;
  42558. };
  42559. /**
  42560. * @override
  42561. * Override Camera._updateRigCameras
  42562. */
  42563. TargetCamera.prototype._updateRigCameras = function () {
  42564. var camLeft = this._rigCameras[0];
  42565. var camRight = this._rigCameras[1];
  42566. switch (this.cameraRigMode) {
  42567. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42568. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42569. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42570. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42571. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42572. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42573. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42574. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42575. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42576. camLeft.setTarget(this.getTarget());
  42577. camRight.setTarget(this.getTarget());
  42578. break;
  42579. case BABYLON.Camera.RIG_MODE_VR:
  42580. if (camLeft.rotationQuaternion) {
  42581. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42582. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42583. }
  42584. else {
  42585. camLeft.rotation.copyFrom(this.rotation);
  42586. camRight.rotation.copyFrom(this.rotation);
  42587. }
  42588. camLeft.position.copyFrom(this.position);
  42589. camRight.position.copyFrom(this.position);
  42590. break;
  42591. }
  42592. _super.prototype._updateRigCameras.call(this);
  42593. };
  42594. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42595. if (!this._rigCamTransformMatrix) {
  42596. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42597. }
  42598. var target = this.getTarget();
  42599. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42600. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42601. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42602. };
  42603. TargetCamera.prototype.getClassName = function () {
  42604. return "TargetCamera";
  42605. };
  42606. __decorate([
  42607. BABYLON.serializeAsVector3()
  42608. ], TargetCamera.prototype, "rotation", void 0);
  42609. __decorate([
  42610. BABYLON.serialize()
  42611. ], TargetCamera.prototype, "speed", void 0);
  42612. __decorate([
  42613. BABYLON.serializeAsMeshReference("lockedTargetId")
  42614. ], TargetCamera.prototype, "lockedTarget", void 0);
  42615. return TargetCamera;
  42616. }(BABYLON.Camera));
  42617. BABYLON.TargetCamera = TargetCamera;
  42618. })(BABYLON || (BABYLON = {}));
  42619. //# sourceMappingURL=babylon.targetCamera.js.map
  42620. var BABYLON;
  42621. (function (BABYLON) {
  42622. var FreeCameraMouseInput = /** @class */ (function () {
  42623. function FreeCameraMouseInput(touchEnabled) {
  42624. if (touchEnabled === void 0) { touchEnabled = true; }
  42625. this.touchEnabled = touchEnabled;
  42626. this.buttons = [0, 1, 2];
  42627. this.angularSensibility = 2000.0;
  42628. this.previousPosition = null;
  42629. }
  42630. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42631. var _this = this;
  42632. var engine = this.camera.getEngine();
  42633. if (!this._pointerInput) {
  42634. this._pointerInput = function (p, s) {
  42635. var evt = p.event;
  42636. if (engine.isInVRExclusivePointerMode) {
  42637. return;
  42638. }
  42639. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42640. return;
  42641. }
  42642. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42643. return;
  42644. }
  42645. var srcElement = (evt.srcElement || evt.target);
  42646. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42647. try {
  42648. srcElement.setPointerCapture(evt.pointerId);
  42649. }
  42650. catch (e) {
  42651. //Nothing to do with the error. Execution will continue.
  42652. }
  42653. _this.previousPosition = {
  42654. x: evt.clientX,
  42655. y: evt.clientY
  42656. };
  42657. if (!noPreventDefault) {
  42658. evt.preventDefault();
  42659. element.focus();
  42660. }
  42661. }
  42662. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42663. try {
  42664. srcElement.releasePointerCapture(evt.pointerId);
  42665. }
  42666. catch (e) {
  42667. //Nothing to do with the error.
  42668. }
  42669. _this.previousPosition = null;
  42670. if (!noPreventDefault) {
  42671. evt.preventDefault();
  42672. }
  42673. }
  42674. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42675. if (!_this.previousPosition || engine.isPointerLock) {
  42676. return;
  42677. }
  42678. var offsetX = evt.clientX - _this.previousPosition.x;
  42679. var offsetY = evt.clientY - _this.previousPosition.y;
  42680. if (_this.camera.getScene().useRightHandedSystem) {
  42681. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42682. }
  42683. else {
  42684. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42685. }
  42686. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42687. _this.previousPosition = {
  42688. x: evt.clientX,
  42689. y: evt.clientY
  42690. };
  42691. if (!noPreventDefault) {
  42692. evt.preventDefault();
  42693. }
  42694. }
  42695. };
  42696. }
  42697. this._onMouseMove = function (evt) {
  42698. if (!engine.isPointerLock) {
  42699. return;
  42700. }
  42701. if (engine.isInVRExclusivePointerMode) {
  42702. return;
  42703. }
  42704. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42705. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42706. if (_this.camera.getScene().useRightHandedSystem) {
  42707. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42708. }
  42709. else {
  42710. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42711. }
  42712. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42713. _this.previousPosition = null;
  42714. if (!noPreventDefault) {
  42715. evt.preventDefault();
  42716. }
  42717. };
  42718. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42719. element.addEventListener("mousemove", this._onMouseMove, false);
  42720. };
  42721. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42722. if (this._observer && element) {
  42723. this.camera.getScene().onPointerObservable.remove(this._observer);
  42724. if (this._onMouseMove) {
  42725. element.removeEventListener("mousemove", this._onMouseMove);
  42726. }
  42727. this._observer = null;
  42728. this._onMouseMove = null;
  42729. this.previousPosition = null;
  42730. }
  42731. };
  42732. FreeCameraMouseInput.prototype.getClassName = function () {
  42733. return "FreeCameraMouseInput";
  42734. };
  42735. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42736. return "mouse";
  42737. };
  42738. __decorate([
  42739. BABYLON.serialize()
  42740. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42741. __decorate([
  42742. BABYLON.serialize()
  42743. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42744. return FreeCameraMouseInput;
  42745. }());
  42746. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42747. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42748. })(BABYLON || (BABYLON = {}));
  42749. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42750. var BABYLON;
  42751. (function (BABYLON) {
  42752. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42753. function FreeCameraKeyboardMoveInput() {
  42754. this._keys = new Array();
  42755. this.keysUp = [38];
  42756. this.keysDown = [40];
  42757. this.keysLeft = [37];
  42758. this.keysRight = [39];
  42759. }
  42760. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42761. var _this = this;
  42762. if (this._onCanvasBlurObserver) {
  42763. return;
  42764. }
  42765. this._scene = this.camera.getScene();
  42766. this._engine = this._scene.getEngine();
  42767. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42768. _this._keys = [];
  42769. });
  42770. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42771. var evt = info.event;
  42772. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42773. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42774. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42775. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42776. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42777. var index = _this._keys.indexOf(evt.keyCode);
  42778. if (index === -1) {
  42779. _this._keys.push(evt.keyCode);
  42780. }
  42781. if (!noPreventDefault) {
  42782. evt.preventDefault();
  42783. }
  42784. }
  42785. }
  42786. else {
  42787. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42788. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42789. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42790. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42791. var index = _this._keys.indexOf(evt.keyCode);
  42792. if (index >= 0) {
  42793. _this._keys.splice(index, 1);
  42794. }
  42795. if (!noPreventDefault) {
  42796. evt.preventDefault();
  42797. }
  42798. }
  42799. }
  42800. });
  42801. };
  42802. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42803. if (this._scene) {
  42804. if (this._onKeyboardObserver) {
  42805. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42806. }
  42807. if (this._onCanvasBlurObserver) {
  42808. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42809. }
  42810. this._onKeyboardObserver = null;
  42811. this._onCanvasBlurObserver = null;
  42812. }
  42813. this._keys = [];
  42814. };
  42815. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42816. if (this._onKeyboardObserver) {
  42817. var camera = this.camera;
  42818. // Keyboard
  42819. for (var index = 0; index < this._keys.length; index++) {
  42820. var keyCode = this._keys[index];
  42821. var speed = camera._computeLocalCameraSpeed();
  42822. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42823. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42824. }
  42825. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42826. camera._localDirection.copyFromFloats(0, 0, speed);
  42827. }
  42828. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42829. camera._localDirection.copyFromFloats(speed, 0, 0);
  42830. }
  42831. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42832. camera._localDirection.copyFromFloats(0, 0, -speed);
  42833. }
  42834. if (camera.getScene().useRightHandedSystem) {
  42835. camera._localDirection.z *= -1;
  42836. }
  42837. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42838. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42839. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42840. }
  42841. }
  42842. };
  42843. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42844. return "FreeCameraKeyboardMoveInput";
  42845. };
  42846. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42847. this._keys = [];
  42848. };
  42849. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42850. return "keyboard";
  42851. };
  42852. __decorate([
  42853. BABYLON.serialize()
  42854. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42855. __decorate([
  42856. BABYLON.serialize()
  42857. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42858. __decorate([
  42859. BABYLON.serialize()
  42860. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42861. __decorate([
  42862. BABYLON.serialize()
  42863. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42864. return FreeCameraKeyboardMoveInput;
  42865. }());
  42866. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42867. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42868. })(BABYLON || (BABYLON = {}));
  42869. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42870. var BABYLON;
  42871. (function (BABYLON) {
  42872. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42873. __extends(FreeCameraInputsManager, _super);
  42874. function FreeCameraInputsManager(camera) {
  42875. return _super.call(this, camera) || this;
  42876. }
  42877. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42878. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42879. return this;
  42880. };
  42881. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42882. if (touchEnabled === void 0) { touchEnabled = true; }
  42883. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42884. return this;
  42885. };
  42886. FreeCameraInputsManager.prototype.addGamepad = function () {
  42887. this.add(new BABYLON.FreeCameraGamepadInput());
  42888. return this;
  42889. };
  42890. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42891. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42892. return this;
  42893. };
  42894. FreeCameraInputsManager.prototype.addTouch = function () {
  42895. this.add(new BABYLON.FreeCameraTouchInput());
  42896. return this;
  42897. };
  42898. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42899. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42900. return this;
  42901. };
  42902. return FreeCameraInputsManager;
  42903. }(BABYLON.CameraInputsManager));
  42904. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42905. })(BABYLON || (BABYLON = {}));
  42906. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42907. var BABYLON;
  42908. (function (BABYLON) {
  42909. var FreeCamera = /** @class */ (function (_super) {
  42910. __extends(FreeCamera, _super);
  42911. function FreeCamera(name, position, scene) {
  42912. var _this = _super.call(this, name, position, scene) || this;
  42913. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42914. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42915. _this.checkCollisions = false;
  42916. _this.applyGravity = false;
  42917. _this._needMoveForGravity = false;
  42918. _this._oldPosition = BABYLON.Vector3.Zero();
  42919. _this._diffPosition = BABYLON.Vector3.Zero();
  42920. _this._newPosition = BABYLON.Vector3.Zero();
  42921. // Collisions
  42922. _this._collisionMask = -1;
  42923. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42924. if (collidedMesh === void 0) { collidedMesh = null; }
  42925. //TODO move this to the collision coordinator!
  42926. if (_this.getScene().workerCollisions)
  42927. newPosition.multiplyInPlace(_this._collider._radius);
  42928. var updatePosition = function (newPos) {
  42929. _this._newPosition.copyFrom(newPos);
  42930. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42931. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42932. _this.position.addInPlace(_this._diffPosition);
  42933. if (_this.onCollide && collidedMesh) {
  42934. _this.onCollide(collidedMesh);
  42935. }
  42936. }
  42937. };
  42938. updatePosition(newPosition);
  42939. };
  42940. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42941. _this.inputs.addKeyboard().addMouse();
  42942. return _this;
  42943. }
  42944. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42945. //-- begin properties for backward compatibility for inputs
  42946. /**
  42947. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42948. * Higher values reduce sensitivity.
  42949. */
  42950. get: function () {
  42951. var mouse = this.inputs.attached["mouse"];
  42952. if (mouse)
  42953. return mouse.angularSensibility;
  42954. return 0;
  42955. },
  42956. /**
  42957. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42958. * Higher values reduce sensitivity.
  42959. */
  42960. set: function (value) {
  42961. var mouse = this.inputs.attached["mouse"];
  42962. if (mouse)
  42963. mouse.angularSensibility = value;
  42964. },
  42965. enumerable: true,
  42966. configurable: true
  42967. });
  42968. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42969. get: function () {
  42970. var keyboard = this.inputs.attached["keyboard"];
  42971. if (keyboard)
  42972. return keyboard.keysUp;
  42973. return [];
  42974. },
  42975. set: function (value) {
  42976. var keyboard = this.inputs.attached["keyboard"];
  42977. if (keyboard)
  42978. keyboard.keysUp = value;
  42979. },
  42980. enumerable: true,
  42981. configurable: true
  42982. });
  42983. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42984. get: function () {
  42985. var keyboard = this.inputs.attached["keyboard"];
  42986. if (keyboard)
  42987. return keyboard.keysDown;
  42988. return [];
  42989. },
  42990. set: function (value) {
  42991. var keyboard = this.inputs.attached["keyboard"];
  42992. if (keyboard)
  42993. keyboard.keysDown = value;
  42994. },
  42995. enumerable: true,
  42996. configurable: true
  42997. });
  42998. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42999. get: function () {
  43000. var keyboard = this.inputs.attached["keyboard"];
  43001. if (keyboard)
  43002. return keyboard.keysLeft;
  43003. return [];
  43004. },
  43005. set: function (value) {
  43006. var keyboard = this.inputs.attached["keyboard"];
  43007. if (keyboard)
  43008. keyboard.keysLeft = value;
  43009. },
  43010. enumerable: true,
  43011. configurable: true
  43012. });
  43013. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43014. get: function () {
  43015. var keyboard = this.inputs.attached["keyboard"];
  43016. if (keyboard)
  43017. return keyboard.keysRight;
  43018. return [];
  43019. },
  43020. set: function (value) {
  43021. var keyboard = this.inputs.attached["keyboard"];
  43022. if (keyboard)
  43023. keyboard.keysRight = value;
  43024. },
  43025. enumerable: true,
  43026. configurable: true
  43027. });
  43028. // Controls
  43029. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43030. this.inputs.attachElement(element, noPreventDefault);
  43031. };
  43032. FreeCamera.prototype.detachControl = function (element) {
  43033. this.inputs.detachElement(element);
  43034. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43035. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43036. };
  43037. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43038. get: function () {
  43039. return this._collisionMask;
  43040. },
  43041. set: function (mask) {
  43042. this._collisionMask = !isNaN(mask) ? mask : -1;
  43043. },
  43044. enumerable: true,
  43045. configurable: true
  43046. });
  43047. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43048. var globalPosition;
  43049. if (this.parent) {
  43050. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43051. }
  43052. else {
  43053. globalPosition = this.position;
  43054. }
  43055. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43056. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43057. if (!this._collider) {
  43058. this._collider = new BABYLON.Collider();
  43059. }
  43060. this._collider._radius = this.ellipsoid;
  43061. this._collider.collisionMask = this._collisionMask;
  43062. //no need for clone, as long as gravity is not on.
  43063. var actualDisplacement = displacement;
  43064. //add gravity to the direction to prevent the dual-collision checking
  43065. if (this.applyGravity) {
  43066. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43067. actualDisplacement = displacement.add(this.getScene().gravity);
  43068. }
  43069. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43070. };
  43071. FreeCamera.prototype._checkInputs = function () {
  43072. if (!this._localDirection) {
  43073. this._localDirection = BABYLON.Vector3.Zero();
  43074. this._transformedDirection = BABYLON.Vector3.Zero();
  43075. }
  43076. this.inputs.checkInputs();
  43077. _super.prototype._checkInputs.call(this);
  43078. };
  43079. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43080. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43081. };
  43082. FreeCamera.prototype._updatePosition = function () {
  43083. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43084. this._collideWithWorld(this.cameraDirection);
  43085. }
  43086. else {
  43087. _super.prototype._updatePosition.call(this);
  43088. }
  43089. };
  43090. FreeCamera.prototype.dispose = function () {
  43091. this.inputs.clear();
  43092. _super.prototype.dispose.call(this);
  43093. };
  43094. FreeCamera.prototype.getClassName = function () {
  43095. return "FreeCamera";
  43096. };
  43097. __decorate([
  43098. BABYLON.serializeAsVector3()
  43099. ], FreeCamera.prototype, "ellipsoid", void 0);
  43100. __decorate([
  43101. BABYLON.serializeAsVector3()
  43102. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43103. __decorate([
  43104. BABYLON.serialize()
  43105. ], FreeCamera.prototype, "checkCollisions", void 0);
  43106. __decorate([
  43107. BABYLON.serialize()
  43108. ], FreeCamera.prototype, "applyGravity", void 0);
  43109. return FreeCamera;
  43110. }(BABYLON.TargetCamera));
  43111. BABYLON.FreeCamera = FreeCamera;
  43112. })(BABYLON || (BABYLON = {}));
  43113. //# sourceMappingURL=babylon.freeCamera.js.map
  43114. var BABYLON;
  43115. (function (BABYLON) {
  43116. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43117. function ArcRotateCameraKeyboardMoveInput() {
  43118. this._keys = new Array();
  43119. this.keysUp = [38];
  43120. this.keysDown = [40];
  43121. this.keysLeft = [37];
  43122. this.keysRight = [39];
  43123. this.keysReset = [220];
  43124. this.panningSensibility = 50.0;
  43125. this.zoomingSensibility = 25.0;
  43126. this.useAltToZoom = true;
  43127. }
  43128. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43129. var _this = this;
  43130. if (this._onCanvasBlurObserver) {
  43131. return;
  43132. }
  43133. this._scene = this.camera.getScene();
  43134. this._engine = this._scene.getEngine();
  43135. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43136. _this._keys = [];
  43137. });
  43138. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43139. var evt = info.event;
  43140. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43141. _this._ctrlPressed = evt.ctrlKey;
  43142. _this._altPressed = evt.altKey;
  43143. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43144. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43145. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43146. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43147. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43148. var index = _this._keys.indexOf(evt.keyCode);
  43149. if (index === -1) {
  43150. _this._keys.push(evt.keyCode);
  43151. }
  43152. if (evt.preventDefault) {
  43153. if (!noPreventDefault) {
  43154. evt.preventDefault();
  43155. }
  43156. }
  43157. }
  43158. }
  43159. else {
  43160. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43161. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43162. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43163. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43164. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43165. var index = _this._keys.indexOf(evt.keyCode);
  43166. if (index >= 0) {
  43167. _this._keys.splice(index, 1);
  43168. }
  43169. if (evt.preventDefault) {
  43170. if (!noPreventDefault) {
  43171. evt.preventDefault();
  43172. }
  43173. }
  43174. }
  43175. }
  43176. });
  43177. };
  43178. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43179. if (this._scene) {
  43180. if (this._onKeyboardObserver) {
  43181. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43182. }
  43183. if (this._onCanvasBlurObserver) {
  43184. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43185. }
  43186. this._onKeyboardObserver = null;
  43187. this._onCanvasBlurObserver = null;
  43188. }
  43189. this._keys = [];
  43190. };
  43191. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43192. if (this._onKeyboardObserver) {
  43193. var camera = this.camera;
  43194. for (var index = 0; index < this._keys.length; index++) {
  43195. var keyCode = this._keys[index];
  43196. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43197. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43198. camera.inertialPanningX -= 1 / this.panningSensibility;
  43199. }
  43200. else {
  43201. camera.inertialAlphaOffset -= 0.01;
  43202. }
  43203. }
  43204. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43205. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43206. camera.inertialPanningY += 1 / this.panningSensibility;
  43207. }
  43208. else if (this._altPressed && this.useAltToZoom) {
  43209. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43210. }
  43211. else {
  43212. camera.inertialBetaOffset -= 0.01;
  43213. }
  43214. }
  43215. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43216. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43217. camera.inertialPanningX += 1 / this.panningSensibility;
  43218. }
  43219. else {
  43220. camera.inertialAlphaOffset += 0.01;
  43221. }
  43222. }
  43223. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43224. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43225. camera.inertialPanningY -= 1 / this.panningSensibility;
  43226. }
  43227. else if (this._altPressed && this.useAltToZoom) {
  43228. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43229. }
  43230. else {
  43231. camera.inertialBetaOffset += 0.01;
  43232. }
  43233. }
  43234. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43235. camera.restoreState();
  43236. }
  43237. }
  43238. }
  43239. };
  43240. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43241. return "ArcRotateCameraKeyboardMoveInput";
  43242. };
  43243. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43244. return "keyboard";
  43245. };
  43246. __decorate([
  43247. BABYLON.serialize()
  43248. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43249. __decorate([
  43250. BABYLON.serialize()
  43251. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43252. __decorate([
  43253. BABYLON.serialize()
  43254. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43255. __decorate([
  43256. BABYLON.serialize()
  43257. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43258. __decorate([
  43259. BABYLON.serialize()
  43260. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43261. __decorate([
  43262. BABYLON.serialize()
  43263. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43264. __decorate([
  43265. BABYLON.serialize()
  43266. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43267. __decorate([
  43268. BABYLON.serialize()
  43269. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43270. return ArcRotateCameraKeyboardMoveInput;
  43271. }());
  43272. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43273. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43274. })(BABYLON || (BABYLON = {}));
  43275. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43276. var BABYLON;
  43277. (function (BABYLON) {
  43278. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43279. function ArcRotateCameraMouseWheelInput() {
  43280. this.wheelPrecision = 3.0;
  43281. /**
  43282. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43283. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43284. */
  43285. this.wheelDeltaPercentage = 0;
  43286. }
  43287. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43288. var _this = this;
  43289. this._wheel = function (p, s) {
  43290. //sanity check - this should be a PointerWheel event.
  43291. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43292. return;
  43293. var event = p.event;
  43294. var delta = 0;
  43295. if (event.wheelDelta) {
  43296. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43297. }
  43298. else if (event.detail) {
  43299. delta = -event.detail / _this.wheelPrecision;
  43300. }
  43301. if (delta)
  43302. _this.camera.inertialRadiusOffset += delta;
  43303. if (event.preventDefault) {
  43304. if (!noPreventDefault) {
  43305. event.preventDefault();
  43306. }
  43307. }
  43308. };
  43309. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43310. };
  43311. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43312. if (this._observer && element) {
  43313. this.camera.getScene().onPointerObservable.remove(this._observer);
  43314. this._observer = null;
  43315. this._wheel = null;
  43316. }
  43317. };
  43318. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43319. return "ArcRotateCameraMouseWheelInput";
  43320. };
  43321. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43322. return "mousewheel";
  43323. };
  43324. __decorate([
  43325. BABYLON.serialize()
  43326. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43327. __decorate([
  43328. BABYLON.serialize()
  43329. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43330. return ArcRotateCameraMouseWheelInput;
  43331. }());
  43332. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43333. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43334. })(BABYLON || (BABYLON = {}));
  43335. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43336. var BABYLON;
  43337. (function (BABYLON) {
  43338. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43339. function ArcRotateCameraPointersInput() {
  43340. this.buttons = [0, 1, 2];
  43341. this.angularSensibilityX = 1000.0;
  43342. this.angularSensibilityY = 1000.0;
  43343. this.pinchPrecision = 12.0;
  43344. /**
  43345. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43346. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43347. */
  43348. this.pinchDeltaPercentage = 0;
  43349. this.panningSensibility = 1000.0;
  43350. this.multiTouchPanning = true;
  43351. this.multiTouchPanAndZoom = true;
  43352. this._isPanClick = false;
  43353. this.pinchInwards = true;
  43354. }
  43355. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43356. var _this = this;
  43357. var engine = this.camera.getEngine();
  43358. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43359. var pointA = null;
  43360. var pointB = null;
  43361. var previousPinchSquaredDistance = 0;
  43362. var initialDistance = 0;
  43363. var twoFingerActivityCount = 0;
  43364. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43365. this._pointerInput = function (p, s) {
  43366. var evt = p.event;
  43367. var isTouch = p.event.pointerType === "touch";
  43368. if (engine.isInVRExclusivePointerMode) {
  43369. return;
  43370. }
  43371. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43372. return;
  43373. }
  43374. var srcElement = (evt.srcElement || evt.target);
  43375. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43376. try {
  43377. srcElement.setPointerCapture(evt.pointerId);
  43378. }
  43379. catch (e) {
  43380. //Nothing to do with the error. Execution will continue.
  43381. }
  43382. // Manage panning with pan button click
  43383. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43384. // manage pointers
  43385. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43386. if (pointA === null) {
  43387. pointA = cacheSoloPointer;
  43388. }
  43389. else if (pointB === null) {
  43390. pointB = cacheSoloPointer;
  43391. }
  43392. if (!noPreventDefault) {
  43393. evt.preventDefault();
  43394. element.focus();
  43395. }
  43396. }
  43397. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43398. _this.camera.restoreState();
  43399. }
  43400. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43401. try {
  43402. srcElement.releasePointerCapture(evt.pointerId);
  43403. }
  43404. catch (e) {
  43405. //Nothing to do with the error.
  43406. }
  43407. cacheSoloPointer = null;
  43408. previousPinchSquaredDistance = 0;
  43409. previousMultiTouchPanPosition.isPaning = false;
  43410. previousMultiTouchPanPosition.isPinching = false;
  43411. twoFingerActivityCount = 0;
  43412. initialDistance = 0;
  43413. if (!isTouch) {
  43414. pointB = null; // Mouse and pen are mono pointer
  43415. }
  43416. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43417. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43418. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43419. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43420. if (engine.badOS) {
  43421. pointA = pointB = null;
  43422. }
  43423. else {
  43424. //only remove the impacted pointer in case of multitouch allowing on most
  43425. //platforms switching from rotate to zoom and pan seamlessly.
  43426. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43427. pointA = pointB;
  43428. pointB = null;
  43429. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43430. }
  43431. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43432. pointB = null;
  43433. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43434. }
  43435. else {
  43436. pointA = pointB = null;
  43437. }
  43438. }
  43439. if (!noPreventDefault) {
  43440. evt.preventDefault();
  43441. }
  43442. }
  43443. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43444. if (!noPreventDefault) {
  43445. evt.preventDefault();
  43446. }
  43447. // One button down
  43448. if (pointA && pointB === null && cacheSoloPointer) {
  43449. if (_this.panningSensibility !== 0 &&
  43450. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43451. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43452. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43453. }
  43454. else {
  43455. var offsetX = evt.clientX - cacheSoloPointer.x;
  43456. var offsetY = evt.clientY - cacheSoloPointer.y;
  43457. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43458. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43459. }
  43460. cacheSoloPointer.x = evt.clientX;
  43461. cacheSoloPointer.y = evt.clientY;
  43462. }
  43463. else if (pointA && pointB) {
  43464. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43465. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43466. ed.x = evt.clientX;
  43467. ed.y = evt.clientY;
  43468. var direction = _this.pinchInwards ? 1 : -1;
  43469. var distX = pointA.x - pointB.x;
  43470. var distY = pointA.y - pointB.y;
  43471. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43472. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43473. if (previousPinchSquaredDistance === 0) {
  43474. initialDistance = pinchDistance;
  43475. previousPinchSquaredDistance = pinchSquaredDistance;
  43476. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43477. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43478. return;
  43479. }
  43480. if (_this.multiTouchPanAndZoom) {
  43481. if (_this.pinchDeltaPercentage) {
  43482. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43483. }
  43484. else {
  43485. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43486. (_this.pinchPrecision *
  43487. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43488. direction);
  43489. }
  43490. if (_this.panningSensibility !== 0) {
  43491. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43492. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43493. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43494. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43495. previousMultiTouchPanPosition.x = pointersCenterX;
  43496. previousMultiTouchPanPosition.y = pointersCenterY;
  43497. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43498. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43499. }
  43500. }
  43501. else {
  43502. twoFingerActivityCount++;
  43503. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43504. if (_this.pinchDeltaPercentage) {
  43505. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43506. }
  43507. else {
  43508. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43509. (_this.pinchPrecision *
  43510. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43511. direction);
  43512. }
  43513. previousMultiTouchPanPosition.isPaning = false;
  43514. previousMultiTouchPanPosition.isPinching = true;
  43515. }
  43516. else {
  43517. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43518. if (!previousMultiTouchPanPosition.isPaning) {
  43519. previousMultiTouchPanPosition.isPaning = true;
  43520. previousMultiTouchPanPosition.isPinching = false;
  43521. previousMultiTouchPanPosition.x = ed.x;
  43522. previousMultiTouchPanPosition.y = ed.y;
  43523. return;
  43524. }
  43525. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43526. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43527. }
  43528. }
  43529. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43530. previousMultiTouchPanPosition.x = ed.x;
  43531. previousMultiTouchPanPosition.y = ed.y;
  43532. }
  43533. }
  43534. previousPinchSquaredDistance = pinchSquaredDistance;
  43535. }
  43536. }
  43537. };
  43538. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43539. this._onContextMenu = function (evt) {
  43540. evt.preventDefault();
  43541. };
  43542. if (!this.camera._useCtrlForPanning) {
  43543. element.addEventListener("contextmenu", this._onContextMenu, false);
  43544. }
  43545. this._onLostFocus = function () {
  43546. //this._keys = [];
  43547. pointA = pointB = null;
  43548. previousPinchSquaredDistance = 0;
  43549. previousMultiTouchPanPosition.isPaning = false;
  43550. previousMultiTouchPanPosition.isPinching = false;
  43551. twoFingerActivityCount = 0;
  43552. cacheSoloPointer = null;
  43553. initialDistance = 0;
  43554. };
  43555. this._onMouseMove = function (evt) {
  43556. if (!engine.isPointerLock) {
  43557. return;
  43558. }
  43559. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43560. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43561. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43562. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43563. if (!noPreventDefault) {
  43564. evt.preventDefault();
  43565. }
  43566. };
  43567. this._onGestureStart = function (e) {
  43568. if (window.MSGesture === undefined) {
  43569. return;
  43570. }
  43571. if (!_this._MSGestureHandler) {
  43572. _this._MSGestureHandler = new MSGesture();
  43573. _this._MSGestureHandler.target = element;
  43574. }
  43575. _this._MSGestureHandler.addPointer(e.pointerId);
  43576. };
  43577. this._onGesture = function (e) {
  43578. _this.camera.radius *= e.scale;
  43579. if (e.preventDefault) {
  43580. if (!noPreventDefault) {
  43581. e.stopPropagation();
  43582. e.preventDefault();
  43583. }
  43584. }
  43585. };
  43586. element.addEventListener("mousemove", this._onMouseMove, false);
  43587. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43588. element.addEventListener("MSGestureChange", this._onGesture, false);
  43589. BABYLON.Tools.RegisterTopRootEvents([
  43590. { name: "blur", handler: this._onLostFocus }
  43591. ]);
  43592. };
  43593. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43594. if (this._onLostFocus) {
  43595. BABYLON.Tools.UnregisterTopRootEvents([
  43596. { name: "blur", handler: this._onLostFocus }
  43597. ]);
  43598. }
  43599. if (element && this._observer) {
  43600. this.camera.getScene().onPointerObservable.remove(this._observer);
  43601. this._observer = null;
  43602. if (this._onContextMenu) {
  43603. element.removeEventListener("contextmenu", this._onContextMenu);
  43604. }
  43605. if (this._onMouseMove) {
  43606. element.removeEventListener("mousemove", this._onMouseMove);
  43607. }
  43608. if (this._onGestureStart) {
  43609. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43610. }
  43611. if (this._onGesture) {
  43612. element.removeEventListener("MSGestureChange", this._onGesture);
  43613. }
  43614. this._isPanClick = false;
  43615. this.pinchInwards = true;
  43616. this._onMouseMove = null;
  43617. this._onGestureStart = null;
  43618. this._onGesture = null;
  43619. this._MSGestureHandler = null;
  43620. this._onLostFocus = null;
  43621. this._onContextMenu = null;
  43622. }
  43623. };
  43624. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43625. return "ArcRotateCameraPointersInput";
  43626. };
  43627. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43628. return "pointers";
  43629. };
  43630. __decorate([
  43631. BABYLON.serialize()
  43632. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43633. __decorate([
  43634. BABYLON.serialize()
  43635. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43636. __decorate([
  43637. BABYLON.serialize()
  43638. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43639. __decorate([
  43640. BABYLON.serialize()
  43641. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43642. __decorate([
  43643. BABYLON.serialize()
  43644. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43645. __decorate([
  43646. BABYLON.serialize()
  43647. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43648. __decorate([
  43649. BABYLON.serialize()
  43650. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43651. __decorate([
  43652. BABYLON.serialize()
  43653. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43654. return ArcRotateCameraPointersInput;
  43655. }());
  43656. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43657. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43658. })(BABYLON || (BABYLON = {}));
  43659. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43660. var BABYLON;
  43661. (function (BABYLON) {
  43662. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43663. __extends(ArcRotateCameraInputsManager, _super);
  43664. function ArcRotateCameraInputsManager(camera) {
  43665. return _super.call(this, camera) || this;
  43666. }
  43667. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43668. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43669. return this;
  43670. };
  43671. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43672. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43673. return this;
  43674. };
  43675. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43676. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43677. return this;
  43678. };
  43679. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43680. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43681. return this;
  43682. };
  43683. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43684. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43685. return this;
  43686. };
  43687. return ArcRotateCameraInputsManager;
  43688. }(BABYLON.CameraInputsManager));
  43689. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43690. })(BABYLON || (BABYLON = {}));
  43691. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43692. var BABYLON;
  43693. (function (BABYLON) {
  43694. var ArcRotateCamera = /** @class */ (function (_super) {
  43695. __extends(ArcRotateCamera, _super);
  43696. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43697. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43698. _this.inertialAlphaOffset = 0;
  43699. _this.inertialBetaOffset = 0;
  43700. _this.inertialRadiusOffset = 0;
  43701. _this.lowerAlphaLimit = null;
  43702. _this.upperAlphaLimit = null;
  43703. _this.lowerBetaLimit = 0.01;
  43704. _this.upperBetaLimit = Math.PI;
  43705. _this.lowerRadiusLimit = null;
  43706. _this.upperRadiusLimit = null;
  43707. _this.inertialPanningX = 0;
  43708. _this.inertialPanningY = 0;
  43709. _this.pinchToPanMaxDistance = 20;
  43710. _this.panningDistanceLimit = null;
  43711. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43712. _this.panningInertia = 0.9;
  43713. //-- end properties for backward compatibility for inputs
  43714. _this.zoomOnFactor = 1;
  43715. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43716. _this.allowUpsideDown = true;
  43717. _this._viewMatrix = new BABYLON.Matrix();
  43718. // Panning
  43719. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43720. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43721. _this.checkCollisions = false;
  43722. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43723. _this._previousPosition = BABYLON.Vector3.Zero();
  43724. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43725. _this._newPosition = BABYLON.Vector3.Zero();
  43726. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43727. if (collidedMesh === void 0) { collidedMesh = null; }
  43728. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43729. newPosition.multiplyInPlace(_this._collider._radius);
  43730. }
  43731. if (!collidedMesh) {
  43732. _this._previousPosition.copyFrom(_this.position);
  43733. }
  43734. else {
  43735. _this.setPosition(newPosition);
  43736. if (_this.onCollide) {
  43737. _this.onCollide(collidedMesh);
  43738. }
  43739. }
  43740. // Recompute because of constraints
  43741. var cosa = Math.cos(_this.alpha);
  43742. var sina = Math.sin(_this.alpha);
  43743. var cosb = Math.cos(_this.beta);
  43744. var sinb = Math.sin(_this.beta);
  43745. if (sinb === 0) {
  43746. sinb = 0.0001;
  43747. }
  43748. var target = _this._getTargetPosition();
  43749. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43750. _this.position.copyFrom(_this._newPosition);
  43751. var up = _this.upVector;
  43752. if (_this.allowUpsideDown && _this.beta < 0) {
  43753. up = up.clone();
  43754. up = up.negate();
  43755. }
  43756. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43757. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43758. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43759. _this._collisionTriggered = false;
  43760. };
  43761. _this._target = BABYLON.Vector3.Zero();
  43762. if (target) {
  43763. _this.setTarget(target);
  43764. }
  43765. _this.alpha = alpha;
  43766. _this.beta = beta;
  43767. _this.radius = radius;
  43768. _this.getViewMatrix();
  43769. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43770. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43771. return _this;
  43772. }
  43773. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43774. get: function () {
  43775. return this._target;
  43776. },
  43777. set: function (value) {
  43778. this.setTarget(value);
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43784. //-- begin properties for backward compatibility for inputs
  43785. get: function () {
  43786. var pointers = this.inputs.attached["pointers"];
  43787. if (pointers)
  43788. return pointers.angularSensibilityX;
  43789. return 0;
  43790. },
  43791. set: function (value) {
  43792. var pointers = this.inputs.attached["pointers"];
  43793. if (pointers) {
  43794. pointers.angularSensibilityX = value;
  43795. }
  43796. },
  43797. enumerable: true,
  43798. configurable: true
  43799. });
  43800. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43801. get: function () {
  43802. var pointers = this.inputs.attached["pointers"];
  43803. if (pointers)
  43804. return pointers.angularSensibilityY;
  43805. return 0;
  43806. },
  43807. set: function (value) {
  43808. var pointers = this.inputs.attached["pointers"];
  43809. if (pointers) {
  43810. pointers.angularSensibilityY = value;
  43811. }
  43812. },
  43813. enumerable: true,
  43814. configurable: true
  43815. });
  43816. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43817. get: function () {
  43818. var pointers = this.inputs.attached["pointers"];
  43819. if (pointers)
  43820. return pointers.pinchPrecision;
  43821. return 0;
  43822. },
  43823. set: function (value) {
  43824. var pointers = this.inputs.attached["pointers"];
  43825. if (pointers) {
  43826. pointers.pinchPrecision = value;
  43827. }
  43828. },
  43829. enumerable: true,
  43830. configurable: true
  43831. });
  43832. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43833. get: function () {
  43834. var pointers = this.inputs.attached["pointers"];
  43835. if (pointers)
  43836. return pointers.pinchDeltaPercentage;
  43837. return 0;
  43838. },
  43839. set: function (value) {
  43840. var pointers = this.inputs.attached["pointers"];
  43841. if (pointers) {
  43842. pointers.pinchDeltaPercentage = value;
  43843. }
  43844. },
  43845. enumerable: true,
  43846. configurable: true
  43847. });
  43848. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43849. get: function () {
  43850. var pointers = this.inputs.attached["pointers"];
  43851. if (pointers)
  43852. return pointers.panningSensibility;
  43853. return 0;
  43854. },
  43855. set: function (value) {
  43856. var pointers = this.inputs.attached["pointers"];
  43857. if (pointers) {
  43858. pointers.panningSensibility = value;
  43859. }
  43860. },
  43861. enumerable: true,
  43862. configurable: true
  43863. });
  43864. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43865. get: function () {
  43866. var keyboard = this.inputs.attached["keyboard"];
  43867. if (keyboard)
  43868. return keyboard.keysUp;
  43869. return [];
  43870. },
  43871. set: function (value) {
  43872. var keyboard = this.inputs.attached["keyboard"];
  43873. if (keyboard)
  43874. keyboard.keysUp = value;
  43875. },
  43876. enumerable: true,
  43877. configurable: true
  43878. });
  43879. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43880. get: function () {
  43881. var keyboard = this.inputs.attached["keyboard"];
  43882. if (keyboard)
  43883. return keyboard.keysDown;
  43884. return [];
  43885. },
  43886. set: function (value) {
  43887. var keyboard = this.inputs.attached["keyboard"];
  43888. if (keyboard)
  43889. keyboard.keysDown = value;
  43890. },
  43891. enumerable: true,
  43892. configurable: true
  43893. });
  43894. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43895. get: function () {
  43896. var keyboard = this.inputs.attached["keyboard"];
  43897. if (keyboard)
  43898. return keyboard.keysLeft;
  43899. return [];
  43900. },
  43901. set: function (value) {
  43902. var keyboard = this.inputs.attached["keyboard"];
  43903. if (keyboard)
  43904. keyboard.keysLeft = value;
  43905. },
  43906. enumerable: true,
  43907. configurable: true
  43908. });
  43909. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43910. get: function () {
  43911. var keyboard = this.inputs.attached["keyboard"];
  43912. if (keyboard)
  43913. return keyboard.keysRight;
  43914. return [];
  43915. },
  43916. set: function (value) {
  43917. var keyboard = this.inputs.attached["keyboard"];
  43918. if (keyboard)
  43919. keyboard.keysRight = value;
  43920. },
  43921. enumerable: true,
  43922. configurable: true
  43923. });
  43924. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43925. get: function () {
  43926. var mousewheel = this.inputs.attached["mousewheel"];
  43927. if (mousewheel)
  43928. return mousewheel.wheelPrecision;
  43929. return 0;
  43930. },
  43931. set: function (value) {
  43932. var mousewheel = this.inputs.attached["mousewheel"];
  43933. if (mousewheel)
  43934. mousewheel.wheelPrecision = value;
  43935. },
  43936. enumerable: true,
  43937. configurable: true
  43938. });
  43939. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43940. get: function () {
  43941. var mousewheel = this.inputs.attached["mousewheel"];
  43942. if (mousewheel)
  43943. return mousewheel.wheelDeltaPercentage;
  43944. return 0;
  43945. },
  43946. set: function (value) {
  43947. var mousewheel = this.inputs.attached["mousewheel"];
  43948. if (mousewheel)
  43949. mousewheel.wheelDeltaPercentage = value;
  43950. },
  43951. enumerable: true,
  43952. configurable: true
  43953. });
  43954. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43955. get: function () {
  43956. return this._bouncingBehavior;
  43957. },
  43958. enumerable: true,
  43959. configurable: true
  43960. });
  43961. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43962. get: function () {
  43963. return this._bouncingBehavior != null;
  43964. },
  43965. set: function (value) {
  43966. if (value === this.useBouncingBehavior) {
  43967. return;
  43968. }
  43969. if (value) {
  43970. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43971. this.addBehavior(this._bouncingBehavior);
  43972. }
  43973. else if (this._bouncingBehavior) {
  43974. this.removeBehavior(this._bouncingBehavior);
  43975. this._bouncingBehavior = null;
  43976. }
  43977. },
  43978. enumerable: true,
  43979. configurable: true
  43980. });
  43981. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43982. get: function () {
  43983. return this._framingBehavior;
  43984. },
  43985. enumerable: true,
  43986. configurable: true
  43987. });
  43988. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43989. get: function () {
  43990. return this._framingBehavior != null;
  43991. },
  43992. set: function (value) {
  43993. if (value === this.useFramingBehavior) {
  43994. return;
  43995. }
  43996. if (value) {
  43997. this._framingBehavior = new BABYLON.FramingBehavior();
  43998. this.addBehavior(this._framingBehavior);
  43999. }
  44000. else if (this._framingBehavior) {
  44001. this.removeBehavior(this._framingBehavior);
  44002. this._framingBehavior = null;
  44003. }
  44004. },
  44005. enumerable: true,
  44006. configurable: true
  44007. });
  44008. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44009. get: function () {
  44010. return this._autoRotationBehavior;
  44011. },
  44012. enumerable: true,
  44013. configurable: true
  44014. });
  44015. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44016. get: function () {
  44017. return this._autoRotationBehavior != null;
  44018. },
  44019. set: function (value) {
  44020. if (value === this.useAutoRotationBehavior) {
  44021. return;
  44022. }
  44023. if (value) {
  44024. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44025. this.addBehavior(this._autoRotationBehavior);
  44026. }
  44027. else if (this._autoRotationBehavior) {
  44028. this.removeBehavior(this._autoRotationBehavior);
  44029. this._autoRotationBehavior = null;
  44030. }
  44031. },
  44032. enumerable: true,
  44033. configurable: true
  44034. });
  44035. // Cache
  44036. ArcRotateCamera.prototype._initCache = function () {
  44037. _super.prototype._initCache.call(this);
  44038. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44039. this._cache.alpha = undefined;
  44040. this._cache.beta = undefined;
  44041. this._cache.radius = undefined;
  44042. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44043. };
  44044. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44045. if (!ignoreParentClass) {
  44046. _super.prototype._updateCache.call(this);
  44047. }
  44048. this._cache._target.copyFrom(this._getTargetPosition());
  44049. this._cache.alpha = this.alpha;
  44050. this._cache.beta = this.beta;
  44051. this._cache.radius = this.radius;
  44052. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44053. };
  44054. ArcRotateCamera.prototype._getTargetPosition = function () {
  44055. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44056. var pos = this._targetHost.getAbsolutePosition();
  44057. if (this._targetBoundingCenter) {
  44058. pos.addToRef(this._targetBoundingCenter, this._target);
  44059. }
  44060. else {
  44061. this._target.copyFrom(pos);
  44062. }
  44063. }
  44064. var lockedTargetPosition = this._getLockedTargetPosition();
  44065. if (lockedTargetPosition) {
  44066. return lockedTargetPosition;
  44067. }
  44068. return this._target;
  44069. };
  44070. ArcRotateCamera.prototype.storeState = function () {
  44071. this._storedAlpha = this.alpha;
  44072. this._storedBeta = this.beta;
  44073. this._storedRadius = this.radius;
  44074. this._storedTarget = this._getTargetPosition().clone();
  44075. return _super.prototype.storeState.call(this);
  44076. };
  44077. /**
  44078. * Restored camera state. You must call storeState() first
  44079. */
  44080. ArcRotateCamera.prototype._restoreStateValues = function () {
  44081. if (!_super.prototype._restoreStateValues.call(this)) {
  44082. return false;
  44083. }
  44084. this.alpha = this._storedAlpha;
  44085. this.beta = this._storedBeta;
  44086. this.radius = this._storedRadius;
  44087. this.setTarget(this._storedTarget.clone());
  44088. this.inertialAlphaOffset = 0;
  44089. this.inertialBetaOffset = 0;
  44090. this.inertialRadiusOffset = 0;
  44091. this.inertialPanningX = 0;
  44092. this.inertialPanningY = 0;
  44093. return true;
  44094. };
  44095. // Synchronized
  44096. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44097. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44098. return false;
  44099. return this._cache._target.equals(this._getTargetPosition())
  44100. && this._cache.alpha === this.alpha
  44101. && this._cache.beta === this.beta
  44102. && this._cache.radius === this.radius
  44103. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44104. };
  44105. // Methods
  44106. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44107. var _this = this;
  44108. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44109. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44110. this._useCtrlForPanning = useCtrlForPanning;
  44111. this._panningMouseButton = panningMouseButton;
  44112. this.inputs.attachElement(element, noPreventDefault);
  44113. this._reset = function () {
  44114. _this.inertialAlphaOffset = 0;
  44115. _this.inertialBetaOffset = 0;
  44116. _this.inertialRadiusOffset = 0;
  44117. _this.inertialPanningX = 0;
  44118. _this.inertialPanningY = 0;
  44119. };
  44120. };
  44121. ArcRotateCamera.prototype.detachControl = function (element) {
  44122. this.inputs.detachElement(element);
  44123. if (this._reset) {
  44124. this._reset();
  44125. }
  44126. };
  44127. ArcRotateCamera.prototype._checkInputs = function () {
  44128. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44129. if (this._collisionTriggered) {
  44130. return;
  44131. }
  44132. this.inputs.checkInputs();
  44133. // Inertia
  44134. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44135. if (this.getScene().useRightHandedSystem) {
  44136. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44137. }
  44138. else {
  44139. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44140. }
  44141. this.beta += this.inertialBetaOffset;
  44142. this.radius -= this.inertialRadiusOffset;
  44143. this.inertialAlphaOffset *= this.inertia;
  44144. this.inertialBetaOffset *= this.inertia;
  44145. this.inertialRadiusOffset *= this.inertia;
  44146. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44147. this.inertialAlphaOffset = 0;
  44148. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44149. this.inertialBetaOffset = 0;
  44150. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44151. this.inertialRadiusOffset = 0;
  44152. }
  44153. // Panning inertia
  44154. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44155. if (!this._localDirection) {
  44156. this._localDirection = BABYLON.Vector3.Zero();
  44157. this._transformedDirection = BABYLON.Vector3.Zero();
  44158. }
  44159. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44160. this._localDirection.multiplyInPlace(this.panningAxis);
  44161. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44162. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44163. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44164. if (!this.panningAxis.y) {
  44165. this._transformedDirection.y = 0;
  44166. }
  44167. if (!this._targetHost) {
  44168. if (this.panningDistanceLimit) {
  44169. this._transformedDirection.addInPlace(this._target);
  44170. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44171. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44172. this._target.copyFrom(this._transformedDirection);
  44173. }
  44174. }
  44175. else {
  44176. this._target.addInPlace(this._transformedDirection);
  44177. }
  44178. }
  44179. this.inertialPanningX *= this.panningInertia;
  44180. this.inertialPanningY *= this.panningInertia;
  44181. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44182. this.inertialPanningX = 0;
  44183. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44184. this.inertialPanningY = 0;
  44185. }
  44186. // Limits
  44187. this._checkLimits();
  44188. _super.prototype._checkInputs.call(this);
  44189. };
  44190. ArcRotateCamera.prototype._checkLimits = function () {
  44191. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44192. if (this.allowUpsideDown && this.beta > Math.PI) {
  44193. this.beta = this.beta - (2 * Math.PI);
  44194. }
  44195. }
  44196. else {
  44197. if (this.beta < this.lowerBetaLimit) {
  44198. this.beta = this.lowerBetaLimit;
  44199. }
  44200. }
  44201. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44202. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44203. this.beta = this.beta + (2 * Math.PI);
  44204. }
  44205. }
  44206. else {
  44207. if (this.beta > this.upperBetaLimit) {
  44208. this.beta = this.upperBetaLimit;
  44209. }
  44210. }
  44211. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44212. this.alpha = this.lowerAlphaLimit;
  44213. }
  44214. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44215. this.alpha = this.upperAlphaLimit;
  44216. }
  44217. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44218. this.radius = this.lowerRadiusLimit;
  44219. }
  44220. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44221. this.radius = this.upperRadiusLimit;
  44222. }
  44223. };
  44224. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44225. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44226. this.radius = radiusv3.length();
  44227. if (this.radius === 0) {
  44228. this.radius = 0.0001; // Just to avoid division by zero
  44229. }
  44230. // Alpha
  44231. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44232. if (radiusv3.z < 0) {
  44233. this.alpha = 2 * Math.PI - this.alpha;
  44234. }
  44235. // Beta
  44236. this.beta = Math.acos(radiusv3.y / this.radius);
  44237. this._checkLimits();
  44238. };
  44239. ArcRotateCamera.prototype.setPosition = function (position) {
  44240. if (this.position.equals(position)) {
  44241. return;
  44242. }
  44243. this.position.copyFrom(position);
  44244. this.rebuildAnglesAndRadius();
  44245. };
  44246. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44247. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44248. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44249. if (target.getBoundingInfo) {
  44250. if (toBoundingCenter) {
  44251. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44252. }
  44253. else {
  44254. this._targetBoundingCenter = null;
  44255. }
  44256. this._targetHost = target;
  44257. this._target = this._getTargetPosition();
  44258. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44259. }
  44260. else {
  44261. var newTarget = target;
  44262. var currentTarget = this._getTargetPosition();
  44263. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44264. return;
  44265. }
  44266. this._targetHost = null;
  44267. this._target = newTarget;
  44268. this._targetBoundingCenter = null;
  44269. this.onMeshTargetChangedObservable.notifyObservers(null);
  44270. }
  44271. this.rebuildAnglesAndRadius();
  44272. };
  44273. ArcRotateCamera.prototype._getViewMatrix = function () {
  44274. // Compute
  44275. var cosa = Math.cos(this.alpha);
  44276. var sina = Math.sin(this.alpha);
  44277. var cosb = Math.cos(this.beta);
  44278. var sinb = Math.sin(this.beta);
  44279. if (sinb === 0) {
  44280. sinb = 0.0001;
  44281. }
  44282. var target = this._getTargetPosition();
  44283. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44284. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44285. if (!this._collider) {
  44286. this._collider = new BABYLON.Collider();
  44287. }
  44288. this._collider._radius = this.collisionRadius;
  44289. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44290. this._collisionTriggered = true;
  44291. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44292. }
  44293. else {
  44294. this.position.copyFrom(this._newPosition);
  44295. var up = this.upVector;
  44296. if (this.allowUpsideDown && sinb < 0) {
  44297. up = up.clone();
  44298. up = up.negate();
  44299. }
  44300. if (this.getScene().useRightHandedSystem) {
  44301. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44302. }
  44303. else {
  44304. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44305. }
  44306. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44307. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44308. }
  44309. this._currentTarget = target;
  44310. return this._viewMatrix;
  44311. };
  44312. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44313. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44314. meshes = meshes || this.getScene().meshes;
  44315. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44316. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44317. this.radius = distance * this.zoomOnFactor;
  44318. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44319. };
  44320. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44321. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44322. var meshesOrMinMaxVector;
  44323. var distance;
  44324. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44325. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44326. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44327. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44328. }
  44329. else {
  44330. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44331. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44332. distance = minMaxVectorAndDistance.distance;
  44333. }
  44334. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44335. if (!doNotUpdateMaxZ) {
  44336. this.maxZ = distance * 2;
  44337. }
  44338. };
  44339. /**
  44340. * @override
  44341. * Override Camera.createRigCamera
  44342. */
  44343. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44344. var alphaShift = 0;
  44345. switch (this.cameraRigMode) {
  44346. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44347. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44348. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44349. case BABYLON.Camera.RIG_MODE_VR:
  44350. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44351. break;
  44352. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44353. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44354. break;
  44355. }
  44356. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44357. rigCam._cameraRigParams = {};
  44358. return rigCam;
  44359. };
  44360. /**
  44361. * @override
  44362. * Override Camera._updateRigCameras
  44363. */
  44364. ArcRotateCamera.prototype._updateRigCameras = function () {
  44365. var camLeft = this._rigCameras[0];
  44366. var camRight = this._rigCameras[1];
  44367. camLeft.beta = camRight.beta = this.beta;
  44368. camLeft.radius = camRight.radius = this.radius;
  44369. switch (this.cameraRigMode) {
  44370. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44371. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44372. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44373. case BABYLON.Camera.RIG_MODE_VR:
  44374. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44375. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44376. break;
  44377. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44378. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44379. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44380. break;
  44381. }
  44382. _super.prototype._updateRigCameras.call(this);
  44383. };
  44384. ArcRotateCamera.prototype.dispose = function () {
  44385. this.inputs.clear();
  44386. _super.prototype.dispose.call(this);
  44387. };
  44388. ArcRotateCamera.prototype.getClassName = function () {
  44389. return "ArcRotateCamera";
  44390. };
  44391. __decorate([
  44392. BABYLON.serialize()
  44393. ], ArcRotateCamera.prototype, "alpha", void 0);
  44394. __decorate([
  44395. BABYLON.serialize()
  44396. ], ArcRotateCamera.prototype, "beta", void 0);
  44397. __decorate([
  44398. BABYLON.serialize()
  44399. ], ArcRotateCamera.prototype, "radius", void 0);
  44400. __decorate([
  44401. BABYLON.serializeAsVector3("target")
  44402. ], ArcRotateCamera.prototype, "_target", void 0);
  44403. __decorate([
  44404. BABYLON.serialize()
  44405. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44406. __decorate([
  44407. BABYLON.serialize()
  44408. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44409. __decorate([
  44410. BABYLON.serialize()
  44411. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44412. __decorate([
  44413. BABYLON.serialize()
  44414. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44415. __decorate([
  44416. BABYLON.serialize()
  44417. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44418. __decorate([
  44419. BABYLON.serialize()
  44420. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44421. __decorate([
  44422. BABYLON.serialize()
  44423. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44424. __decorate([
  44425. BABYLON.serialize()
  44426. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44427. __decorate([
  44428. BABYLON.serialize()
  44429. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44430. __decorate([
  44431. BABYLON.serialize()
  44432. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44433. __decorate([
  44434. BABYLON.serialize()
  44435. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44436. __decorate([
  44437. BABYLON.serialize()
  44438. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44439. __decorate([
  44440. BABYLON.serialize()
  44441. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44442. __decorate([
  44443. BABYLON.serializeAsVector3()
  44444. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44445. __decorate([
  44446. BABYLON.serialize()
  44447. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44448. __decorate([
  44449. BABYLON.serialize()
  44450. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44451. __decorate([
  44452. BABYLON.serialize()
  44453. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44454. return ArcRotateCamera;
  44455. }(BABYLON.TargetCamera));
  44456. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44457. })(BABYLON || (BABYLON = {}));
  44458. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44459. var BABYLON;
  44460. (function (BABYLON) {
  44461. /**
  44462. * The HemisphericLight simulates the ambient environment light,
  44463. * so the passed direction is the light reflection direction, not the incoming direction.
  44464. */
  44465. var HemisphericLight = /** @class */ (function (_super) {
  44466. __extends(HemisphericLight, _super);
  44467. /**
  44468. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44469. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44470. * The HemisphericLight can't cast shadows.
  44471. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44472. * @param name The friendly name of the light
  44473. * @param direction The direction of the light reflection
  44474. * @param scene The scene the light belongs to
  44475. */
  44476. function HemisphericLight(name, direction, scene) {
  44477. var _this = _super.call(this, name, scene) || this;
  44478. /**
  44479. * The groundColor is the light in the opposite direction to the one specified during creation.
  44480. * 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.
  44481. */
  44482. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44483. _this.direction = direction || BABYLON.Vector3.Up();
  44484. return _this;
  44485. }
  44486. HemisphericLight.prototype._buildUniformLayout = function () {
  44487. this._uniformBuffer.addUniform("vLightData", 4);
  44488. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44489. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44490. this._uniformBuffer.addUniform("vLightGround", 3);
  44491. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44492. this._uniformBuffer.addUniform("depthValues", 2);
  44493. this._uniformBuffer.create();
  44494. };
  44495. /**
  44496. * Returns the string "HemisphericLight".
  44497. * @return The class name
  44498. */
  44499. HemisphericLight.prototype.getClassName = function () {
  44500. return "HemisphericLight";
  44501. };
  44502. /**
  44503. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44504. * Returns the updated direction.
  44505. * @param target The target the direction should point to
  44506. * @return The computed direction
  44507. */
  44508. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44509. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44510. return this.direction;
  44511. };
  44512. /**
  44513. * Returns the shadow generator associated to the light.
  44514. * @returns Always null for hemispheric lights because it does not support shadows.
  44515. */
  44516. HemisphericLight.prototype.getShadowGenerator = function () {
  44517. return null;
  44518. };
  44519. /**
  44520. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44521. * @param effect The effect to update
  44522. * @param lightIndex The index of the light in the effect to update
  44523. * @returns The hemispheric light
  44524. */
  44525. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44526. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44527. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44528. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44529. return this;
  44530. };
  44531. /**
  44532. * @ignore internal use only.
  44533. */
  44534. HemisphericLight.prototype._getWorldMatrix = function () {
  44535. if (!this._worldMatrix) {
  44536. this._worldMatrix = BABYLON.Matrix.Identity();
  44537. }
  44538. return this._worldMatrix;
  44539. };
  44540. /**
  44541. * Returns the integer 3.
  44542. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44543. */
  44544. HemisphericLight.prototype.getTypeID = function () {
  44545. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44546. };
  44547. __decorate([
  44548. BABYLON.serializeAsColor3()
  44549. ], HemisphericLight.prototype, "groundColor", void 0);
  44550. __decorate([
  44551. BABYLON.serializeAsVector3()
  44552. ], HemisphericLight.prototype, "direction", void 0);
  44553. return HemisphericLight;
  44554. }(BABYLON.Light));
  44555. BABYLON.HemisphericLight = HemisphericLight;
  44556. })(BABYLON || (BABYLON = {}));
  44557. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44558. var BABYLON;
  44559. (function (BABYLON) {
  44560. /**
  44561. * Base implementation of @see IShadowLight
  44562. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44563. */
  44564. var ShadowLight = /** @class */ (function (_super) {
  44565. __extends(ShadowLight, _super);
  44566. function ShadowLight() {
  44567. var _this = _super !== null && _super.apply(this, arguments) || this;
  44568. _this._needProjectionMatrixCompute = true;
  44569. return _this;
  44570. }
  44571. ShadowLight.prototype._setPosition = function (value) {
  44572. this._position = value;
  44573. };
  44574. Object.defineProperty(ShadowLight.prototype, "position", {
  44575. /**
  44576. * Sets the position the shadow will be casted from. Also use as the light position for both
  44577. * point and spot lights.
  44578. */
  44579. get: function () {
  44580. return this._position;
  44581. },
  44582. /**
  44583. * Sets the position the shadow will be casted from. Also use as the light position for both
  44584. * point and spot lights.
  44585. */
  44586. set: function (value) {
  44587. this._setPosition(value);
  44588. },
  44589. enumerable: true,
  44590. configurable: true
  44591. });
  44592. ShadowLight.prototype._setDirection = function (value) {
  44593. this._direction = value;
  44594. };
  44595. Object.defineProperty(ShadowLight.prototype, "direction", {
  44596. /**
  44597. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44598. * Also use as the light direction on spot and directional lights.
  44599. */
  44600. get: function () {
  44601. return this._direction;
  44602. },
  44603. /**
  44604. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44605. * Also use as the light direction on spot and directional lights.
  44606. */
  44607. set: function (value) {
  44608. this._setDirection(value);
  44609. },
  44610. enumerable: true,
  44611. configurable: true
  44612. });
  44613. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44614. /**
  44615. * Gets the shadow projection clipping minimum z value.
  44616. */
  44617. get: function () {
  44618. return this._shadowMinZ;
  44619. },
  44620. /**
  44621. * Sets the shadow projection clipping minimum z value.
  44622. */
  44623. set: function (value) {
  44624. this._shadowMinZ = value;
  44625. this.forceProjectionMatrixCompute();
  44626. },
  44627. enumerable: true,
  44628. configurable: true
  44629. });
  44630. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44631. /**
  44632. * Sets the shadow projection clipping maximum z value.
  44633. */
  44634. get: function () {
  44635. return this._shadowMaxZ;
  44636. },
  44637. /**
  44638. * Gets the shadow projection clipping maximum z value.
  44639. */
  44640. set: function (value) {
  44641. this._shadowMaxZ = value;
  44642. this.forceProjectionMatrixCompute();
  44643. },
  44644. enumerable: true,
  44645. configurable: true
  44646. });
  44647. /**
  44648. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44649. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44650. */
  44651. ShadowLight.prototype.computeTransformedInformation = function () {
  44652. if (this.parent && this.parent.getWorldMatrix) {
  44653. if (!this.transformedPosition) {
  44654. this.transformedPosition = BABYLON.Vector3.Zero();
  44655. }
  44656. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44657. // In case the direction is present.
  44658. if (this.direction) {
  44659. if (!this.transformedDirection) {
  44660. this.transformedDirection = BABYLON.Vector3.Zero();
  44661. }
  44662. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44663. }
  44664. return true;
  44665. }
  44666. return false;
  44667. };
  44668. /**
  44669. * Return the depth scale used for the shadow map.
  44670. * @returns the depth scale.
  44671. */
  44672. ShadowLight.prototype.getDepthScale = function () {
  44673. return 50.0;
  44674. };
  44675. /**
  44676. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44677. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44678. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44679. */
  44680. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44681. return this.transformedDirection ? this.transformedDirection : this.direction;
  44682. };
  44683. /**
  44684. * Returns the ShadowLight absolute position in the World.
  44685. * @returns the position vector in world space
  44686. */
  44687. ShadowLight.prototype.getAbsolutePosition = function () {
  44688. return this.transformedPosition ? this.transformedPosition : this.position;
  44689. };
  44690. /**
  44691. * Sets the ShadowLight direction toward the passed target.
  44692. * @param target The point tot target in local space
  44693. * @returns the updated ShadowLight direction
  44694. */
  44695. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44696. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44697. return this.direction;
  44698. };
  44699. /**
  44700. * Returns the light rotation in euler definition.
  44701. * @returns the x y z rotation in local space.
  44702. */
  44703. ShadowLight.prototype.getRotation = function () {
  44704. this.direction.normalize();
  44705. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44706. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44707. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44708. };
  44709. /**
  44710. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44711. * @returns true if a cube texture needs to be use
  44712. */
  44713. ShadowLight.prototype.needCube = function () {
  44714. return false;
  44715. };
  44716. /**
  44717. * Detects if the projection matrix requires to be recomputed this frame.
  44718. * @returns true if it requires to be recomputed otherwise, false.
  44719. */
  44720. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44721. return this._needProjectionMatrixCompute;
  44722. };
  44723. /**
  44724. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44725. */
  44726. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44727. this._needProjectionMatrixCompute = true;
  44728. };
  44729. /**
  44730. * Get the world matrix of the sahdow lights.
  44731. * @ignore Internal Use Only
  44732. */
  44733. ShadowLight.prototype._getWorldMatrix = function () {
  44734. if (!this._worldMatrix) {
  44735. this._worldMatrix = BABYLON.Matrix.Identity();
  44736. }
  44737. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44738. return this._worldMatrix;
  44739. };
  44740. /**
  44741. * Gets the minZ used for shadow according to both the scene and the light.
  44742. * @param activeCamera The camera we are returning the min for
  44743. * @returns the depth min z
  44744. */
  44745. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44746. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44747. };
  44748. /**
  44749. * Gets the maxZ used for shadow according to both the scene and the light.
  44750. * @param activeCamera The camera we are returning the max for
  44751. * @returns the depth max z
  44752. */
  44753. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44754. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44755. };
  44756. /**
  44757. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44758. * @param matrix The materix to updated with the projection information
  44759. * @param viewMatrix The transform matrix of the light
  44760. * @param renderList The list of mesh to render in the map
  44761. * @returns The current light
  44762. */
  44763. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44764. if (this.customProjectionMatrixBuilder) {
  44765. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44766. }
  44767. else {
  44768. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44769. }
  44770. return this;
  44771. };
  44772. __decorate([
  44773. BABYLON.serializeAsVector3()
  44774. ], ShadowLight.prototype, "position", null);
  44775. __decorate([
  44776. BABYLON.serializeAsVector3()
  44777. ], ShadowLight.prototype, "direction", null);
  44778. __decorate([
  44779. BABYLON.serialize()
  44780. ], ShadowLight.prototype, "shadowMinZ", null);
  44781. __decorate([
  44782. BABYLON.serialize()
  44783. ], ShadowLight.prototype, "shadowMaxZ", null);
  44784. return ShadowLight;
  44785. }(BABYLON.Light));
  44786. BABYLON.ShadowLight = ShadowLight;
  44787. })(BABYLON || (BABYLON = {}));
  44788. //# sourceMappingURL=babylon.shadowLight.js.map
  44789. var BABYLON;
  44790. (function (BABYLON) {
  44791. /**
  44792. * A point light is a light defined by an unique point in world space.
  44793. * The light is emitted in every direction from this point.
  44794. * A good example of a point light is a standard light bulb.
  44795. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44796. */
  44797. var PointLight = /** @class */ (function (_super) {
  44798. __extends(PointLight, _super);
  44799. /**
  44800. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44801. * A PointLight emits the light in every direction.
  44802. * It can cast shadows.
  44803. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44804. * ```javascript
  44805. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44806. * ```
  44807. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44808. * @param name The light friendly name
  44809. * @param position The position of the point light in the scene
  44810. * @param scene The scene the lights belongs to
  44811. */
  44812. function PointLight(name, position, scene) {
  44813. var _this = _super.call(this, name, scene) || this;
  44814. _this._shadowAngle = Math.PI / 2;
  44815. _this.position = position;
  44816. return _this;
  44817. }
  44818. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44819. /**
  44820. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44821. * This specifies what angle the shadow will use to be created.
  44822. *
  44823. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44824. */
  44825. get: function () {
  44826. return this._shadowAngle;
  44827. },
  44828. /**
  44829. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44830. * This specifies what angle the shadow will use to be created.
  44831. *
  44832. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44833. */
  44834. set: function (value) {
  44835. this._shadowAngle = value;
  44836. this.forceProjectionMatrixCompute();
  44837. },
  44838. enumerable: true,
  44839. configurable: true
  44840. });
  44841. Object.defineProperty(PointLight.prototype, "direction", {
  44842. /**
  44843. * Gets the direction if it has been set.
  44844. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44845. */
  44846. get: function () {
  44847. return this._direction;
  44848. },
  44849. /**
  44850. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44851. */
  44852. set: function (value) {
  44853. var previousNeedCube = this.needCube();
  44854. this._direction = value;
  44855. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44856. this._shadowGenerator.recreateShadowMap();
  44857. }
  44858. },
  44859. enumerable: true,
  44860. configurable: true
  44861. });
  44862. /**
  44863. * Returns the string "PointLight"
  44864. * @returns the class name
  44865. */
  44866. PointLight.prototype.getClassName = function () {
  44867. return "PointLight";
  44868. };
  44869. /**
  44870. * Returns the integer 0.
  44871. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44872. */
  44873. PointLight.prototype.getTypeID = function () {
  44874. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44875. };
  44876. /**
  44877. * Specifies wether or not the shadowmap should be a cube texture.
  44878. * @returns true if the shadowmap needs to be a cube texture.
  44879. */
  44880. PointLight.prototype.needCube = function () {
  44881. return !this.direction;
  44882. };
  44883. /**
  44884. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44885. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44886. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44887. */
  44888. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44889. if (this.direction) {
  44890. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44891. }
  44892. else {
  44893. switch (faceIndex) {
  44894. case 0:
  44895. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44896. case 1:
  44897. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44898. case 2:
  44899. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44900. case 3:
  44901. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44902. case 4:
  44903. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44904. case 5:
  44905. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44906. }
  44907. }
  44908. return BABYLON.Vector3.Zero();
  44909. };
  44910. /**
  44911. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44912. * - fov = PI / 2
  44913. * - aspect ratio : 1.0
  44914. * - z-near and far equal to the active camera minZ and maxZ.
  44915. * Returns the PointLight.
  44916. */
  44917. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44918. var activeCamera = this.getScene().activeCamera;
  44919. if (!activeCamera) {
  44920. return;
  44921. }
  44922. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44923. };
  44924. PointLight.prototype._buildUniformLayout = function () {
  44925. this._uniformBuffer.addUniform("vLightData", 4);
  44926. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44927. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44928. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44929. this._uniformBuffer.addUniform("depthValues", 2);
  44930. this._uniformBuffer.create();
  44931. };
  44932. /**
  44933. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44934. * @param effect The effect to update
  44935. * @param lightIndex The index of the light in the effect to update
  44936. * @returns The point light
  44937. */
  44938. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44939. if (this.computeTransformedInformation()) {
  44940. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44941. return this;
  44942. }
  44943. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44944. return this;
  44945. };
  44946. __decorate([
  44947. BABYLON.serialize()
  44948. ], PointLight.prototype, "shadowAngle", null);
  44949. return PointLight;
  44950. }(BABYLON.ShadowLight));
  44951. BABYLON.PointLight = PointLight;
  44952. })(BABYLON || (BABYLON = {}));
  44953. //# sourceMappingURL=babylon.pointLight.js.map
  44954. var BABYLON;
  44955. (function (BABYLON) {
  44956. /**
  44957. * A directional light is defined by a direction (what a surprise!).
  44958. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44959. * 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.
  44960. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44961. */
  44962. var DirectionalLight = /** @class */ (function (_super) {
  44963. __extends(DirectionalLight, _super);
  44964. /**
  44965. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44966. * The directional light is emitted from everywhere in the given direction.
  44967. * It can cast shawdows.
  44968. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44969. * @param name The friendly name of the light
  44970. * @param direction The direction of the light
  44971. * @param scene The scene the light belongs to
  44972. */
  44973. function DirectionalLight(name, direction, scene) {
  44974. var _this = _super.call(this, name, scene) || this;
  44975. _this._shadowFrustumSize = 0;
  44976. _this._shadowOrthoScale = 0.5;
  44977. /**
  44978. * Automatically compute the projection matrix to best fit (including all the casters)
  44979. * on each frame.
  44980. */
  44981. _this.autoUpdateExtends = true;
  44982. // Cache
  44983. _this._orthoLeft = Number.MAX_VALUE;
  44984. _this._orthoRight = Number.MIN_VALUE;
  44985. _this._orthoTop = Number.MIN_VALUE;
  44986. _this._orthoBottom = Number.MAX_VALUE;
  44987. _this.position = direction.scale(-1.0);
  44988. _this.direction = direction;
  44989. return _this;
  44990. }
  44991. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44992. /**
  44993. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44994. */
  44995. get: function () {
  44996. return this._shadowFrustumSize;
  44997. },
  44998. /**
  44999. * Specifies a fix frustum size for the shadow generation.
  45000. */
  45001. set: function (value) {
  45002. this._shadowFrustumSize = value;
  45003. this.forceProjectionMatrixCompute();
  45004. },
  45005. enumerable: true,
  45006. configurable: true
  45007. });
  45008. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45009. /**
  45010. * Gets the shadow projection scale against the optimal computed one.
  45011. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45012. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45013. */
  45014. get: function () {
  45015. return this._shadowOrthoScale;
  45016. },
  45017. /**
  45018. * Sets the shadow projection scale against the optimal computed one.
  45019. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45020. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45021. */
  45022. set: function (value) {
  45023. this._shadowOrthoScale = value;
  45024. this.forceProjectionMatrixCompute();
  45025. },
  45026. enumerable: true,
  45027. configurable: true
  45028. });
  45029. /**
  45030. * Returns the string "DirectionalLight".
  45031. * @return The class name
  45032. */
  45033. DirectionalLight.prototype.getClassName = function () {
  45034. return "DirectionalLight";
  45035. };
  45036. /**
  45037. * Returns the integer 1.
  45038. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45039. */
  45040. DirectionalLight.prototype.getTypeID = function () {
  45041. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45042. };
  45043. /**
  45044. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45045. * Returns the DirectionalLight Shadow projection matrix.
  45046. */
  45047. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45048. if (this.shadowFrustumSize > 0) {
  45049. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45050. }
  45051. else {
  45052. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45053. }
  45054. };
  45055. /**
  45056. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45057. * Returns the DirectionalLight Shadow projection matrix.
  45058. */
  45059. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45060. var activeCamera = this.getScene().activeCamera;
  45061. if (!activeCamera) {
  45062. return;
  45063. }
  45064. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45065. };
  45066. /**
  45067. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45068. * Returns the DirectionalLight Shadow projection matrix.
  45069. */
  45070. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45071. var activeCamera = this.getScene().activeCamera;
  45072. if (!activeCamera) {
  45073. return;
  45074. }
  45075. // Check extends
  45076. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45077. var tempVector3 = BABYLON.Vector3.Zero();
  45078. this._orthoLeft = Number.MAX_VALUE;
  45079. this._orthoRight = Number.MIN_VALUE;
  45080. this._orthoTop = Number.MIN_VALUE;
  45081. this._orthoBottom = Number.MAX_VALUE;
  45082. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45083. var mesh = renderList[meshIndex];
  45084. if (!mesh) {
  45085. continue;
  45086. }
  45087. var boundingInfo = mesh.getBoundingInfo();
  45088. var boundingBox = boundingInfo.boundingBox;
  45089. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45090. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45091. if (tempVector3.x < this._orthoLeft)
  45092. this._orthoLeft = tempVector3.x;
  45093. if (tempVector3.y < this._orthoBottom)
  45094. this._orthoBottom = tempVector3.y;
  45095. if (tempVector3.x > this._orthoRight)
  45096. this._orthoRight = tempVector3.x;
  45097. if (tempVector3.y > this._orthoTop)
  45098. this._orthoTop = tempVector3.y;
  45099. }
  45100. }
  45101. }
  45102. var xOffset = this._orthoRight - this._orthoLeft;
  45103. var yOffset = this._orthoTop - this._orthoBottom;
  45104. 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);
  45105. };
  45106. DirectionalLight.prototype._buildUniformLayout = function () {
  45107. this._uniformBuffer.addUniform("vLightData", 4);
  45108. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45109. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45110. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45111. this._uniformBuffer.addUniform("depthValues", 2);
  45112. this._uniformBuffer.create();
  45113. };
  45114. /**
  45115. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45116. * @param effect The effect to update
  45117. * @param lightIndex The index of the light in the effect to update
  45118. * @returns The directional light
  45119. */
  45120. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45121. if (this.computeTransformedInformation()) {
  45122. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45123. return this;
  45124. }
  45125. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45126. return this;
  45127. };
  45128. /**
  45129. * Gets the minZ used for shadow according to both the scene and the light.
  45130. *
  45131. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45132. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45133. * @param activeCamera The camera we are returning the min for
  45134. * @returns the depth min z
  45135. */
  45136. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45137. return 1;
  45138. };
  45139. /**
  45140. * Gets the maxZ used for shadow according to both the scene and the light.
  45141. *
  45142. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45143. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45144. * @param activeCamera The camera we are returning the max for
  45145. * @returns the depth max z
  45146. */
  45147. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45148. return 1;
  45149. };
  45150. __decorate([
  45151. BABYLON.serialize()
  45152. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45153. __decorate([
  45154. BABYLON.serialize()
  45155. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45156. __decorate([
  45157. BABYLON.serialize()
  45158. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45159. return DirectionalLight;
  45160. }(BABYLON.ShadowLight));
  45161. BABYLON.DirectionalLight = DirectionalLight;
  45162. })(BABYLON || (BABYLON = {}));
  45163. //# sourceMappingURL=babylon.directionalLight.js.map
  45164. var BABYLON;
  45165. (function (BABYLON) {
  45166. /**
  45167. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45168. * These values define a cone of light starting from the position, emitting toward the direction.
  45169. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45170. * and the exponent defines the speed of the decay of the light with distance (reach).
  45171. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45172. */
  45173. var SpotLight = /** @class */ (function (_super) {
  45174. __extends(SpotLight, _super);
  45175. /**
  45176. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45177. * It can cast shadows.
  45178. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45179. * @param name The light friendly name
  45180. * @param position The position of the spot light in the scene
  45181. * @param direction The direction of the light in the scene
  45182. * @param angle The cone angle of the light in Radians
  45183. * @param exponent The light decay speed with the distance from the emission spot
  45184. * @param scene The scene the lights belongs to
  45185. */
  45186. function SpotLight(name, position, direction, angle, exponent, scene) {
  45187. var _this = _super.call(this, name, scene) || this;
  45188. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45189. _this._projectionTextureLightNear = 1e-6;
  45190. _this._projectionTextureLightFar = 1000.0;
  45191. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45192. _this._projectionTextureViewLightDirty = true;
  45193. _this._projectionTextureProjectionLightDirty = true;
  45194. _this._projectionTextureDirty = true;
  45195. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45196. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45197. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45198. _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);
  45199. _this.position = position;
  45200. _this.direction = direction;
  45201. _this.angle = angle;
  45202. _this.exponent = exponent;
  45203. return _this;
  45204. }
  45205. Object.defineProperty(SpotLight.prototype, "angle", {
  45206. /**
  45207. * Gets the cone angle of the spot light in Radians.
  45208. */
  45209. get: function () {
  45210. return this._angle;
  45211. },
  45212. /**
  45213. * Sets the cone angle of the spot light in Radians.
  45214. */
  45215. set: function (value) {
  45216. this._angle = value;
  45217. this._projectionTextureProjectionLightDirty = true;
  45218. this.forceProjectionMatrixCompute();
  45219. },
  45220. enumerable: true,
  45221. configurable: true
  45222. });
  45223. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45224. /**
  45225. * Allows scaling the angle of the light for shadow generation only.
  45226. */
  45227. get: function () {
  45228. return this._shadowAngleScale;
  45229. },
  45230. /**
  45231. * Allows scaling the angle of the light for shadow generation only.
  45232. */
  45233. set: function (value) {
  45234. this._shadowAngleScale = value;
  45235. this.forceProjectionMatrixCompute();
  45236. },
  45237. enumerable: true,
  45238. configurable: true
  45239. });
  45240. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45241. /**
  45242. * Allows reading the projecton texture
  45243. */
  45244. get: function () {
  45245. return this._projectionTextureMatrix;
  45246. },
  45247. enumerable: true,
  45248. configurable: true
  45249. });
  45250. ;
  45251. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45252. /**
  45253. * Gets the near clip of the Spotlight for texture projection.
  45254. */
  45255. get: function () {
  45256. return this._projectionTextureLightNear;
  45257. },
  45258. /**
  45259. * Sets the near clip of the Spotlight for texture projection.
  45260. */
  45261. set: function (value) {
  45262. this._projectionTextureLightNear = value;
  45263. this._projectionTextureProjectionLightDirty = true;
  45264. },
  45265. enumerable: true,
  45266. configurable: true
  45267. });
  45268. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45269. /**
  45270. * Gets the far clip of the Spotlight for texture projection.
  45271. */
  45272. get: function () {
  45273. return this._projectionTextureLightFar;
  45274. },
  45275. /**
  45276. * Sets the far clip of the Spotlight for texture projection.
  45277. */
  45278. set: function (value) {
  45279. this._projectionTextureLightFar = value;
  45280. this._projectionTextureProjectionLightDirty = true;
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45286. /**
  45287. * Gets the Up vector of the Spotlight for texture projection.
  45288. */
  45289. get: function () {
  45290. return this._projectionTextureUpDirection;
  45291. },
  45292. /**
  45293. * Sets the Up vector of the Spotlight for texture projection.
  45294. */
  45295. set: function (value) {
  45296. this._projectionTextureUpDirection = value;
  45297. this._projectionTextureProjectionLightDirty = true;
  45298. },
  45299. enumerable: true,
  45300. configurable: true
  45301. });
  45302. ;
  45303. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45304. /**
  45305. * Gets the projection texture of the light.
  45306. */
  45307. get: function () {
  45308. return this._projectionTexture;
  45309. },
  45310. /**
  45311. * Sets the projection texture of the light.
  45312. */
  45313. set: function (value) {
  45314. this._projectionTexture = value;
  45315. this._projectionTextureDirty = true;
  45316. },
  45317. enumerable: true,
  45318. configurable: true
  45319. });
  45320. /**
  45321. * Returns the string "SpotLight".
  45322. * @returns the class name
  45323. */
  45324. SpotLight.prototype.getClassName = function () {
  45325. return "SpotLight";
  45326. };
  45327. /**
  45328. * Returns the integer 2.
  45329. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45330. */
  45331. SpotLight.prototype.getTypeID = function () {
  45332. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45333. };
  45334. /**
  45335. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45336. */
  45337. SpotLight.prototype._setDirection = function (value) {
  45338. _super.prototype._setDirection.call(this, value);
  45339. this._projectionTextureViewLightDirty = true;
  45340. };
  45341. /**
  45342. * Overrides the position setter to recompute the projection texture view light Matrix.
  45343. */
  45344. SpotLight.prototype._setPosition = function (value) {
  45345. _super.prototype._setPosition.call(this, value);
  45346. this._projectionTextureViewLightDirty = true;
  45347. };
  45348. /**
  45349. * 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.
  45350. * Returns the SpotLight.
  45351. */
  45352. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45353. var activeCamera = this.getScene().activeCamera;
  45354. if (!activeCamera) {
  45355. return;
  45356. }
  45357. this._shadowAngleScale = this._shadowAngleScale || 1;
  45358. var angle = this._shadowAngleScale * this._angle;
  45359. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45360. };
  45361. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45362. this._projectionTextureViewLightDirty = false;
  45363. this._projectionTextureDirty = true;
  45364. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45365. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45366. };
  45367. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45368. this._projectionTextureProjectionLightDirty = false;
  45369. this._projectionTextureDirty = true;
  45370. var light_far = this.projectionTextureLightFar;
  45371. var light_near = this.projectionTextureLightNear;
  45372. var P = light_far / (light_far - light_near);
  45373. var Q = -P * light_near;
  45374. var S = 1.0 / Math.tan(this._angle / 2.0);
  45375. var A = 1.0;
  45376. 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);
  45377. };
  45378. /**
  45379. * Main function for light texture projection matrix computing.
  45380. */
  45381. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45382. this._projectionTextureDirty = false;
  45383. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45384. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45385. };
  45386. SpotLight.prototype._buildUniformLayout = function () {
  45387. this._uniformBuffer.addUniform("vLightData", 4);
  45388. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45389. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45390. this._uniformBuffer.addUniform("vLightDirection", 3);
  45391. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45392. this._uniformBuffer.addUniform("depthValues", 2);
  45393. this._uniformBuffer.create();
  45394. };
  45395. /**
  45396. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45397. * @param effect The effect to update
  45398. * @param lightIndex The index of the light in the effect to update
  45399. * @returns The spot light
  45400. */
  45401. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45402. var normalizeDirection;
  45403. if (this.computeTransformedInformation()) {
  45404. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45405. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45406. }
  45407. else {
  45408. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45409. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45410. }
  45411. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45412. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45413. if (this._projectionTextureViewLightDirty) {
  45414. this._computeProjectionTextureViewLightMatrix();
  45415. }
  45416. if (this._projectionTextureProjectionLightDirty) {
  45417. this._computeProjectionTextureProjectionLightMatrix();
  45418. }
  45419. if (this._projectionTextureDirty) {
  45420. this._computeProjectionTextureMatrix();
  45421. }
  45422. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45423. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45424. }
  45425. return this;
  45426. };
  45427. /**
  45428. * Disposes the light and the associated resources.
  45429. */
  45430. SpotLight.prototype.dispose = function () {
  45431. _super.prototype.dispose.call(this);
  45432. if (this._projectionTexture) {
  45433. this._projectionTexture.dispose();
  45434. }
  45435. };
  45436. __decorate([
  45437. BABYLON.serialize()
  45438. ], SpotLight.prototype, "angle", null);
  45439. __decorate([
  45440. BABYLON.serialize()
  45441. ], SpotLight.prototype, "shadowAngleScale", null);
  45442. __decorate([
  45443. BABYLON.serialize()
  45444. ], SpotLight.prototype, "exponent", void 0);
  45445. __decorate([
  45446. BABYLON.serialize()
  45447. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45448. __decorate([
  45449. BABYLON.serialize()
  45450. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45451. __decorate([
  45452. BABYLON.serialize()
  45453. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45454. __decorate([
  45455. BABYLON.serializeAsTexture("projectedLightTexture")
  45456. ], SpotLight.prototype, "_projectionTexture", void 0);
  45457. return SpotLight;
  45458. }(BABYLON.ShadowLight));
  45459. BABYLON.SpotLight = SpotLight;
  45460. })(BABYLON || (BABYLON = {}));
  45461. //# sourceMappingURL=babylon.spotLight.js.map
  45462. var BABYLON;
  45463. (function (BABYLON) {
  45464. var AnimationRange = /** @class */ (function () {
  45465. function AnimationRange(name, from, to) {
  45466. this.name = name;
  45467. this.from = from;
  45468. this.to = to;
  45469. }
  45470. AnimationRange.prototype.clone = function () {
  45471. return new AnimationRange(this.name, this.from, this.to);
  45472. };
  45473. return AnimationRange;
  45474. }());
  45475. BABYLON.AnimationRange = AnimationRange;
  45476. /**
  45477. * Composed of a frame, and an action function
  45478. */
  45479. var AnimationEvent = /** @class */ (function () {
  45480. function AnimationEvent(frame, action, onlyOnce) {
  45481. this.frame = frame;
  45482. this.action = action;
  45483. this.onlyOnce = onlyOnce;
  45484. this.isDone = false;
  45485. }
  45486. return AnimationEvent;
  45487. }());
  45488. BABYLON.AnimationEvent = AnimationEvent;
  45489. var PathCursor = /** @class */ (function () {
  45490. function PathCursor(path) {
  45491. this.path = path;
  45492. this._onchange = new Array();
  45493. this.value = 0;
  45494. this.animations = new Array();
  45495. }
  45496. PathCursor.prototype.getPoint = function () {
  45497. var point = this.path.getPointAtLengthPosition(this.value);
  45498. return new BABYLON.Vector3(point.x, 0, point.y);
  45499. };
  45500. PathCursor.prototype.moveAhead = function (step) {
  45501. if (step === void 0) { step = 0.002; }
  45502. this.move(step);
  45503. return this;
  45504. };
  45505. PathCursor.prototype.moveBack = function (step) {
  45506. if (step === void 0) { step = 0.002; }
  45507. this.move(-step);
  45508. return this;
  45509. };
  45510. PathCursor.prototype.move = function (step) {
  45511. if (Math.abs(step) > 1) {
  45512. throw "step size should be less than 1.";
  45513. }
  45514. this.value += step;
  45515. this.ensureLimits();
  45516. this.raiseOnChange();
  45517. return this;
  45518. };
  45519. PathCursor.prototype.ensureLimits = function () {
  45520. while (this.value > 1) {
  45521. this.value -= 1;
  45522. }
  45523. while (this.value < 0) {
  45524. this.value += 1;
  45525. }
  45526. return this;
  45527. };
  45528. // used by animation engine
  45529. PathCursor.prototype.raiseOnChange = function () {
  45530. var _this = this;
  45531. this._onchange.forEach(function (f) { return f(_this); });
  45532. return this;
  45533. };
  45534. PathCursor.prototype.onchange = function (f) {
  45535. this._onchange.push(f);
  45536. return this;
  45537. };
  45538. return PathCursor;
  45539. }());
  45540. BABYLON.PathCursor = PathCursor;
  45541. var AnimationKeyInterpolation;
  45542. (function (AnimationKeyInterpolation) {
  45543. /**
  45544. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45545. */
  45546. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45547. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45548. var Animation = /** @class */ (function () {
  45549. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45550. this.name = name;
  45551. this.targetProperty = targetProperty;
  45552. this.framePerSecond = framePerSecond;
  45553. this.dataType = dataType;
  45554. this.loopMode = loopMode;
  45555. this.enableBlending = enableBlending;
  45556. this._runtimeAnimations = new Array();
  45557. // The set of event that will be linked to this animation
  45558. this._events = new Array();
  45559. this.blendingSpeed = 0.01;
  45560. this._ranges = {};
  45561. this.targetPropertyPath = targetProperty.split(".");
  45562. this.dataType = dataType;
  45563. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45564. }
  45565. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45566. var dataType = undefined;
  45567. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45568. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45569. }
  45570. else if (from instanceof BABYLON.Quaternion) {
  45571. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45572. }
  45573. else if (from instanceof BABYLON.Vector3) {
  45574. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45575. }
  45576. else if (from instanceof BABYLON.Vector2) {
  45577. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45578. }
  45579. else if (from instanceof BABYLON.Color3) {
  45580. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45581. }
  45582. else if (from instanceof BABYLON.Size) {
  45583. dataType = Animation.ANIMATIONTYPE_SIZE;
  45584. }
  45585. if (dataType == undefined) {
  45586. return null;
  45587. }
  45588. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45589. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45590. animation.setKeys(keys);
  45591. if (easingFunction !== undefined) {
  45592. animation.setEasingFunction(easingFunction);
  45593. }
  45594. return animation;
  45595. };
  45596. /**
  45597. * Sets up an animation.
  45598. * @param property the property to animate
  45599. * @param animationType the animation type to apply
  45600. * @param easingFunction the easing function used in the animation
  45601. * @returns The created animation
  45602. */
  45603. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45604. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45605. animation.setEasingFunction(easingFunction);
  45606. return animation;
  45607. };
  45608. /**
  45609. * Create and start an animation on a node
  45610. * @param {string} name defines the name of the global animation that will be run on all nodes
  45611. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45612. * @param {string} targetProperty defines property to animate
  45613. * @param {number} framePerSecond defines the number of frame per second yo use
  45614. * @param {number} totalFrame defines the number of frames in total
  45615. * @param {any} from defines the initial value
  45616. * @param {any} to defines the final value
  45617. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45618. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45619. * @param onAnimationEnd defines the callback to call when animation end
  45620. * @returns the animatable created for this animation
  45621. */
  45622. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45623. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45624. if (!animation) {
  45625. return null;
  45626. }
  45627. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45628. };
  45629. /**
  45630. * Create and start an animation on a node and its descendants
  45631. * @param {string} name defines the name of the global animation that will be run on all nodes
  45632. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45633. * @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.
  45634. * @param {string} targetProperty defines property to animate
  45635. * @param {number} framePerSecond defines the number of frame per second yo use
  45636. * @param {number} totalFrame defines the number of frames in total
  45637. * @param {any} from defines the initial value
  45638. * @param {any} to defines the final value
  45639. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45640. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45641. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45642. * @returns the list of animatables created for all nodes
  45643. * @example https://www.babylonjs-playground.com/#MH0VLI
  45644. */
  45645. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45646. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45647. if (!animation) {
  45648. return null;
  45649. }
  45650. var scene = node.getScene();
  45651. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45652. };
  45653. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45654. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45655. if (!animation) {
  45656. return null;
  45657. }
  45658. node.animations.push(animation);
  45659. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45660. };
  45661. /**
  45662. * Transition property of the Camera to the target Value.
  45663. * @param property The property to transition
  45664. * @param targetValue The target Value of the property
  45665. * @param host The object where the property to animate belongs
  45666. * @param scene Scene used to run the animation
  45667. * @param frameRate Framerate (in frame/s) to use
  45668. * @param transition The transition type we want to use
  45669. * @param duration The duration of the animation, in milliseconds
  45670. * @param onAnimationEnd Call back trigger at the end of the animation.
  45671. */
  45672. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45673. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45674. if (duration <= 0) {
  45675. host[property] = targetValue;
  45676. if (onAnimationEnd) {
  45677. onAnimationEnd();
  45678. }
  45679. return null;
  45680. }
  45681. var endFrame = frameRate * (duration / 1000);
  45682. transition.setKeys([{
  45683. frame: 0,
  45684. value: host[property].clone ? host[property].clone() : host[property]
  45685. },
  45686. {
  45687. frame: endFrame,
  45688. value: targetValue
  45689. }]);
  45690. if (!host.animations) {
  45691. host.animations = [];
  45692. }
  45693. host.animations.push(transition);
  45694. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45695. animation.onAnimationEnd = onAnimationEnd;
  45696. return animation;
  45697. };
  45698. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45699. /**
  45700. * Return the array of runtime animations currently using this animation
  45701. */
  45702. get: function () {
  45703. return this._runtimeAnimations;
  45704. },
  45705. enumerable: true,
  45706. configurable: true
  45707. });
  45708. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45709. get: function () {
  45710. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45711. var runtimeAnimation = _a[_i];
  45712. if (!runtimeAnimation.isStopped) {
  45713. return true;
  45714. }
  45715. }
  45716. return false;
  45717. },
  45718. enumerable: true,
  45719. configurable: true
  45720. });
  45721. // Methods
  45722. /**
  45723. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45724. */
  45725. Animation.prototype.toString = function (fullDetails) {
  45726. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45727. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45728. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45729. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45730. if (fullDetails) {
  45731. ret += ", Ranges: {";
  45732. var first = true;
  45733. for (var name in this._ranges) {
  45734. if (first) {
  45735. ret += ", ";
  45736. first = false;
  45737. }
  45738. ret += name;
  45739. }
  45740. ret += "}";
  45741. }
  45742. return ret;
  45743. };
  45744. /**
  45745. * Add an event to this animation.
  45746. */
  45747. Animation.prototype.addEvent = function (event) {
  45748. this._events.push(event);
  45749. };
  45750. /**
  45751. * Remove all events found at the given frame
  45752. * @param frame
  45753. */
  45754. Animation.prototype.removeEvents = function (frame) {
  45755. for (var index = 0; index < this._events.length; index++) {
  45756. if (this._events[index].frame === frame) {
  45757. this._events.splice(index, 1);
  45758. index--;
  45759. }
  45760. }
  45761. };
  45762. Animation.prototype.getEvents = function () {
  45763. return this._events;
  45764. };
  45765. Animation.prototype.createRange = function (name, from, to) {
  45766. // check name not already in use; could happen for bones after serialized
  45767. if (!this._ranges[name]) {
  45768. this._ranges[name] = new AnimationRange(name, from, to);
  45769. }
  45770. };
  45771. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45772. if (deleteFrames === void 0) { deleteFrames = true; }
  45773. var range = this._ranges[name];
  45774. if (!range) {
  45775. return;
  45776. }
  45777. if (deleteFrames) {
  45778. var from = range.from;
  45779. var to = range.to;
  45780. // this loop MUST go high to low for multiple splices to work
  45781. for (var key = this._keys.length - 1; key >= 0; key--) {
  45782. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45783. this._keys.splice(key, 1);
  45784. }
  45785. }
  45786. }
  45787. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45788. };
  45789. Animation.prototype.getRange = function (name) {
  45790. return this._ranges[name];
  45791. };
  45792. Animation.prototype.getKeys = function () {
  45793. return this._keys;
  45794. };
  45795. Animation.prototype.getHighestFrame = function () {
  45796. var ret = 0;
  45797. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45798. if (ret < this._keys[key].frame) {
  45799. ret = this._keys[key].frame;
  45800. }
  45801. }
  45802. return ret;
  45803. };
  45804. Animation.prototype.getEasingFunction = function () {
  45805. return this._easingFunction;
  45806. };
  45807. Animation.prototype.setEasingFunction = function (easingFunction) {
  45808. this._easingFunction = easingFunction;
  45809. };
  45810. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45811. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45812. };
  45813. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45814. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45815. };
  45816. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45817. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45818. };
  45819. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45820. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45821. };
  45822. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45823. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45824. };
  45825. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45826. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45827. };
  45828. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45829. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45830. };
  45831. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45832. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45833. };
  45834. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45835. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45836. };
  45837. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45838. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45839. };
  45840. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45841. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45842. };
  45843. Animation.prototype.clone = function () {
  45844. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45845. clone.enableBlending = this.enableBlending;
  45846. clone.blendingSpeed = this.blendingSpeed;
  45847. if (this._keys) {
  45848. clone.setKeys(this._keys);
  45849. }
  45850. if (this._ranges) {
  45851. clone._ranges = {};
  45852. for (var name in this._ranges) {
  45853. var range = this._ranges[name];
  45854. if (!range) {
  45855. continue;
  45856. }
  45857. clone._ranges[name] = range.clone();
  45858. }
  45859. }
  45860. return clone;
  45861. };
  45862. Animation.prototype.setKeys = function (values) {
  45863. this._keys = values.slice(0);
  45864. };
  45865. Animation.prototype.serialize = function () {
  45866. var serializationObject = {};
  45867. serializationObject.name = this.name;
  45868. serializationObject.property = this.targetProperty;
  45869. serializationObject.framePerSecond = this.framePerSecond;
  45870. serializationObject.dataType = this.dataType;
  45871. serializationObject.loopBehavior = this.loopMode;
  45872. serializationObject.enableBlending = this.enableBlending;
  45873. serializationObject.blendingSpeed = this.blendingSpeed;
  45874. var dataType = this.dataType;
  45875. serializationObject.keys = [];
  45876. var keys = this.getKeys();
  45877. for (var index = 0; index < keys.length; index++) {
  45878. var animationKey = keys[index];
  45879. var key = {};
  45880. key.frame = animationKey.frame;
  45881. switch (dataType) {
  45882. case Animation.ANIMATIONTYPE_FLOAT:
  45883. key.values = [animationKey.value];
  45884. break;
  45885. case Animation.ANIMATIONTYPE_QUATERNION:
  45886. case Animation.ANIMATIONTYPE_MATRIX:
  45887. case Animation.ANIMATIONTYPE_VECTOR3:
  45888. case Animation.ANIMATIONTYPE_COLOR3:
  45889. key.values = animationKey.value.asArray();
  45890. break;
  45891. }
  45892. serializationObject.keys.push(key);
  45893. }
  45894. serializationObject.ranges = [];
  45895. for (var name in this._ranges) {
  45896. var source = this._ranges[name];
  45897. if (!source) {
  45898. continue;
  45899. }
  45900. var range = {};
  45901. range.name = name;
  45902. range.from = source.from;
  45903. range.to = source.to;
  45904. serializationObject.ranges.push(range);
  45905. }
  45906. return serializationObject;
  45907. };
  45908. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45909. get: function () {
  45910. return Animation._ANIMATIONTYPE_FLOAT;
  45911. },
  45912. enumerable: true,
  45913. configurable: true
  45914. });
  45915. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45916. get: function () {
  45917. return Animation._ANIMATIONTYPE_VECTOR3;
  45918. },
  45919. enumerable: true,
  45920. configurable: true
  45921. });
  45922. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45923. get: function () {
  45924. return Animation._ANIMATIONTYPE_VECTOR2;
  45925. },
  45926. enumerable: true,
  45927. configurable: true
  45928. });
  45929. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45930. get: function () {
  45931. return Animation._ANIMATIONTYPE_SIZE;
  45932. },
  45933. enumerable: true,
  45934. configurable: true
  45935. });
  45936. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45937. get: function () {
  45938. return Animation._ANIMATIONTYPE_QUATERNION;
  45939. },
  45940. enumerable: true,
  45941. configurable: true
  45942. });
  45943. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45944. get: function () {
  45945. return Animation._ANIMATIONTYPE_MATRIX;
  45946. },
  45947. enumerable: true,
  45948. configurable: true
  45949. });
  45950. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45951. get: function () {
  45952. return Animation._ANIMATIONTYPE_COLOR3;
  45953. },
  45954. enumerable: true,
  45955. configurable: true
  45956. });
  45957. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45958. get: function () {
  45959. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45960. },
  45961. enumerable: true,
  45962. configurable: true
  45963. });
  45964. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45965. get: function () {
  45966. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45967. },
  45968. enumerable: true,
  45969. configurable: true
  45970. });
  45971. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45972. get: function () {
  45973. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45974. },
  45975. enumerable: true,
  45976. configurable: true
  45977. });
  45978. Animation.Parse = function (parsedAnimation) {
  45979. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45980. var dataType = parsedAnimation.dataType;
  45981. var keys = [];
  45982. var data;
  45983. var index;
  45984. if (parsedAnimation.enableBlending) {
  45985. animation.enableBlending = parsedAnimation.enableBlending;
  45986. }
  45987. if (parsedAnimation.blendingSpeed) {
  45988. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45989. }
  45990. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45991. var key = parsedAnimation.keys[index];
  45992. var inTangent;
  45993. var outTangent;
  45994. switch (dataType) {
  45995. case Animation.ANIMATIONTYPE_FLOAT:
  45996. data = key.values[0];
  45997. if (key.values.length >= 1) {
  45998. inTangent = key.values[1];
  45999. }
  46000. if (key.values.length >= 2) {
  46001. outTangent = key.values[2];
  46002. }
  46003. break;
  46004. case Animation.ANIMATIONTYPE_QUATERNION:
  46005. data = BABYLON.Quaternion.FromArray(key.values);
  46006. if (key.values.length >= 8) {
  46007. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46008. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46009. inTangent = _inTangent;
  46010. }
  46011. }
  46012. if (key.values.length >= 12) {
  46013. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46014. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46015. outTangent = _outTangent;
  46016. }
  46017. }
  46018. break;
  46019. case Animation.ANIMATIONTYPE_MATRIX:
  46020. data = BABYLON.Matrix.FromArray(key.values);
  46021. break;
  46022. case Animation.ANIMATIONTYPE_COLOR3:
  46023. data = BABYLON.Color3.FromArray(key.values);
  46024. break;
  46025. case Animation.ANIMATIONTYPE_VECTOR3:
  46026. default:
  46027. data = BABYLON.Vector3.FromArray(key.values);
  46028. break;
  46029. }
  46030. var keyData = {};
  46031. keyData.frame = key.frame;
  46032. keyData.value = data;
  46033. if (inTangent != undefined) {
  46034. keyData.inTangent = inTangent;
  46035. }
  46036. if (outTangent != undefined) {
  46037. keyData.outTangent = outTangent;
  46038. }
  46039. keys.push(keyData);
  46040. }
  46041. animation.setKeys(keys);
  46042. if (parsedAnimation.ranges) {
  46043. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46044. data = parsedAnimation.ranges[index];
  46045. animation.createRange(data.name, data.from, data.to);
  46046. }
  46047. }
  46048. return animation;
  46049. };
  46050. Animation.AppendSerializedAnimations = function (source, destination) {
  46051. if (source.animations) {
  46052. destination.animations = [];
  46053. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46054. var animation = source.animations[animationIndex];
  46055. destination.animations.push(animation.serialize());
  46056. }
  46057. }
  46058. };
  46059. Animation.AllowMatricesInterpolation = false;
  46060. // Statics
  46061. Animation._ANIMATIONTYPE_FLOAT = 0;
  46062. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46063. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46064. Animation._ANIMATIONTYPE_MATRIX = 3;
  46065. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46066. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46067. Animation._ANIMATIONTYPE_SIZE = 6;
  46068. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46069. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46070. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46071. return Animation;
  46072. }());
  46073. BABYLON.Animation = Animation;
  46074. })(BABYLON || (BABYLON = {}));
  46075. //# sourceMappingURL=babylon.animation.js.map
  46076. var BABYLON;
  46077. (function (BABYLON) {
  46078. /**
  46079. * This class defines the direct association between an animation and a target
  46080. */
  46081. var TargetedAnimation = /** @class */ (function () {
  46082. function TargetedAnimation() {
  46083. }
  46084. return TargetedAnimation;
  46085. }());
  46086. BABYLON.TargetedAnimation = TargetedAnimation;
  46087. /**
  46088. * Use this class to create coordinated animations on multiple targets
  46089. */
  46090. var AnimationGroup = /** @class */ (function () {
  46091. function AnimationGroup(name, scene) {
  46092. if (scene === void 0) { scene = null; }
  46093. this.name = name;
  46094. this._targetedAnimations = new Array();
  46095. this._animatables = new Array();
  46096. this._from = Number.MAX_VALUE;
  46097. this._to = -Number.MAX_VALUE;
  46098. this._speedRatio = 1;
  46099. this.onAnimationEndObservable = new BABYLON.Observable();
  46100. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46101. this._scene.animationGroups.push(this);
  46102. }
  46103. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46104. /**
  46105. * Define if the animations are started
  46106. */
  46107. get: function () {
  46108. return this._isStarted;
  46109. },
  46110. enumerable: true,
  46111. configurable: true
  46112. });
  46113. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46114. /**
  46115. * Gets or sets the speed ratio to use for all animations
  46116. */
  46117. get: function () {
  46118. return this._speedRatio;
  46119. },
  46120. /**
  46121. * Gets or sets the speed ratio to use for all animations
  46122. */
  46123. set: function (value) {
  46124. if (this._speedRatio === value) {
  46125. return;
  46126. }
  46127. this._speedRatio = value;
  46128. for (var index = 0; index < this._animatables.length; index++) {
  46129. var animatable = this._animatables[index];
  46130. animatable.speedRatio = this._speedRatio;
  46131. }
  46132. },
  46133. enumerable: true,
  46134. configurable: true
  46135. });
  46136. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46137. /**
  46138. * Gets the targeted animations for this animation group
  46139. */
  46140. get: function () {
  46141. return this._targetedAnimations;
  46142. },
  46143. enumerable: true,
  46144. configurable: true
  46145. });
  46146. /**
  46147. * Add an animation (with its target) in the group
  46148. * @param animation defines the animation we want to add
  46149. * @param target defines the target of the animation
  46150. * @returns the {BABYLON.TargetedAnimation} object
  46151. */
  46152. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46153. var targetedAnimation = {
  46154. animation: animation,
  46155. target: target
  46156. };
  46157. var keys = animation.getKeys();
  46158. if (this._from > keys[0].frame) {
  46159. this._from = keys[0].frame;
  46160. }
  46161. if (this._to < keys[keys.length - 1].frame) {
  46162. this._to = keys[keys.length - 1].frame;
  46163. }
  46164. this._targetedAnimations.push(targetedAnimation);
  46165. return targetedAnimation;
  46166. };
  46167. /**
  46168. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46169. * It can add constant keys at begin or end
  46170. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46171. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46172. */
  46173. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46174. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46175. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46176. beginFrame = Math.max(beginFrame, this._from);
  46177. endFrame = Math.min(endFrame, this._to);
  46178. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46179. var targetedAnimation = this._targetedAnimations[index];
  46180. var keys = targetedAnimation.animation.getKeys();
  46181. var startKey = keys[0];
  46182. var endKey = keys[keys.length - 1];
  46183. if (startKey.frame > beginFrame) {
  46184. var newKey = {
  46185. frame: beginFrame,
  46186. value: startKey.value,
  46187. inTangent: startKey.inTangent,
  46188. outTangent: startKey.outTangent,
  46189. interpolation: startKey.interpolation
  46190. };
  46191. keys.splice(0, 0, newKey);
  46192. }
  46193. if (endKey.frame < endFrame) {
  46194. var newKey = {
  46195. frame: endFrame,
  46196. value: endKey.value,
  46197. inTangent: endKey.outTangent,
  46198. outTangent: endKey.outTangent,
  46199. interpolation: endKey.interpolation
  46200. };
  46201. keys.push(newKey);
  46202. }
  46203. }
  46204. return this;
  46205. };
  46206. /**
  46207. * Start all animations on given targets
  46208. * @param loop defines if animations must loop
  46209. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46210. */
  46211. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46212. var _this = this;
  46213. if (loop === void 0) { loop = false; }
  46214. if (speedRatio === void 0) { speedRatio = 1; }
  46215. if (this._isStarted || this._targetedAnimations.length === 0) {
  46216. return this;
  46217. }
  46218. var _loop_1 = function () {
  46219. var targetedAnimation = this_1._targetedAnimations[index];
  46220. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46221. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46222. }));
  46223. };
  46224. var this_1 = this;
  46225. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46226. _loop_1();
  46227. }
  46228. this._speedRatio = speedRatio;
  46229. this._isStarted = true;
  46230. return this;
  46231. };
  46232. /**
  46233. * Pause all animations
  46234. */
  46235. AnimationGroup.prototype.pause = function () {
  46236. if (!this._isStarted) {
  46237. return this;
  46238. }
  46239. for (var index = 0; index < this._animatables.length; index++) {
  46240. var animatable = this._animatables[index];
  46241. animatable.pause();
  46242. }
  46243. return this;
  46244. };
  46245. /**
  46246. * Play all animations to initial state
  46247. * This function will start() the animations if they were not started or will restart() them if they were paused
  46248. * @param loop defines if animations must loop
  46249. */
  46250. AnimationGroup.prototype.play = function (loop) {
  46251. if (this.isStarted) {
  46252. if (loop !== undefined) {
  46253. for (var index = 0; index < this._animatables.length; index++) {
  46254. var animatable = this._animatables[index];
  46255. animatable.loopAnimation = loop;
  46256. }
  46257. }
  46258. this.restart();
  46259. }
  46260. else {
  46261. this.start(loop, this._speedRatio);
  46262. }
  46263. return this;
  46264. };
  46265. /**
  46266. * Reset all animations to initial state
  46267. */
  46268. AnimationGroup.prototype.reset = function () {
  46269. if (!this._isStarted) {
  46270. return this;
  46271. }
  46272. for (var index = 0; index < this._animatables.length; index++) {
  46273. var animatable = this._animatables[index];
  46274. animatable.reset();
  46275. }
  46276. return this;
  46277. };
  46278. /**
  46279. * Restart animations from key 0
  46280. */
  46281. AnimationGroup.prototype.restart = function () {
  46282. if (!this._isStarted) {
  46283. return this;
  46284. }
  46285. for (var index = 0; index < this._animatables.length; index++) {
  46286. var animatable = this._animatables[index];
  46287. animatable.restart();
  46288. }
  46289. return this;
  46290. };
  46291. /**
  46292. * Stop all animations
  46293. */
  46294. AnimationGroup.prototype.stop = function () {
  46295. if (!this._isStarted) {
  46296. return this;
  46297. }
  46298. for (var index = 0; index < this._animatables.length; index++) {
  46299. var animatable = this._animatables[index];
  46300. animatable.stop();
  46301. }
  46302. this._isStarted = false;
  46303. return this;
  46304. };
  46305. /**
  46306. * Dispose all associated resources
  46307. */
  46308. AnimationGroup.prototype.dispose = function () {
  46309. this._targetedAnimations = [];
  46310. this._animatables = [];
  46311. var index = this._scene.animationGroups.indexOf(this);
  46312. if (index > -1) {
  46313. this._scene.animationGroups.splice(index, 1);
  46314. }
  46315. };
  46316. return AnimationGroup;
  46317. }());
  46318. BABYLON.AnimationGroup = AnimationGroup;
  46319. })(BABYLON || (BABYLON = {}));
  46320. //# sourceMappingURL=babylon.animationGroup.js.map
  46321. var BABYLON;
  46322. (function (BABYLON) {
  46323. var RuntimeAnimation = /** @class */ (function () {
  46324. function RuntimeAnimation(target, animation) {
  46325. this._offsetsCache = {};
  46326. this._highLimitsCache = {};
  46327. this._stopped = false;
  46328. this._blendingFactor = 0;
  46329. this._ratioOffset = 0;
  46330. this._animation = animation;
  46331. this._target = target;
  46332. animation._runtimeAnimations.push(this);
  46333. }
  46334. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46335. get: function () {
  46336. return this._animation;
  46337. },
  46338. enumerable: true,
  46339. configurable: true
  46340. });
  46341. RuntimeAnimation.prototype.reset = function () {
  46342. this._offsetsCache = {};
  46343. this._highLimitsCache = {};
  46344. this.currentFrame = 0;
  46345. this._blendingFactor = 0;
  46346. this._originalBlendValue = null;
  46347. };
  46348. RuntimeAnimation.prototype.isStopped = function () {
  46349. return this._stopped;
  46350. };
  46351. RuntimeAnimation.prototype.dispose = function () {
  46352. var index = this._animation.runtimeAnimations.indexOf(this);
  46353. if (index > -1) {
  46354. this._animation.runtimeAnimations.splice(index, 1);
  46355. }
  46356. };
  46357. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46358. if (typeof value === "function") {
  46359. return value();
  46360. }
  46361. return value;
  46362. };
  46363. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46364. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46365. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46366. }
  46367. this.currentFrame = currentFrame;
  46368. var keys = this._animation.getKeys();
  46369. // Try to get a hash to find the right key
  46370. 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));
  46371. if (keys[startKeyIndex].frame >= currentFrame) {
  46372. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46373. startKeyIndex--;
  46374. }
  46375. }
  46376. for (var key = startKeyIndex; key < keys.length; key++) {
  46377. var endKey = keys[key + 1];
  46378. if (endKey.frame >= currentFrame) {
  46379. var startKey = keys[key];
  46380. var startValue = this._getKeyValue(startKey.value);
  46381. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46382. return startValue;
  46383. }
  46384. var endValue = this._getKeyValue(endKey.value);
  46385. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46386. var frameDelta = endKey.frame - startKey.frame;
  46387. // gradient : percent of currentFrame between the frame inf and the frame sup
  46388. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46389. // check for easingFunction and correction of gradient
  46390. var easingFunction = this._animation.getEasingFunction();
  46391. if (easingFunction != null) {
  46392. gradient = easingFunction.ease(gradient);
  46393. }
  46394. switch (this._animation.dataType) {
  46395. // Float
  46396. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46397. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46398. switch (loopMode) {
  46399. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46400. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46401. return floatValue;
  46402. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46403. return offsetValue * repeatCount + floatValue;
  46404. }
  46405. break;
  46406. // Quaternion
  46407. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46408. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46409. switch (loopMode) {
  46410. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46411. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46412. return quatValue;
  46413. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46414. return quatValue.add(offsetValue.scale(repeatCount));
  46415. }
  46416. return quatValue;
  46417. // Vector3
  46418. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46419. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46420. switch (loopMode) {
  46421. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46422. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46423. return vec3Value;
  46424. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46425. return vec3Value.add(offsetValue.scale(repeatCount));
  46426. }
  46427. // Vector2
  46428. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46429. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46430. switch (loopMode) {
  46431. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46432. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46433. return vec2Value;
  46434. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46435. return vec2Value.add(offsetValue.scale(repeatCount));
  46436. }
  46437. // Size
  46438. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46439. switch (loopMode) {
  46440. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46441. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46442. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46443. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46444. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46445. }
  46446. // Color3
  46447. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46448. switch (loopMode) {
  46449. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46450. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46451. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46452. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46453. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46454. }
  46455. // Matrix
  46456. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46457. switch (loopMode) {
  46458. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46459. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46460. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46461. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46462. }
  46463. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46464. return startValue;
  46465. }
  46466. default:
  46467. break;
  46468. }
  46469. break;
  46470. }
  46471. }
  46472. return this._getKeyValue(keys[keys.length - 1].value);
  46473. };
  46474. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46475. if (blend === void 0) { blend = false; }
  46476. // Set value
  46477. var path;
  46478. var destination;
  46479. var targetPropertyPath = this._animation.targetPropertyPath;
  46480. if (targetPropertyPath.length > 1) {
  46481. var property = this._target[targetPropertyPath[0]];
  46482. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46483. property = property[targetPropertyPath[index]];
  46484. }
  46485. path = targetPropertyPath[targetPropertyPath.length - 1];
  46486. destination = property;
  46487. }
  46488. else {
  46489. path = targetPropertyPath[0];
  46490. destination = this._target;
  46491. }
  46492. // Blending
  46493. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46494. if (!this._originalBlendValue) {
  46495. if (destination[path].clone) {
  46496. this._originalBlendValue = destination[path].clone();
  46497. }
  46498. else {
  46499. this._originalBlendValue = destination[path];
  46500. }
  46501. }
  46502. if (this._originalBlendValue.prototype) {
  46503. if (this._originalBlendValue.prototype.Lerp) {
  46504. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46505. }
  46506. else {
  46507. destination[path] = currentValue;
  46508. }
  46509. }
  46510. else if (this._originalBlendValue.m) {
  46511. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46512. }
  46513. else {
  46514. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46515. }
  46516. this._blendingFactor += this._animation.blendingSpeed;
  46517. }
  46518. else {
  46519. destination[path] = currentValue;
  46520. }
  46521. if (this._target.markAsDirty) {
  46522. this._target.markAsDirty(this._animation.targetProperty);
  46523. }
  46524. };
  46525. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46526. var keys = this._animation.getKeys();
  46527. if (frame < keys[0].frame) {
  46528. frame = keys[0].frame;
  46529. }
  46530. else if (frame > keys[keys.length - 1].frame) {
  46531. frame = keys[keys.length - 1].frame;
  46532. }
  46533. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46534. this.setValue(currentValue);
  46535. };
  46536. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46537. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46538. this._ratioOffset = this._previousRatio - newRatio;
  46539. };
  46540. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46541. if (blend === void 0) { blend = false; }
  46542. var targetPropertyPath = this._animation.targetPropertyPath;
  46543. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46544. this._stopped = true;
  46545. return false;
  46546. }
  46547. var returnValue = true;
  46548. var keys = this._animation.getKeys();
  46549. // Adding a start key at frame 0 if missing
  46550. if (keys[0].frame !== 0) {
  46551. var newKey = { frame: 0, value: keys[0].value };
  46552. keys.splice(0, 0, newKey);
  46553. }
  46554. // Check limits
  46555. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46556. from = keys[0].frame;
  46557. }
  46558. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46559. to = keys[keys.length - 1].frame;
  46560. }
  46561. //to and from cannot be the same key
  46562. if (from === to) {
  46563. if (from > keys[0].frame) {
  46564. from--;
  46565. }
  46566. else if (to < keys[keys.length - 1].frame) {
  46567. to++;
  46568. }
  46569. }
  46570. // Compute ratio
  46571. var range = to - from;
  46572. var offsetValue;
  46573. // ratio represents the frame delta between from and to
  46574. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46575. var highLimitValue = 0;
  46576. this._previousDelay = delay;
  46577. this._previousRatio = ratio;
  46578. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46579. returnValue = false;
  46580. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46581. }
  46582. else {
  46583. // Get max value if required
  46584. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46585. var keyOffset = to.toString() + from.toString();
  46586. if (!this._offsetsCache[keyOffset]) {
  46587. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46588. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46589. switch (this._animation.dataType) {
  46590. // Float
  46591. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46592. this._offsetsCache[keyOffset] = toValue - fromValue;
  46593. break;
  46594. // Quaternion
  46595. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46596. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46597. break;
  46598. // Vector3
  46599. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46600. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46601. // Vector2
  46602. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46603. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46604. // Size
  46605. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46606. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46607. // Color3
  46608. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46609. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46610. default:
  46611. break;
  46612. }
  46613. this._highLimitsCache[keyOffset] = toValue;
  46614. }
  46615. highLimitValue = this._highLimitsCache[keyOffset];
  46616. offsetValue = this._offsetsCache[keyOffset];
  46617. }
  46618. }
  46619. if (offsetValue === undefined) {
  46620. switch (this._animation.dataType) {
  46621. // Float
  46622. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46623. offsetValue = 0;
  46624. break;
  46625. // Quaternion
  46626. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46627. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46628. break;
  46629. // Vector3
  46630. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46631. offsetValue = BABYLON.Vector3.Zero();
  46632. break;
  46633. // Vector2
  46634. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46635. offsetValue = BABYLON.Vector2.Zero();
  46636. break;
  46637. // Size
  46638. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46639. offsetValue = BABYLON.Size.Zero();
  46640. break;
  46641. // Color3
  46642. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46643. offsetValue = BABYLON.Color3.Black();
  46644. }
  46645. }
  46646. // Compute value
  46647. var repeatCount = (ratio / range) >> 0;
  46648. var currentFrame = returnValue ? from + ratio % range : to;
  46649. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46650. // Set value
  46651. this.setValue(currentValue);
  46652. // Check events
  46653. var events = this._animation.getEvents();
  46654. for (var index = 0; index < events.length; index++) {
  46655. // Make sure current frame has passed event frame and that event frame is within the current range
  46656. // Also, handle both forward and reverse animations
  46657. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46658. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46659. var event = events[index];
  46660. if (!event.isDone) {
  46661. // If event should be done only once, remove it.
  46662. if (event.onlyOnce) {
  46663. events.splice(index, 1);
  46664. index--;
  46665. }
  46666. event.isDone = true;
  46667. event.action();
  46668. } // Don't do anything if the event has already be done.
  46669. }
  46670. else if (events[index].isDone && !events[index].onlyOnce) {
  46671. // reset event, the animation is looping
  46672. events[index].isDone = false;
  46673. }
  46674. }
  46675. if (!returnValue) {
  46676. this._stopped = true;
  46677. }
  46678. return returnValue;
  46679. };
  46680. return RuntimeAnimation;
  46681. }());
  46682. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46683. })(BABYLON || (BABYLON = {}));
  46684. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46685. var BABYLON;
  46686. (function (BABYLON) {
  46687. var Animatable = /** @class */ (function () {
  46688. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46689. if (fromFrame === void 0) { fromFrame = 0; }
  46690. if (toFrame === void 0) { toFrame = 100; }
  46691. if (loopAnimation === void 0) { loopAnimation = false; }
  46692. if (speedRatio === void 0) { speedRatio = 1.0; }
  46693. this.target = target;
  46694. this.fromFrame = fromFrame;
  46695. this.toFrame = toFrame;
  46696. this.loopAnimation = loopAnimation;
  46697. this.onAnimationEnd = onAnimationEnd;
  46698. this._localDelayOffset = null;
  46699. this._pausedDelay = null;
  46700. this._runtimeAnimations = new Array();
  46701. this._paused = false;
  46702. this._speedRatio = 1;
  46703. this.animationStarted = false;
  46704. if (animations) {
  46705. this.appendAnimations(target, animations);
  46706. }
  46707. this._speedRatio = speedRatio;
  46708. this._scene = scene;
  46709. scene._activeAnimatables.push(this);
  46710. }
  46711. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46712. get: function () {
  46713. return this._speedRatio;
  46714. },
  46715. set: function (value) {
  46716. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46717. var animation = this._runtimeAnimations[index];
  46718. animation._prepareForSpeedRatioChange(value);
  46719. }
  46720. this._speedRatio = value;
  46721. },
  46722. enumerable: true,
  46723. configurable: true
  46724. });
  46725. // Methods
  46726. Animatable.prototype.getAnimations = function () {
  46727. return this._runtimeAnimations;
  46728. };
  46729. Animatable.prototype.appendAnimations = function (target, animations) {
  46730. for (var index = 0; index < animations.length; index++) {
  46731. var animation = animations[index];
  46732. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46733. }
  46734. };
  46735. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46736. var runtimeAnimations = this._runtimeAnimations;
  46737. for (var index = 0; index < runtimeAnimations.length; index++) {
  46738. if (runtimeAnimations[index].animation.targetProperty === property) {
  46739. return runtimeAnimations[index].animation;
  46740. }
  46741. }
  46742. return null;
  46743. };
  46744. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46745. var runtimeAnimations = this._runtimeAnimations;
  46746. for (var index = 0; index < runtimeAnimations.length; index++) {
  46747. if (runtimeAnimations[index].animation.targetProperty === property) {
  46748. return runtimeAnimations[index];
  46749. }
  46750. }
  46751. return null;
  46752. };
  46753. Animatable.prototype.reset = function () {
  46754. var runtimeAnimations = this._runtimeAnimations;
  46755. for (var index = 0; index < runtimeAnimations.length; index++) {
  46756. runtimeAnimations[index].reset();
  46757. }
  46758. // Reset to original value
  46759. for (index = 0; index < runtimeAnimations.length; index++) {
  46760. var animation = runtimeAnimations[index];
  46761. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46762. }
  46763. this._localDelayOffset = null;
  46764. this._pausedDelay = null;
  46765. };
  46766. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46767. var runtimeAnimations = this._runtimeAnimations;
  46768. for (var index = 0; index < runtimeAnimations.length; index++) {
  46769. runtimeAnimations[index].animation.enableBlending = true;
  46770. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46771. }
  46772. };
  46773. Animatable.prototype.disableBlending = function () {
  46774. var runtimeAnimations = this._runtimeAnimations;
  46775. for (var index = 0; index < runtimeAnimations.length; index++) {
  46776. runtimeAnimations[index].animation.enableBlending = false;
  46777. }
  46778. };
  46779. Animatable.prototype.goToFrame = function (frame) {
  46780. var runtimeAnimations = this._runtimeAnimations;
  46781. if (runtimeAnimations[0]) {
  46782. var fps = runtimeAnimations[0].animation.framePerSecond;
  46783. var currentFrame = runtimeAnimations[0].currentFrame;
  46784. var adjustTime = frame - currentFrame;
  46785. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  46786. if (this._localDelayOffset === null) {
  46787. this._localDelayOffset = 0;
  46788. }
  46789. this._localDelayOffset -= delay;
  46790. }
  46791. for (var index = 0; index < runtimeAnimations.length; index++) {
  46792. runtimeAnimations[index].goToFrame(frame);
  46793. }
  46794. };
  46795. Animatable.prototype.pause = function () {
  46796. if (this._paused) {
  46797. return;
  46798. }
  46799. this._paused = true;
  46800. };
  46801. Animatable.prototype.restart = function () {
  46802. this._paused = false;
  46803. };
  46804. Animatable.prototype.stop = function (animationName) {
  46805. if (animationName) {
  46806. var idx = this._scene._activeAnimatables.indexOf(this);
  46807. if (idx > -1) {
  46808. var runtimeAnimations = this._runtimeAnimations;
  46809. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46810. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46811. continue;
  46812. }
  46813. runtimeAnimations[index].dispose();
  46814. runtimeAnimations.splice(index, 1);
  46815. }
  46816. if (runtimeAnimations.length == 0) {
  46817. this._scene._activeAnimatables.splice(idx, 1);
  46818. if (this.onAnimationEnd) {
  46819. this.onAnimationEnd();
  46820. }
  46821. }
  46822. }
  46823. }
  46824. else {
  46825. var index = this._scene._activeAnimatables.indexOf(this);
  46826. if (index > -1) {
  46827. this._scene._activeAnimatables.splice(index, 1);
  46828. var runtimeAnimations = this._runtimeAnimations;
  46829. for (var index = 0; index < runtimeAnimations.length; index++) {
  46830. runtimeAnimations[index].dispose();
  46831. }
  46832. if (this.onAnimationEnd) {
  46833. this.onAnimationEnd();
  46834. }
  46835. }
  46836. }
  46837. };
  46838. Animatable.prototype._animate = function (delay) {
  46839. if (this._paused) {
  46840. this.animationStarted = false;
  46841. if (this._pausedDelay === null) {
  46842. this._pausedDelay = delay;
  46843. }
  46844. return true;
  46845. }
  46846. if (this._localDelayOffset === null) {
  46847. this._localDelayOffset = delay;
  46848. this._pausedDelay = null;
  46849. }
  46850. else if (this._pausedDelay !== null) {
  46851. this._localDelayOffset += delay - this._pausedDelay;
  46852. this._pausedDelay = null;
  46853. }
  46854. // Animating
  46855. var running = false;
  46856. var runtimeAnimations = this._runtimeAnimations;
  46857. var index;
  46858. for (index = 0; index < runtimeAnimations.length; index++) {
  46859. var animation = runtimeAnimations[index];
  46860. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46861. running = running || isRunning;
  46862. }
  46863. this.animationStarted = running;
  46864. if (!running) {
  46865. // Remove from active animatables
  46866. index = this._scene._activeAnimatables.indexOf(this);
  46867. this._scene._activeAnimatables.splice(index, 1);
  46868. // Dispose all runtime animations
  46869. for (index = 0; index < runtimeAnimations.length; index++) {
  46870. runtimeAnimations[index].dispose();
  46871. }
  46872. }
  46873. if (!running && this.onAnimationEnd) {
  46874. this.onAnimationEnd();
  46875. this.onAnimationEnd = null;
  46876. }
  46877. return running;
  46878. };
  46879. return Animatable;
  46880. }());
  46881. BABYLON.Animatable = Animatable;
  46882. })(BABYLON || (BABYLON = {}));
  46883. //# sourceMappingURL=babylon.animatable.js.map
  46884. var BABYLON;
  46885. (function (BABYLON) {
  46886. var EasingFunction = /** @class */ (function () {
  46887. function EasingFunction() {
  46888. // Properties
  46889. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46890. }
  46891. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46892. get: function () {
  46893. return EasingFunction._EASINGMODE_EASEIN;
  46894. },
  46895. enumerable: true,
  46896. configurable: true
  46897. });
  46898. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46899. get: function () {
  46900. return EasingFunction._EASINGMODE_EASEOUT;
  46901. },
  46902. enumerable: true,
  46903. configurable: true
  46904. });
  46905. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46906. get: function () {
  46907. return EasingFunction._EASINGMODE_EASEINOUT;
  46908. },
  46909. enumerable: true,
  46910. configurable: true
  46911. });
  46912. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46913. var n = Math.min(Math.max(easingMode, 0), 2);
  46914. this._easingMode = n;
  46915. };
  46916. EasingFunction.prototype.getEasingMode = function () {
  46917. return this._easingMode;
  46918. };
  46919. EasingFunction.prototype.easeInCore = function (gradient) {
  46920. throw new Error('You must implement this method');
  46921. };
  46922. EasingFunction.prototype.ease = function (gradient) {
  46923. switch (this._easingMode) {
  46924. case EasingFunction.EASINGMODE_EASEIN:
  46925. return this.easeInCore(gradient);
  46926. case EasingFunction.EASINGMODE_EASEOUT:
  46927. return (1 - this.easeInCore(1 - gradient));
  46928. }
  46929. if (gradient >= 0.5) {
  46930. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46931. }
  46932. return (this.easeInCore(gradient * 2) * 0.5);
  46933. };
  46934. //Statics
  46935. EasingFunction._EASINGMODE_EASEIN = 0;
  46936. EasingFunction._EASINGMODE_EASEOUT = 1;
  46937. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46938. return EasingFunction;
  46939. }());
  46940. BABYLON.EasingFunction = EasingFunction;
  46941. var CircleEase = /** @class */ (function (_super) {
  46942. __extends(CircleEase, _super);
  46943. function CircleEase() {
  46944. return _super !== null && _super.apply(this, arguments) || this;
  46945. }
  46946. CircleEase.prototype.easeInCore = function (gradient) {
  46947. gradient = Math.max(0, Math.min(1, gradient));
  46948. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46949. };
  46950. return CircleEase;
  46951. }(EasingFunction));
  46952. BABYLON.CircleEase = CircleEase;
  46953. var BackEase = /** @class */ (function (_super) {
  46954. __extends(BackEase, _super);
  46955. function BackEase(amplitude) {
  46956. if (amplitude === void 0) { amplitude = 1; }
  46957. var _this = _super.call(this) || this;
  46958. _this.amplitude = amplitude;
  46959. return _this;
  46960. }
  46961. BackEase.prototype.easeInCore = function (gradient) {
  46962. var num = Math.max(0, this.amplitude);
  46963. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46964. };
  46965. return BackEase;
  46966. }(EasingFunction));
  46967. BABYLON.BackEase = BackEase;
  46968. var BounceEase = /** @class */ (function (_super) {
  46969. __extends(BounceEase, _super);
  46970. function BounceEase(bounces, bounciness) {
  46971. if (bounces === void 0) { bounces = 3; }
  46972. if (bounciness === void 0) { bounciness = 2; }
  46973. var _this = _super.call(this) || this;
  46974. _this.bounces = bounces;
  46975. _this.bounciness = bounciness;
  46976. return _this;
  46977. }
  46978. BounceEase.prototype.easeInCore = function (gradient) {
  46979. var y = Math.max(0.0, this.bounces);
  46980. var bounciness = this.bounciness;
  46981. if (bounciness <= 1.0) {
  46982. bounciness = 1.001;
  46983. }
  46984. var num9 = Math.pow(bounciness, y);
  46985. var num5 = 1.0 - bounciness;
  46986. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46987. var num15 = gradient * num4;
  46988. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46989. var num3 = Math.floor(num65);
  46990. var num13 = num3 + 1.0;
  46991. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46992. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46993. var num7 = (num8 + num12) * 0.5;
  46994. var num6 = gradient - num7;
  46995. var num2 = num7 - num8;
  46996. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46997. };
  46998. return BounceEase;
  46999. }(EasingFunction));
  47000. BABYLON.BounceEase = BounceEase;
  47001. var CubicEase = /** @class */ (function (_super) {
  47002. __extends(CubicEase, _super);
  47003. function CubicEase() {
  47004. return _super !== null && _super.apply(this, arguments) || this;
  47005. }
  47006. CubicEase.prototype.easeInCore = function (gradient) {
  47007. return (gradient * gradient * gradient);
  47008. };
  47009. return CubicEase;
  47010. }(EasingFunction));
  47011. BABYLON.CubicEase = CubicEase;
  47012. var ElasticEase = /** @class */ (function (_super) {
  47013. __extends(ElasticEase, _super);
  47014. function ElasticEase(oscillations, springiness) {
  47015. if (oscillations === void 0) { oscillations = 3; }
  47016. if (springiness === void 0) { springiness = 3; }
  47017. var _this = _super.call(this) || this;
  47018. _this.oscillations = oscillations;
  47019. _this.springiness = springiness;
  47020. return _this;
  47021. }
  47022. ElasticEase.prototype.easeInCore = function (gradient) {
  47023. var num2;
  47024. var num3 = Math.max(0.0, this.oscillations);
  47025. var num = Math.max(0.0, this.springiness);
  47026. if (num == 0) {
  47027. num2 = gradient;
  47028. }
  47029. else {
  47030. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47031. }
  47032. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47033. };
  47034. return ElasticEase;
  47035. }(EasingFunction));
  47036. BABYLON.ElasticEase = ElasticEase;
  47037. var ExponentialEase = /** @class */ (function (_super) {
  47038. __extends(ExponentialEase, _super);
  47039. function ExponentialEase(exponent) {
  47040. if (exponent === void 0) { exponent = 2; }
  47041. var _this = _super.call(this) || this;
  47042. _this.exponent = exponent;
  47043. return _this;
  47044. }
  47045. ExponentialEase.prototype.easeInCore = function (gradient) {
  47046. if (this.exponent <= 0) {
  47047. return gradient;
  47048. }
  47049. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47050. };
  47051. return ExponentialEase;
  47052. }(EasingFunction));
  47053. BABYLON.ExponentialEase = ExponentialEase;
  47054. var PowerEase = /** @class */ (function (_super) {
  47055. __extends(PowerEase, _super);
  47056. function PowerEase(power) {
  47057. if (power === void 0) { power = 2; }
  47058. var _this = _super.call(this) || this;
  47059. _this.power = power;
  47060. return _this;
  47061. }
  47062. PowerEase.prototype.easeInCore = function (gradient) {
  47063. var y = Math.max(0.0, this.power);
  47064. return Math.pow(gradient, y);
  47065. };
  47066. return PowerEase;
  47067. }(EasingFunction));
  47068. BABYLON.PowerEase = PowerEase;
  47069. var QuadraticEase = /** @class */ (function (_super) {
  47070. __extends(QuadraticEase, _super);
  47071. function QuadraticEase() {
  47072. return _super !== null && _super.apply(this, arguments) || this;
  47073. }
  47074. QuadraticEase.prototype.easeInCore = function (gradient) {
  47075. return (gradient * gradient);
  47076. };
  47077. return QuadraticEase;
  47078. }(EasingFunction));
  47079. BABYLON.QuadraticEase = QuadraticEase;
  47080. var QuarticEase = /** @class */ (function (_super) {
  47081. __extends(QuarticEase, _super);
  47082. function QuarticEase() {
  47083. return _super !== null && _super.apply(this, arguments) || this;
  47084. }
  47085. QuarticEase.prototype.easeInCore = function (gradient) {
  47086. return (gradient * gradient * gradient * gradient);
  47087. };
  47088. return QuarticEase;
  47089. }(EasingFunction));
  47090. BABYLON.QuarticEase = QuarticEase;
  47091. var QuinticEase = /** @class */ (function (_super) {
  47092. __extends(QuinticEase, _super);
  47093. function QuinticEase() {
  47094. return _super !== null && _super.apply(this, arguments) || this;
  47095. }
  47096. QuinticEase.prototype.easeInCore = function (gradient) {
  47097. return (gradient * gradient * gradient * gradient * gradient);
  47098. };
  47099. return QuinticEase;
  47100. }(EasingFunction));
  47101. BABYLON.QuinticEase = QuinticEase;
  47102. var SineEase = /** @class */ (function (_super) {
  47103. __extends(SineEase, _super);
  47104. function SineEase() {
  47105. return _super !== null && _super.apply(this, arguments) || this;
  47106. }
  47107. SineEase.prototype.easeInCore = function (gradient) {
  47108. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47109. };
  47110. return SineEase;
  47111. }(EasingFunction));
  47112. BABYLON.SineEase = SineEase;
  47113. var BezierCurveEase = /** @class */ (function (_super) {
  47114. __extends(BezierCurveEase, _super);
  47115. function BezierCurveEase(x1, y1, x2, y2) {
  47116. if (x1 === void 0) { x1 = 0; }
  47117. if (y1 === void 0) { y1 = 0; }
  47118. if (x2 === void 0) { x2 = 1; }
  47119. if (y2 === void 0) { y2 = 1; }
  47120. var _this = _super.call(this) || this;
  47121. _this.x1 = x1;
  47122. _this.y1 = y1;
  47123. _this.x2 = x2;
  47124. _this.y2 = y2;
  47125. return _this;
  47126. }
  47127. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47128. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47129. };
  47130. return BezierCurveEase;
  47131. }(EasingFunction));
  47132. BABYLON.BezierCurveEase = BezierCurveEase;
  47133. })(BABYLON || (BABYLON = {}));
  47134. //# sourceMappingURL=babylon.easing.js.map
  47135. var BABYLON;
  47136. (function (BABYLON) {
  47137. var Condition = /** @class */ (function () {
  47138. function Condition(actionManager) {
  47139. this._actionManager = actionManager;
  47140. }
  47141. Condition.prototype.isValid = function () {
  47142. return true;
  47143. };
  47144. Condition.prototype._getProperty = function (propertyPath) {
  47145. return this._actionManager._getProperty(propertyPath);
  47146. };
  47147. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47148. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47149. };
  47150. Condition.prototype.serialize = function () {
  47151. };
  47152. Condition.prototype._serialize = function (serializedCondition) {
  47153. return {
  47154. type: 2,
  47155. children: [],
  47156. name: serializedCondition.name,
  47157. properties: serializedCondition.properties
  47158. };
  47159. };
  47160. return Condition;
  47161. }());
  47162. BABYLON.Condition = Condition;
  47163. var ValueCondition = /** @class */ (function (_super) {
  47164. __extends(ValueCondition, _super);
  47165. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47166. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47167. var _this = _super.call(this, actionManager) || this;
  47168. _this.propertyPath = propertyPath;
  47169. _this.value = value;
  47170. _this.operator = operator;
  47171. _this._target = target;
  47172. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47173. _this._property = _this._getProperty(_this.propertyPath);
  47174. return _this;
  47175. }
  47176. Object.defineProperty(ValueCondition, "IsEqual", {
  47177. get: function () {
  47178. return ValueCondition._IsEqual;
  47179. },
  47180. enumerable: true,
  47181. configurable: true
  47182. });
  47183. Object.defineProperty(ValueCondition, "IsDifferent", {
  47184. get: function () {
  47185. return ValueCondition._IsDifferent;
  47186. },
  47187. enumerable: true,
  47188. configurable: true
  47189. });
  47190. Object.defineProperty(ValueCondition, "IsGreater", {
  47191. get: function () {
  47192. return ValueCondition._IsGreater;
  47193. },
  47194. enumerable: true,
  47195. configurable: true
  47196. });
  47197. Object.defineProperty(ValueCondition, "IsLesser", {
  47198. get: function () {
  47199. return ValueCondition._IsLesser;
  47200. },
  47201. enumerable: true,
  47202. configurable: true
  47203. });
  47204. // Methods
  47205. ValueCondition.prototype.isValid = function () {
  47206. switch (this.operator) {
  47207. case ValueCondition.IsGreater:
  47208. return this._effectiveTarget[this._property] > this.value;
  47209. case ValueCondition.IsLesser:
  47210. return this._effectiveTarget[this._property] < this.value;
  47211. case ValueCondition.IsEqual:
  47212. case ValueCondition.IsDifferent:
  47213. var check;
  47214. if (this.value.equals) {
  47215. check = this.value.equals(this._effectiveTarget[this._property]);
  47216. }
  47217. else {
  47218. check = this.value === this._effectiveTarget[this._property];
  47219. }
  47220. return this.operator === ValueCondition.IsEqual ? check : !check;
  47221. }
  47222. return false;
  47223. };
  47224. ValueCondition.prototype.serialize = function () {
  47225. return this._serialize({
  47226. name: "ValueCondition",
  47227. properties: [
  47228. BABYLON.Action._GetTargetProperty(this._target),
  47229. { name: "propertyPath", value: this.propertyPath },
  47230. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47231. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47232. ]
  47233. });
  47234. };
  47235. ValueCondition.GetOperatorName = function (operator) {
  47236. switch (operator) {
  47237. case ValueCondition._IsEqual: return "IsEqual";
  47238. case ValueCondition._IsDifferent: return "IsDifferent";
  47239. case ValueCondition._IsGreater: return "IsGreater";
  47240. case ValueCondition._IsLesser: return "IsLesser";
  47241. default: return "";
  47242. }
  47243. };
  47244. // Statics
  47245. ValueCondition._IsEqual = 0;
  47246. ValueCondition._IsDifferent = 1;
  47247. ValueCondition._IsGreater = 2;
  47248. ValueCondition._IsLesser = 3;
  47249. return ValueCondition;
  47250. }(Condition));
  47251. BABYLON.ValueCondition = ValueCondition;
  47252. var PredicateCondition = /** @class */ (function (_super) {
  47253. __extends(PredicateCondition, _super);
  47254. function PredicateCondition(actionManager, predicate) {
  47255. var _this = _super.call(this, actionManager) || this;
  47256. _this.predicate = predicate;
  47257. return _this;
  47258. }
  47259. PredicateCondition.prototype.isValid = function () {
  47260. return this.predicate();
  47261. };
  47262. return PredicateCondition;
  47263. }(Condition));
  47264. BABYLON.PredicateCondition = PredicateCondition;
  47265. var StateCondition = /** @class */ (function (_super) {
  47266. __extends(StateCondition, _super);
  47267. function StateCondition(actionManager, target, value) {
  47268. var _this = _super.call(this, actionManager) || this;
  47269. _this.value = value;
  47270. _this._target = target;
  47271. return _this;
  47272. }
  47273. // Methods
  47274. StateCondition.prototype.isValid = function () {
  47275. return this._target.state === this.value;
  47276. };
  47277. StateCondition.prototype.serialize = function () {
  47278. return this._serialize({
  47279. name: "StateCondition",
  47280. properties: [
  47281. BABYLON.Action._GetTargetProperty(this._target),
  47282. { name: "value", value: this.value }
  47283. ]
  47284. });
  47285. };
  47286. return StateCondition;
  47287. }(Condition));
  47288. BABYLON.StateCondition = StateCondition;
  47289. })(BABYLON || (BABYLON = {}));
  47290. //# sourceMappingURL=babylon.condition.js.map
  47291. var BABYLON;
  47292. (function (BABYLON) {
  47293. var Action = /** @class */ (function () {
  47294. function Action(triggerOptions, condition) {
  47295. this.triggerOptions = triggerOptions;
  47296. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47297. if (triggerOptions.parameter) {
  47298. this.trigger = triggerOptions.trigger;
  47299. this._triggerParameter = triggerOptions.parameter;
  47300. }
  47301. else {
  47302. this.trigger = triggerOptions;
  47303. }
  47304. this._nextActiveAction = this;
  47305. this._condition = condition;
  47306. }
  47307. // Methods
  47308. Action.prototype._prepare = function () {
  47309. };
  47310. Action.prototype.getTriggerParameter = function () {
  47311. return this._triggerParameter;
  47312. };
  47313. Action.prototype._executeCurrent = function (evt) {
  47314. if (this._nextActiveAction._condition) {
  47315. var condition = this._nextActiveAction._condition;
  47316. var currentRenderId = this._actionManager.getScene().getRenderId();
  47317. // We cache the current evaluation for the current frame
  47318. if (condition._evaluationId === currentRenderId) {
  47319. if (!condition._currentResult) {
  47320. return;
  47321. }
  47322. }
  47323. else {
  47324. condition._evaluationId = currentRenderId;
  47325. if (!condition.isValid()) {
  47326. condition._currentResult = false;
  47327. return;
  47328. }
  47329. condition._currentResult = true;
  47330. }
  47331. }
  47332. this.onBeforeExecuteObservable.notifyObservers(this);
  47333. this._nextActiveAction.execute(evt);
  47334. this.skipToNextActiveAction();
  47335. };
  47336. Action.prototype.execute = function (evt) {
  47337. };
  47338. Action.prototype.skipToNextActiveAction = function () {
  47339. if (this._nextActiveAction._child) {
  47340. if (!this._nextActiveAction._child._actionManager) {
  47341. this._nextActiveAction._child._actionManager = this._actionManager;
  47342. }
  47343. this._nextActiveAction = this._nextActiveAction._child;
  47344. }
  47345. else {
  47346. this._nextActiveAction = this;
  47347. }
  47348. };
  47349. Action.prototype.then = function (action) {
  47350. this._child = action;
  47351. action._actionManager = this._actionManager;
  47352. action._prepare();
  47353. return action;
  47354. };
  47355. Action.prototype._getProperty = function (propertyPath) {
  47356. return this._actionManager._getProperty(propertyPath);
  47357. };
  47358. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47359. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47360. };
  47361. Action.prototype.serialize = function (parent) {
  47362. };
  47363. // Called by BABYLON.Action objects in serialize(...). Internal use
  47364. Action.prototype._serialize = function (serializedAction, parent) {
  47365. var serializationObject = {
  47366. type: 1,
  47367. children: [],
  47368. name: serializedAction.name,
  47369. properties: serializedAction.properties || []
  47370. };
  47371. // Serialize child
  47372. if (this._child) {
  47373. this._child.serialize(serializationObject);
  47374. }
  47375. // Check if "this" has a condition
  47376. if (this._condition) {
  47377. var serializedCondition = this._condition.serialize();
  47378. serializedCondition.children.push(serializationObject);
  47379. if (parent) {
  47380. parent.children.push(serializedCondition);
  47381. }
  47382. return serializedCondition;
  47383. }
  47384. if (parent) {
  47385. parent.children.push(serializationObject);
  47386. }
  47387. return serializationObject;
  47388. };
  47389. Action._SerializeValueAsString = function (value) {
  47390. if (typeof value === "number") {
  47391. return value.toString();
  47392. }
  47393. if (typeof value === "boolean") {
  47394. return value ? "true" : "false";
  47395. }
  47396. if (value instanceof BABYLON.Vector2) {
  47397. return value.x + ", " + value.y;
  47398. }
  47399. if (value instanceof BABYLON.Vector3) {
  47400. return value.x + ", " + value.y + ", " + value.z;
  47401. }
  47402. if (value instanceof BABYLON.Color3) {
  47403. return value.r + ", " + value.g + ", " + value.b;
  47404. }
  47405. if (value instanceof BABYLON.Color4) {
  47406. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47407. }
  47408. return value; // string
  47409. };
  47410. Action._GetTargetProperty = function (target) {
  47411. return {
  47412. name: "target",
  47413. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47414. : target instanceof BABYLON.Light ? "LightProperties"
  47415. : target instanceof BABYLON.Camera ? "CameraProperties"
  47416. : "SceneProperties",
  47417. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47418. };
  47419. };
  47420. return Action;
  47421. }());
  47422. BABYLON.Action = Action;
  47423. })(BABYLON || (BABYLON = {}));
  47424. //# sourceMappingURL=babylon.action.js.map
  47425. var BABYLON;
  47426. (function (BABYLON) {
  47427. /**
  47428. * ActionEvent is the event beint sent when an action is triggered.
  47429. */
  47430. var ActionEvent = /** @class */ (function () {
  47431. /**
  47432. * @param source The mesh or sprite that triggered the action.
  47433. * @param pointerX The X mouse cursor position at the time of the event
  47434. * @param pointerY The Y mouse cursor position at the time of the event
  47435. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47436. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47437. */
  47438. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47439. this.source = source;
  47440. this.pointerX = pointerX;
  47441. this.pointerY = pointerY;
  47442. this.meshUnderPointer = meshUnderPointer;
  47443. this.sourceEvent = sourceEvent;
  47444. this.additionalData = additionalData;
  47445. }
  47446. /**
  47447. * Helper function to auto-create an ActionEvent from a source mesh.
  47448. * @param source The source mesh that triggered the event
  47449. * @param evt {Event} The original (browser) event
  47450. */
  47451. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47452. var scene = source.getScene();
  47453. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47454. };
  47455. /**
  47456. * Helper function to auto-create an ActionEvent from a source mesh.
  47457. * @param source The source sprite that triggered the event
  47458. * @param scene Scene associated with the sprite
  47459. * @param evt {Event} The original (browser) event
  47460. */
  47461. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47462. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47463. };
  47464. /**
  47465. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47466. * @param scene the scene where the event occurred
  47467. * @param evt {Event} The original (browser) event
  47468. */
  47469. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47470. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47471. };
  47472. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47473. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47474. };
  47475. return ActionEvent;
  47476. }());
  47477. BABYLON.ActionEvent = ActionEvent;
  47478. /**
  47479. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47480. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47481. */
  47482. var ActionManager = /** @class */ (function () {
  47483. function ActionManager(scene) {
  47484. // Members
  47485. this.actions = new Array();
  47486. this.hoverCursor = '';
  47487. this._scene = scene;
  47488. scene._actionManagers.push(this);
  47489. }
  47490. Object.defineProperty(ActionManager, "NothingTrigger", {
  47491. get: function () {
  47492. return ActionManager._NothingTrigger;
  47493. },
  47494. enumerable: true,
  47495. configurable: true
  47496. });
  47497. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47498. get: function () {
  47499. return ActionManager._OnPickTrigger;
  47500. },
  47501. enumerable: true,
  47502. configurable: true
  47503. });
  47504. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47505. get: function () {
  47506. return ActionManager._OnLeftPickTrigger;
  47507. },
  47508. enumerable: true,
  47509. configurable: true
  47510. });
  47511. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47512. get: function () {
  47513. return ActionManager._OnRightPickTrigger;
  47514. },
  47515. enumerable: true,
  47516. configurable: true
  47517. });
  47518. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47519. get: function () {
  47520. return ActionManager._OnCenterPickTrigger;
  47521. },
  47522. enumerable: true,
  47523. configurable: true
  47524. });
  47525. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47526. get: function () {
  47527. return ActionManager._OnPickDownTrigger;
  47528. },
  47529. enumerable: true,
  47530. configurable: true
  47531. });
  47532. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47533. get: function () {
  47534. return ActionManager._OnDoublePickTrigger;
  47535. },
  47536. enumerable: true,
  47537. configurable: true
  47538. });
  47539. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47540. get: function () {
  47541. return ActionManager._OnPickUpTrigger;
  47542. },
  47543. enumerable: true,
  47544. configurable: true
  47545. });
  47546. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47547. /// This trigger will only be raised if you also declared a OnPickDown
  47548. get: function () {
  47549. return ActionManager._OnPickOutTrigger;
  47550. },
  47551. enumerable: true,
  47552. configurable: true
  47553. });
  47554. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47555. get: function () {
  47556. return ActionManager._OnLongPressTrigger;
  47557. },
  47558. enumerable: true,
  47559. configurable: true
  47560. });
  47561. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47562. get: function () {
  47563. return ActionManager._OnPointerOverTrigger;
  47564. },
  47565. enumerable: true,
  47566. configurable: true
  47567. });
  47568. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47569. get: function () {
  47570. return ActionManager._OnPointerOutTrigger;
  47571. },
  47572. enumerable: true,
  47573. configurable: true
  47574. });
  47575. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47576. get: function () {
  47577. return ActionManager._OnEveryFrameTrigger;
  47578. },
  47579. enumerable: true,
  47580. configurable: true
  47581. });
  47582. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47583. get: function () {
  47584. return ActionManager._OnIntersectionEnterTrigger;
  47585. },
  47586. enumerable: true,
  47587. configurable: true
  47588. });
  47589. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47590. get: function () {
  47591. return ActionManager._OnIntersectionExitTrigger;
  47592. },
  47593. enumerable: true,
  47594. configurable: true
  47595. });
  47596. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47597. get: function () {
  47598. return ActionManager._OnKeyDownTrigger;
  47599. },
  47600. enumerable: true,
  47601. configurable: true
  47602. });
  47603. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47604. get: function () {
  47605. return ActionManager._OnKeyUpTrigger;
  47606. },
  47607. enumerable: true,
  47608. configurable: true
  47609. });
  47610. // Methods
  47611. ActionManager.prototype.dispose = function () {
  47612. var index = this._scene._actionManagers.indexOf(this);
  47613. for (var i = 0; i < this.actions.length; i++) {
  47614. var action = this.actions[i];
  47615. ActionManager.Triggers[action.trigger]--;
  47616. if (ActionManager.Triggers[action.trigger] === 0) {
  47617. delete ActionManager.Triggers[action.trigger];
  47618. }
  47619. }
  47620. if (index > -1) {
  47621. this._scene._actionManagers.splice(index, 1);
  47622. }
  47623. };
  47624. ActionManager.prototype.getScene = function () {
  47625. return this._scene;
  47626. };
  47627. /**
  47628. * Does this action manager handles actions of any of the given triggers
  47629. * @param {number[]} triggers - the triggers to be tested
  47630. * @return {boolean} whether one (or more) of the triggers is handeled
  47631. */
  47632. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47633. for (var index = 0; index < this.actions.length; index++) {
  47634. var action = this.actions[index];
  47635. if (triggers.indexOf(action.trigger) > -1) {
  47636. return true;
  47637. }
  47638. }
  47639. return false;
  47640. };
  47641. /**
  47642. * Does this action manager handles actions of a given trigger
  47643. * @param {number} trigger - the trigger to be tested
  47644. * @return {boolean} whether the trigger is handeled
  47645. */
  47646. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47647. for (var index = 0; index < this.actions.length; index++) {
  47648. var action = this.actions[index];
  47649. if (action.trigger === trigger) {
  47650. return true;
  47651. }
  47652. }
  47653. return false;
  47654. };
  47655. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47656. /**
  47657. * Does this action manager has pointer triggers
  47658. * @return {boolean} whether or not it has pointer triggers
  47659. */
  47660. get: function () {
  47661. for (var index = 0; index < this.actions.length; index++) {
  47662. var action = this.actions[index];
  47663. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47664. return true;
  47665. }
  47666. }
  47667. return false;
  47668. },
  47669. enumerable: true,
  47670. configurable: true
  47671. });
  47672. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47673. /**
  47674. * Does this action manager has pick triggers
  47675. * @return {boolean} whether or not it has pick triggers
  47676. */
  47677. get: function () {
  47678. for (var index = 0; index < this.actions.length; index++) {
  47679. var action = this.actions[index];
  47680. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47681. return true;
  47682. }
  47683. }
  47684. return false;
  47685. },
  47686. enumerable: true,
  47687. configurable: true
  47688. });
  47689. Object.defineProperty(ActionManager, "HasTriggers", {
  47690. /**
  47691. * Does exist one action manager with at least one trigger
  47692. * @return {boolean} whether or not it exists one action manager with one trigger
  47693. **/
  47694. get: function () {
  47695. for (var t in ActionManager.Triggers) {
  47696. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47697. return true;
  47698. }
  47699. }
  47700. return false;
  47701. },
  47702. enumerable: true,
  47703. configurable: true
  47704. });
  47705. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47706. /**
  47707. * Does exist one action manager with at least one pick trigger
  47708. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47709. **/
  47710. get: function () {
  47711. for (var t in ActionManager.Triggers) {
  47712. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47713. var t_int = parseInt(t);
  47714. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47715. return true;
  47716. }
  47717. }
  47718. }
  47719. return false;
  47720. },
  47721. enumerable: true,
  47722. configurable: true
  47723. });
  47724. /**
  47725. * Does exist one action manager that handles actions of a given trigger
  47726. * @param {number} trigger - the trigger to be tested
  47727. * @return {boolean} whether the trigger is handeled by at least one action manager
  47728. **/
  47729. ActionManager.HasSpecificTrigger = function (trigger) {
  47730. for (var t in ActionManager.Triggers) {
  47731. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47732. var t_int = parseInt(t);
  47733. if (t_int === trigger) {
  47734. return true;
  47735. }
  47736. }
  47737. }
  47738. return false;
  47739. };
  47740. /**
  47741. * Registers an action to this action manager
  47742. * @param {BABYLON.Action} action - the action to be registered
  47743. * @return {BABYLON.Action} the action amended (prepared) after registration
  47744. */
  47745. ActionManager.prototype.registerAction = function (action) {
  47746. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47747. if (this.getScene().actionManager !== this) {
  47748. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47749. return null;
  47750. }
  47751. }
  47752. this.actions.push(action);
  47753. if (ActionManager.Triggers[action.trigger]) {
  47754. ActionManager.Triggers[action.trigger]++;
  47755. }
  47756. else {
  47757. ActionManager.Triggers[action.trigger] = 1;
  47758. }
  47759. action._actionManager = this;
  47760. action._prepare();
  47761. return action;
  47762. };
  47763. /**
  47764. * Unregisters an action to this action manager
  47765. * @param action The action to be unregistered
  47766. * @return whether the action has been unregistered
  47767. */
  47768. ActionManager.prototype.unregisterAction = function (action) {
  47769. var index = this.actions.indexOf(action);
  47770. if (index !== -1) {
  47771. this.actions.splice(index, 1);
  47772. ActionManager.Triggers[action.trigger] -= 1;
  47773. if (ActionManager.Triggers[action.trigger] === 0) {
  47774. delete ActionManager.Triggers[action.trigger];
  47775. }
  47776. delete action._actionManager;
  47777. return true;
  47778. }
  47779. return false;
  47780. };
  47781. /**
  47782. * Process a specific trigger
  47783. * @param {number} trigger - the trigger to process
  47784. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47785. */
  47786. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47787. for (var index = 0; index < this.actions.length; index++) {
  47788. var action = this.actions[index];
  47789. if (action.trigger === trigger) {
  47790. if (evt) {
  47791. if (trigger === ActionManager.OnKeyUpTrigger
  47792. || trigger === ActionManager.OnKeyDownTrigger) {
  47793. var parameter = action.getTriggerParameter();
  47794. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47795. if (!parameter.toLowerCase) {
  47796. continue;
  47797. }
  47798. var lowerCase = parameter.toLowerCase();
  47799. if (lowerCase !== evt.sourceEvent.key) {
  47800. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47801. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47802. if (actualkey !== lowerCase) {
  47803. continue;
  47804. }
  47805. }
  47806. }
  47807. }
  47808. }
  47809. action._executeCurrent(evt);
  47810. }
  47811. }
  47812. };
  47813. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47814. var properties = propertyPath.split(".");
  47815. for (var index = 0; index < properties.length - 1; index++) {
  47816. target = target[properties[index]];
  47817. }
  47818. return target;
  47819. };
  47820. ActionManager.prototype._getProperty = function (propertyPath) {
  47821. var properties = propertyPath.split(".");
  47822. return properties[properties.length - 1];
  47823. };
  47824. ActionManager.prototype.serialize = function (name) {
  47825. var root = {
  47826. children: new Array(),
  47827. name: name,
  47828. type: 3,
  47829. properties: new Array() // Empty for root but required
  47830. };
  47831. for (var i = 0; i < this.actions.length; i++) {
  47832. var triggerObject = {
  47833. type: 0,
  47834. children: new Array(),
  47835. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47836. properties: new Array()
  47837. };
  47838. var triggerOptions = this.actions[i].triggerOptions;
  47839. if (triggerOptions && typeof triggerOptions !== "number") {
  47840. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47841. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47842. }
  47843. else {
  47844. var parameter = {};
  47845. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47846. if (triggerOptions.parameter.mesh) {
  47847. parameter._meshId = triggerOptions.parameter.mesh.id;
  47848. }
  47849. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47850. }
  47851. }
  47852. // Serialize child action, recursively
  47853. this.actions[i].serialize(triggerObject);
  47854. // Add serialized trigger
  47855. root.children.push(triggerObject);
  47856. }
  47857. return root;
  47858. };
  47859. ActionManager.Parse = function (parsedActions, object, scene) {
  47860. var actionManager = new ActionManager(scene);
  47861. if (object === null)
  47862. scene.actionManager = actionManager;
  47863. else
  47864. object.actionManager = actionManager;
  47865. // instanciate a new object
  47866. var instanciate = function (name, params) {
  47867. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47868. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47869. newInstance.constructor.apply(newInstance, params);
  47870. return newInstance;
  47871. };
  47872. var parseParameter = function (name, value, target, propertyPath) {
  47873. if (propertyPath === null) {
  47874. // String, boolean or float
  47875. var floatValue = parseFloat(value);
  47876. if (value === "true" || value === "false")
  47877. return value === "true";
  47878. else
  47879. return isNaN(floatValue) ? value : floatValue;
  47880. }
  47881. var effectiveTarget = propertyPath.split(".");
  47882. var values = value.split(",");
  47883. // Get effective Target
  47884. for (var i = 0; i < effectiveTarget.length; i++) {
  47885. target = target[effectiveTarget[i]];
  47886. }
  47887. // Return appropriate value with its type
  47888. if (typeof (target) === "boolean")
  47889. return values[0] === "true";
  47890. if (typeof (target) === "string")
  47891. return values[0];
  47892. // Parameters with multiple values such as Vector3 etc.
  47893. var split = new Array();
  47894. for (var i = 0; i < values.length; i++)
  47895. split.push(parseFloat(values[i]));
  47896. if (target instanceof BABYLON.Vector3)
  47897. return BABYLON.Vector3.FromArray(split);
  47898. if (target instanceof BABYLON.Vector4)
  47899. return BABYLON.Vector4.FromArray(split);
  47900. if (target instanceof BABYLON.Color3)
  47901. return BABYLON.Color3.FromArray(split);
  47902. if (target instanceof BABYLON.Color4)
  47903. return BABYLON.Color4.FromArray(split);
  47904. return parseFloat(values[0]);
  47905. };
  47906. // traverse graph per trigger
  47907. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47908. if (combineArray === void 0) { combineArray = null; }
  47909. if (parsedAction.detached)
  47910. return;
  47911. var parameters = new Array();
  47912. var target = null;
  47913. var propertyPath = null;
  47914. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47915. // Parameters
  47916. if (parsedAction.type === 2)
  47917. parameters.push(actionManager);
  47918. else
  47919. parameters.push(trigger);
  47920. if (combine) {
  47921. var actions = new Array();
  47922. for (var j = 0; j < parsedAction.combine.length; j++) {
  47923. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47924. }
  47925. parameters.push(actions);
  47926. }
  47927. else {
  47928. for (var i = 0; i < parsedAction.properties.length; i++) {
  47929. var value = parsedAction.properties[i].value;
  47930. var name = parsedAction.properties[i].name;
  47931. var targetType = parsedAction.properties[i].targetType;
  47932. if (name === "target")
  47933. if (targetType !== null && targetType === "SceneProperties")
  47934. value = target = scene;
  47935. else
  47936. value = target = scene.getNodeByName(value);
  47937. else if (name === "parent")
  47938. value = scene.getNodeByName(value);
  47939. else if (name === "sound")
  47940. value = scene.getSoundByName(value);
  47941. else if (name !== "propertyPath") {
  47942. if (parsedAction.type === 2 && name === "operator")
  47943. value = BABYLON.ValueCondition[value];
  47944. else
  47945. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47946. }
  47947. else {
  47948. propertyPath = value;
  47949. }
  47950. parameters.push(value);
  47951. }
  47952. }
  47953. if (combineArray === null) {
  47954. parameters.push(condition);
  47955. }
  47956. else {
  47957. parameters.push(null);
  47958. }
  47959. // If interpolate value action
  47960. if (parsedAction.name === "InterpolateValueAction") {
  47961. var param = parameters[parameters.length - 2];
  47962. parameters[parameters.length - 1] = param;
  47963. parameters[parameters.length - 2] = condition;
  47964. }
  47965. // Action or condition(s) and not CombineAction
  47966. var newAction = instanciate(parsedAction.name, parameters);
  47967. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47968. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47969. if (action)
  47970. action.then(nothing);
  47971. else
  47972. actionManager.registerAction(nothing);
  47973. action = nothing;
  47974. }
  47975. if (combineArray === null) {
  47976. if (newAction instanceof BABYLON.Condition) {
  47977. condition = newAction;
  47978. newAction = action;
  47979. }
  47980. else {
  47981. condition = null;
  47982. if (action)
  47983. action.then(newAction);
  47984. else
  47985. actionManager.registerAction(newAction);
  47986. }
  47987. }
  47988. else {
  47989. combineArray.push(newAction);
  47990. }
  47991. for (var i = 0; i < parsedAction.children.length; i++)
  47992. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47993. };
  47994. // triggers
  47995. for (var i = 0; i < parsedActions.children.length; i++) {
  47996. var triggerParams;
  47997. var trigger = parsedActions.children[i];
  47998. if (trigger.properties.length > 0) {
  47999. var param = trigger.properties[0].value;
  48000. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48001. if (value._meshId) {
  48002. value.mesh = scene.getMeshByID(value._meshId);
  48003. }
  48004. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48005. }
  48006. else
  48007. triggerParams = ActionManager[trigger.name];
  48008. for (var j = 0; j < trigger.children.length; j++) {
  48009. if (!trigger.detached)
  48010. traverse(trigger.children[j], triggerParams, null, null);
  48011. }
  48012. }
  48013. };
  48014. ActionManager.GetTriggerName = function (trigger) {
  48015. switch (trigger) {
  48016. case 0: return "NothingTrigger";
  48017. case 1: return "OnPickTrigger";
  48018. case 2: return "OnLeftPickTrigger";
  48019. case 3: return "OnRightPickTrigger";
  48020. case 4: return "OnCenterPickTrigger";
  48021. case 5: return "OnPickDownTrigger";
  48022. case 6: return "OnPickUpTrigger";
  48023. case 7: return "OnLongPressTrigger";
  48024. case 8: return "OnPointerOverTrigger";
  48025. case 9: return "OnPointerOutTrigger";
  48026. case 10: return "OnEveryFrameTrigger";
  48027. case 11: return "OnIntersectionEnterTrigger";
  48028. case 12: return "OnIntersectionExitTrigger";
  48029. case 13: return "OnKeyDownTrigger";
  48030. case 14: return "OnKeyUpTrigger";
  48031. case 15: return "OnPickOutTrigger";
  48032. default: return "";
  48033. }
  48034. };
  48035. // Statics
  48036. ActionManager._NothingTrigger = 0;
  48037. ActionManager._OnPickTrigger = 1;
  48038. ActionManager._OnLeftPickTrigger = 2;
  48039. ActionManager._OnRightPickTrigger = 3;
  48040. ActionManager._OnCenterPickTrigger = 4;
  48041. ActionManager._OnPickDownTrigger = 5;
  48042. ActionManager._OnDoublePickTrigger = 6;
  48043. ActionManager._OnPickUpTrigger = 7;
  48044. ActionManager._OnLongPressTrigger = 8;
  48045. ActionManager._OnPointerOverTrigger = 9;
  48046. ActionManager._OnPointerOutTrigger = 10;
  48047. ActionManager._OnEveryFrameTrigger = 11;
  48048. ActionManager._OnIntersectionEnterTrigger = 12;
  48049. ActionManager._OnIntersectionExitTrigger = 13;
  48050. ActionManager._OnKeyDownTrigger = 14;
  48051. ActionManager._OnKeyUpTrigger = 15;
  48052. ActionManager._OnPickOutTrigger = 16;
  48053. ActionManager.Triggers = {};
  48054. return ActionManager;
  48055. }());
  48056. BABYLON.ActionManager = ActionManager;
  48057. })(BABYLON || (BABYLON = {}));
  48058. //# sourceMappingURL=babylon.actionManager.js.map
  48059. var BABYLON;
  48060. (function (BABYLON) {
  48061. var InterpolateValueAction = /** @class */ (function (_super) {
  48062. __extends(InterpolateValueAction, _super);
  48063. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48064. if (duration === void 0) { duration = 1000; }
  48065. var _this = _super.call(this, triggerOptions, condition) || this;
  48066. _this.propertyPath = propertyPath;
  48067. _this.value = value;
  48068. _this.duration = duration;
  48069. _this.stopOtherAnimations = stopOtherAnimations;
  48070. _this.onInterpolationDone = onInterpolationDone;
  48071. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48072. _this._target = _this._effectiveTarget = target;
  48073. return _this;
  48074. }
  48075. InterpolateValueAction.prototype._prepare = function () {
  48076. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48077. this._property = this._getProperty(this.propertyPath);
  48078. };
  48079. InterpolateValueAction.prototype.execute = function () {
  48080. var _this = this;
  48081. var scene = this._actionManager.getScene();
  48082. var keys = [
  48083. {
  48084. frame: 0,
  48085. value: this._effectiveTarget[this._property]
  48086. }, {
  48087. frame: 100,
  48088. value: this.value
  48089. }
  48090. ];
  48091. var dataType;
  48092. if (typeof this.value === "number") {
  48093. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48094. }
  48095. else if (this.value instanceof BABYLON.Color3) {
  48096. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48097. }
  48098. else if (this.value instanceof BABYLON.Vector3) {
  48099. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48100. }
  48101. else if (this.value instanceof BABYLON.Matrix) {
  48102. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48103. }
  48104. else if (this.value instanceof BABYLON.Quaternion) {
  48105. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48106. }
  48107. else {
  48108. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48109. return;
  48110. }
  48111. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48112. animation.setKeys(keys);
  48113. if (this.stopOtherAnimations) {
  48114. scene.stopAnimation(this._effectiveTarget);
  48115. }
  48116. var wrapper = function () {
  48117. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48118. if (_this.onInterpolationDone) {
  48119. _this.onInterpolationDone();
  48120. }
  48121. };
  48122. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48123. };
  48124. InterpolateValueAction.prototype.serialize = function (parent) {
  48125. return _super.prototype._serialize.call(this, {
  48126. name: "InterpolateValueAction",
  48127. properties: [
  48128. BABYLON.Action._GetTargetProperty(this._target),
  48129. { name: "propertyPath", value: this.propertyPath },
  48130. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48131. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48132. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48133. ]
  48134. }, parent);
  48135. };
  48136. return InterpolateValueAction;
  48137. }(BABYLON.Action));
  48138. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48139. })(BABYLON || (BABYLON = {}));
  48140. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48141. var BABYLON;
  48142. (function (BABYLON) {
  48143. var SwitchBooleanAction = /** @class */ (function (_super) {
  48144. __extends(SwitchBooleanAction, _super);
  48145. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48146. var _this = _super.call(this, triggerOptions, condition) || this;
  48147. _this.propertyPath = propertyPath;
  48148. _this._target = _this._effectiveTarget = target;
  48149. return _this;
  48150. }
  48151. SwitchBooleanAction.prototype._prepare = function () {
  48152. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48153. this._property = this._getProperty(this.propertyPath);
  48154. };
  48155. SwitchBooleanAction.prototype.execute = function () {
  48156. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48157. };
  48158. SwitchBooleanAction.prototype.serialize = function (parent) {
  48159. return _super.prototype._serialize.call(this, {
  48160. name: "SwitchBooleanAction",
  48161. properties: [
  48162. BABYLON.Action._GetTargetProperty(this._target),
  48163. { name: "propertyPath", value: this.propertyPath }
  48164. ]
  48165. }, parent);
  48166. };
  48167. return SwitchBooleanAction;
  48168. }(BABYLON.Action));
  48169. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48170. var SetStateAction = /** @class */ (function (_super) {
  48171. __extends(SetStateAction, _super);
  48172. function SetStateAction(triggerOptions, target, value, condition) {
  48173. var _this = _super.call(this, triggerOptions, condition) || this;
  48174. _this.value = value;
  48175. _this._target = target;
  48176. return _this;
  48177. }
  48178. SetStateAction.prototype.execute = function () {
  48179. this._target.state = this.value;
  48180. };
  48181. SetStateAction.prototype.serialize = function (parent) {
  48182. return _super.prototype._serialize.call(this, {
  48183. name: "SetStateAction",
  48184. properties: [
  48185. BABYLON.Action._GetTargetProperty(this._target),
  48186. { name: "value", value: this.value }
  48187. ]
  48188. }, parent);
  48189. };
  48190. return SetStateAction;
  48191. }(BABYLON.Action));
  48192. BABYLON.SetStateAction = SetStateAction;
  48193. var SetValueAction = /** @class */ (function (_super) {
  48194. __extends(SetValueAction, _super);
  48195. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48196. var _this = _super.call(this, triggerOptions, condition) || this;
  48197. _this.propertyPath = propertyPath;
  48198. _this.value = value;
  48199. _this._target = _this._effectiveTarget = target;
  48200. return _this;
  48201. }
  48202. SetValueAction.prototype._prepare = function () {
  48203. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48204. this._property = this._getProperty(this.propertyPath);
  48205. };
  48206. SetValueAction.prototype.execute = function () {
  48207. this._effectiveTarget[this._property] = this.value;
  48208. if (this._target.markAsDirty) {
  48209. this._target.markAsDirty(this._property);
  48210. }
  48211. };
  48212. SetValueAction.prototype.serialize = function (parent) {
  48213. return _super.prototype._serialize.call(this, {
  48214. name: "SetValueAction",
  48215. properties: [
  48216. BABYLON.Action._GetTargetProperty(this._target),
  48217. { name: "propertyPath", value: this.propertyPath },
  48218. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48219. ]
  48220. }, parent);
  48221. };
  48222. return SetValueAction;
  48223. }(BABYLON.Action));
  48224. BABYLON.SetValueAction = SetValueAction;
  48225. var IncrementValueAction = /** @class */ (function (_super) {
  48226. __extends(IncrementValueAction, _super);
  48227. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48228. var _this = _super.call(this, triggerOptions, condition) || this;
  48229. _this.propertyPath = propertyPath;
  48230. _this.value = value;
  48231. _this._target = _this._effectiveTarget = target;
  48232. return _this;
  48233. }
  48234. IncrementValueAction.prototype._prepare = function () {
  48235. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48236. this._property = this._getProperty(this.propertyPath);
  48237. if (typeof this._effectiveTarget[this._property] !== "number") {
  48238. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48239. }
  48240. };
  48241. IncrementValueAction.prototype.execute = function () {
  48242. this._effectiveTarget[this._property] += this.value;
  48243. if (this._target.markAsDirty) {
  48244. this._target.markAsDirty(this._property);
  48245. }
  48246. };
  48247. IncrementValueAction.prototype.serialize = function (parent) {
  48248. return _super.prototype._serialize.call(this, {
  48249. name: "IncrementValueAction",
  48250. properties: [
  48251. BABYLON.Action._GetTargetProperty(this._target),
  48252. { name: "propertyPath", value: this.propertyPath },
  48253. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48254. ]
  48255. }, parent);
  48256. };
  48257. return IncrementValueAction;
  48258. }(BABYLON.Action));
  48259. BABYLON.IncrementValueAction = IncrementValueAction;
  48260. var PlayAnimationAction = /** @class */ (function (_super) {
  48261. __extends(PlayAnimationAction, _super);
  48262. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48263. var _this = _super.call(this, triggerOptions, condition) || this;
  48264. _this.from = from;
  48265. _this.to = to;
  48266. _this.loop = loop;
  48267. _this._target = target;
  48268. return _this;
  48269. }
  48270. PlayAnimationAction.prototype._prepare = function () {
  48271. };
  48272. PlayAnimationAction.prototype.execute = function () {
  48273. var scene = this._actionManager.getScene();
  48274. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48275. };
  48276. PlayAnimationAction.prototype.serialize = function (parent) {
  48277. return _super.prototype._serialize.call(this, {
  48278. name: "PlayAnimationAction",
  48279. properties: [
  48280. BABYLON.Action._GetTargetProperty(this._target),
  48281. { name: "from", value: String(this.from) },
  48282. { name: "to", value: String(this.to) },
  48283. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48284. ]
  48285. }, parent);
  48286. };
  48287. return PlayAnimationAction;
  48288. }(BABYLON.Action));
  48289. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48290. var StopAnimationAction = /** @class */ (function (_super) {
  48291. __extends(StopAnimationAction, _super);
  48292. function StopAnimationAction(triggerOptions, target, condition) {
  48293. var _this = _super.call(this, triggerOptions, condition) || this;
  48294. _this._target = target;
  48295. return _this;
  48296. }
  48297. StopAnimationAction.prototype._prepare = function () {
  48298. };
  48299. StopAnimationAction.prototype.execute = function () {
  48300. var scene = this._actionManager.getScene();
  48301. scene.stopAnimation(this._target);
  48302. };
  48303. StopAnimationAction.prototype.serialize = function (parent) {
  48304. return _super.prototype._serialize.call(this, {
  48305. name: "StopAnimationAction",
  48306. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48307. }, parent);
  48308. };
  48309. return StopAnimationAction;
  48310. }(BABYLON.Action));
  48311. BABYLON.StopAnimationAction = StopAnimationAction;
  48312. var DoNothingAction = /** @class */ (function (_super) {
  48313. __extends(DoNothingAction, _super);
  48314. function DoNothingAction(triggerOptions, condition) {
  48315. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48316. return _super.call(this, triggerOptions, condition) || this;
  48317. }
  48318. DoNothingAction.prototype.execute = function () {
  48319. };
  48320. DoNothingAction.prototype.serialize = function (parent) {
  48321. return _super.prototype._serialize.call(this, {
  48322. name: "DoNothingAction",
  48323. properties: []
  48324. }, parent);
  48325. };
  48326. return DoNothingAction;
  48327. }(BABYLON.Action));
  48328. BABYLON.DoNothingAction = DoNothingAction;
  48329. var CombineAction = /** @class */ (function (_super) {
  48330. __extends(CombineAction, _super);
  48331. function CombineAction(triggerOptions, children, condition) {
  48332. var _this = _super.call(this, triggerOptions, condition) || this;
  48333. _this.children = children;
  48334. return _this;
  48335. }
  48336. CombineAction.prototype._prepare = function () {
  48337. for (var index = 0; index < this.children.length; index++) {
  48338. this.children[index]._actionManager = this._actionManager;
  48339. this.children[index]._prepare();
  48340. }
  48341. };
  48342. CombineAction.prototype.execute = function (evt) {
  48343. for (var index = 0; index < this.children.length; index++) {
  48344. this.children[index].execute(evt);
  48345. }
  48346. };
  48347. CombineAction.prototype.serialize = function (parent) {
  48348. var serializationObject = _super.prototype._serialize.call(this, {
  48349. name: "CombineAction",
  48350. properties: [],
  48351. combine: []
  48352. }, parent);
  48353. for (var i = 0; i < this.children.length; i++) {
  48354. serializationObject.combine.push(this.children[i].serialize(null));
  48355. }
  48356. return serializationObject;
  48357. };
  48358. return CombineAction;
  48359. }(BABYLON.Action));
  48360. BABYLON.CombineAction = CombineAction;
  48361. var ExecuteCodeAction = /** @class */ (function (_super) {
  48362. __extends(ExecuteCodeAction, _super);
  48363. function ExecuteCodeAction(triggerOptions, func, condition) {
  48364. var _this = _super.call(this, triggerOptions, condition) || this;
  48365. _this.func = func;
  48366. return _this;
  48367. }
  48368. ExecuteCodeAction.prototype.execute = function (evt) {
  48369. this.func(evt);
  48370. };
  48371. return ExecuteCodeAction;
  48372. }(BABYLON.Action));
  48373. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48374. var SetParentAction = /** @class */ (function (_super) {
  48375. __extends(SetParentAction, _super);
  48376. function SetParentAction(triggerOptions, target, parent, condition) {
  48377. var _this = _super.call(this, triggerOptions, condition) || this;
  48378. _this._target = target;
  48379. _this._parent = parent;
  48380. return _this;
  48381. }
  48382. SetParentAction.prototype._prepare = function () {
  48383. };
  48384. SetParentAction.prototype.execute = function () {
  48385. if (this._target.parent === this._parent) {
  48386. return;
  48387. }
  48388. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48389. invertParentWorldMatrix.invert();
  48390. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48391. this._target.parent = this._parent;
  48392. };
  48393. SetParentAction.prototype.serialize = function (parent) {
  48394. return _super.prototype._serialize.call(this, {
  48395. name: "SetParentAction",
  48396. properties: [
  48397. BABYLON.Action._GetTargetProperty(this._target),
  48398. BABYLON.Action._GetTargetProperty(this._parent),
  48399. ]
  48400. }, parent);
  48401. };
  48402. return SetParentAction;
  48403. }(BABYLON.Action));
  48404. BABYLON.SetParentAction = SetParentAction;
  48405. var PlaySoundAction = /** @class */ (function (_super) {
  48406. __extends(PlaySoundAction, _super);
  48407. function PlaySoundAction(triggerOptions, sound, condition) {
  48408. var _this = _super.call(this, triggerOptions, condition) || this;
  48409. _this._sound = sound;
  48410. return _this;
  48411. }
  48412. PlaySoundAction.prototype._prepare = function () {
  48413. };
  48414. PlaySoundAction.prototype.execute = function () {
  48415. if (this._sound !== undefined)
  48416. this._sound.play();
  48417. };
  48418. PlaySoundAction.prototype.serialize = function (parent) {
  48419. return _super.prototype._serialize.call(this, {
  48420. name: "PlaySoundAction",
  48421. properties: [{ name: "sound", value: this._sound.name }]
  48422. }, parent);
  48423. };
  48424. return PlaySoundAction;
  48425. }(BABYLON.Action));
  48426. BABYLON.PlaySoundAction = PlaySoundAction;
  48427. var StopSoundAction = /** @class */ (function (_super) {
  48428. __extends(StopSoundAction, _super);
  48429. function StopSoundAction(triggerOptions, sound, condition) {
  48430. var _this = _super.call(this, triggerOptions, condition) || this;
  48431. _this._sound = sound;
  48432. return _this;
  48433. }
  48434. StopSoundAction.prototype._prepare = function () {
  48435. };
  48436. StopSoundAction.prototype.execute = function () {
  48437. if (this._sound !== undefined)
  48438. this._sound.stop();
  48439. };
  48440. StopSoundAction.prototype.serialize = function (parent) {
  48441. return _super.prototype._serialize.call(this, {
  48442. name: "StopSoundAction",
  48443. properties: [{ name: "sound", value: this._sound.name }]
  48444. }, parent);
  48445. };
  48446. return StopSoundAction;
  48447. }(BABYLON.Action));
  48448. BABYLON.StopSoundAction = StopSoundAction;
  48449. })(BABYLON || (BABYLON = {}));
  48450. //# sourceMappingURL=babylon.directActions.js.map
  48451. var BABYLON;
  48452. (function (BABYLON) {
  48453. var SpriteManager = /** @class */ (function () {
  48454. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48455. if (epsilon === void 0) { epsilon = 0.01; }
  48456. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48457. this.name = name;
  48458. this.sprites = new Array();
  48459. this.renderingGroupId = 0;
  48460. this.layerMask = 0x0FFFFFFF;
  48461. this.fogEnabled = true;
  48462. this.isPickable = false;
  48463. /**
  48464. * An event triggered when the manager is disposed.
  48465. * @type {BABYLON.Observable}
  48466. */
  48467. this.onDisposeObservable = new BABYLON.Observable();
  48468. this._vertexBuffers = {};
  48469. this._capacity = capacity;
  48470. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48471. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48472. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48473. if (cellSize.width && cellSize.height) {
  48474. this.cellWidth = cellSize.width;
  48475. this.cellHeight = cellSize.height;
  48476. }
  48477. else if (cellSize !== undefined) {
  48478. this.cellWidth = cellSize;
  48479. this.cellHeight = cellSize;
  48480. }
  48481. else {
  48482. return;
  48483. }
  48484. this._epsilon = epsilon;
  48485. this._scene = scene;
  48486. this._scene.spriteManagers.push(this);
  48487. var indices = [];
  48488. var index = 0;
  48489. for (var count = 0; count < capacity; count++) {
  48490. indices.push(index);
  48491. indices.push(index + 1);
  48492. indices.push(index + 2);
  48493. indices.push(index);
  48494. indices.push(index + 2);
  48495. indices.push(index + 3);
  48496. index += 4;
  48497. }
  48498. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48499. // VBO
  48500. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48501. this._vertexData = new Float32Array(capacity * 16 * 4);
  48502. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48503. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48504. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48505. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48506. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48507. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48508. this._vertexBuffers["options"] = options;
  48509. this._vertexBuffers["cellInfo"] = cellInfo;
  48510. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48511. // Effects
  48512. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48513. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48514. }
  48515. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48516. set: function (callback) {
  48517. if (this._onDisposeObserver) {
  48518. this.onDisposeObservable.remove(this._onDisposeObserver);
  48519. }
  48520. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48521. },
  48522. enumerable: true,
  48523. configurable: true
  48524. });
  48525. Object.defineProperty(SpriteManager.prototype, "texture", {
  48526. get: function () {
  48527. return this._spriteTexture;
  48528. },
  48529. set: function (value) {
  48530. this._spriteTexture = value;
  48531. },
  48532. enumerable: true,
  48533. configurable: true
  48534. });
  48535. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48536. var arrayOffset = index * 16;
  48537. if (offsetX === 0)
  48538. offsetX = this._epsilon;
  48539. else if (offsetX === 1)
  48540. offsetX = 1 - this._epsilon;
  48541. if (offsetY === 0)
  48542. offsetY = this._epsilon;
  48543. else if (offsetY === 1)
  48544. offsetY = 1 - this._epsilon;
  48545. this._vertexData[arrayOffset] = sprite.position.x;
  48546. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48547. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48548. this._vertexData[arrayOffset + 3] = sprite.angle;
  48549. this._vertexData[arrayOffset + 4] = sprite.width;
  48550. this._vertexData[arrayOffset + 5] = sprite.height;
  48551. this._vertexData[arrayOffset + 6] = offsetX;
  48552. this._vertexData[arrayOffset + 7] = offsetY;
  48553. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48554. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48555. var offset = (sprite.cellIndex / rowSize) >> 0;
  48556. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48557. this._vertexData[arrayOffset + 11] = offset;
  48558. // Color
  48559. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48560. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48561. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48562. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48563. };
  48564. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48565. var count = Math.min(this._capacity, this.sprites.length);
  48566. var min = BABYLON.Vector3.Zero();
  48567. var max = BABYLON.Vector3.Zero();
  48568. var distance = Number.MAX_VALUE;
  48569. var currentSprite = null;
  48570. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48571. var cameraView = camera.getViewMatrix();
  48572. for (var index = 0; index < count; index++) {
  48573. var sprite = this.sprites[index];
  48574. if (!sprite) {
  48575. continue;
  48576. }
  48577. if (predicate) {
  48578. if (!predicate(sprite)) {
  48579. continue;
  48580. }
  48581. }
  48582. else if (!sprite.isPickable) {
  48583. continue;
  48584. }
  48585. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48586. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48587. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48588. if (ray.intersectsBoxMinMax(min, max)) {
  48589. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48590. if (distance > currentDistance) {
  48591. distance = currentDistance;
  48592. currentSprite = sprite;
  48593. if (fastCheck) {
  48594. break;
  48595. }
  48596. }
  48597. }
  48598. }
  48599. if (currentSprite) {
  48600. var result = new BABYLON.PickingInfo();
  48601. result.hit = true;
  48602. result.pickedSprite = currentSprite;
  48603. result.distance = distance;
  48604. return result;
  48605. }
  48606. return null;
  48607. };
  48608. SpriteManager.prototype.render = function () {
  48609. // Check
  48610. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48611. return;
  48612. var engine = this._scene.getEngine();
  48613. var baseSize = this._spriteTexture.getBaseSize();
  48614. // Sprites
  48615. var deltaTime = engine.getDeltaTime();
  48616. var max = Math.min(this._capacity, this.sprites.length);
  48617. var rowSize = baseSize.width / this.cellWidth;
  48618. var offset = 0;
  48619. for (var index = 0; index < max; index++) {
  48620. var sprite = this.sprites[index];
  48621. if (!sprite) {
  48622. continue;
  48623. }
  48624. sprite._animate(deltaTime);
  48625. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48626. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48627. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48628. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48629. }
  48630. this._buffer.update(this._vertexData);
  48631. // Render
  48632. var effect = this._effectBase;
  48633. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48634. effect = this._effectFog;
  48635. }
  48636. engine.enableEffect(effect);
  48637. var viewMatrix = this._scene.getViewMatrix();
  48638. effect.setTexture("diffuseSampler", this._spriteTexture);
  48639. effect.setMatrix("view", viewMatrix);
  48640. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48641. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48642. // Fog
  48643. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48644. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48645. effect.setColor3("vFogColor", this._scene.fogColor);
  48646. }
  48647. // VBOs
  48648. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48649. // Draw order
  48650. engine.setDepthFunctionToLessOrEqual();
  48651. effect.setBool("alphaTest", true);
  48652. engine.setColorWrite(false);
  48653. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48654. engine.setColorWrite(true);
  48655. effect.setBool("alphaTest", false);
  48656. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48657. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48658. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48659. };
  48660. SpriteManager.prototype.dispose = function () {
  48661. if (this._buffer) {
  48662. this._buffer.dispose();
  48663. this._buffer = null;
  48664. }
  48665. if (this._indexBuffer) {
  48666. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48667. this._indexBuffer = null;
  48668. }
  48669. if (this._spriteTexture) {
  48670. this._spriteTexture.dispose();
  48671. this._spriteTexture = null;
  48672. }
  48673. // Remove from scene
  48674. var index = this._scene.spriteManagers.indexOf(this);
  48675. this._scene.spriteManagers.splice(index, 1);
  48676. // Callback
  48677. this.onDisposeObservable.notifyObservers(this);
  48678. this.onDisposeObservable.clear();
  48679. };
  48680. return SpriteManager;
  48681. }());
  48682. BABYLON.SpriteManager = SpriteManager;
  48683. })(BABYLON || (BABYLON = {}));
  48684. //# sourceMappingURL=babylon.spriteManager.js.map
  48685. var BABYLON;
  48686. (function (BABYLON) {
  48687. var Sprite = /** @class */ (function () {
  48688. function Sprite(name, manager) {
  48689. this.name = name;
  48690. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48691. this.width = 1.0;
  48692. this.height = 1.0;
  48693. this.angle = 0;
  48694. this.cellIndex = 0;
  48695. this.invertU = 0;
  48696. this.invertV = 0;
  48697. this.animations = new Array();
  48698. this.isPickable = false;
  48699. this._animationStarted = false;
  48700. this._loopAnimation = false;
  48701. this._fromIndex = 0;
  48702. this._toIndex = 0;
  48703. this._delay = 0;
  48704. this._direction = 1;
  48705. this._time = 0;
  48706. this._manager = manager;
  48707. this._manager.sprites.push(this);
  48708. this.position = BABYLON.Vector3.Zero();
  48709. }
  48710. Object.defineProperty(Sprite.prototype, "size", {
  48711. get: function () {
  48712. return this.width;
  48713. },
  48714. set: function (value) {
  48715. this.width = value;
  48716. this.height = value;
  48717. },
  48718. enumerable: true,
  48719. configurable: true
  48720. });
  48721. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48722. this._fromIndex = from;
  48723. this._toIndex = to;
  48724. this._loopAnimation = loop;
  48725. this._delay = delay;
  48726. this._animationStarted = true;
  48727. this._direction = from < to ? 1 : -1;
  48728. this.cellIndex = from;
  48729. this._time = 0;
  48730. this._onAnimationEnd = onAnimationEnd;
  48731. };
  48732. Sprite.prototype.stopAnimation = function () {
  48733. this._animationStarted = false;
  48734. };
  48735. Sprite.prototype._animate = function (deltaTime) {
  48736. if (!this._animationStarted)
  48737. return;
  48738. this._time += deltaTime;
  48739. if (this._time > this._delay) {
  48740. this._time = this._time % this._delay;
  48741. this.cellIndex += this._direction;
  48742. if (this.cellIndex > this._toIndex) {
  48743. if (this._loopAnimation) {
  48744. this.cellIndex = this._fromIndex;
  48745. }
  48746. else {
  48747. this.cellIndex = this._toIndex;
  48748. this._animationStarted = false;
  48749. if (this._onAnimationEnd) {
  48750. this._onAnimationEnd();
  48751. }
  48752. if (this.disposeWhenFinishedAnimating) {
  48753. this.dispose();
  48754. }
  48755. }
  48756. }
  48757. }
  48758. };
  48759. Sprite.prototype.dispose = function () {
  48760. for (var i = 0; i < this._manager.sprites.length; i++) {
  48761. if (this._manager.sprites[i] == this) {
  48762. this._manager.sprites.splice(i, 1);
  48763. }
  48764. }
  48765. };
  48766. return Sprite;
  48767. }());
  48768. BABYLON.Sprite = Sprite;
  48769. })(BABYLON || (BABYLON = {}));
  48770. //# sourceMappingURL=babylon.sprite.js.map
  48771. var BABYLON;
  48772. (function (BABYLON) {
  48773. var IntersectionInfo = /** @class */ (function () {
  48774. function IntersectionInfo(bu, bv, distance) {
  48775. this.bu = bu;
  48776. this.bv = bv;
  48777. this.distance = distance;
  48778. this.faceId = 0;
  48779. this.subMeshId = 0;
  48780. }
  48781. return IntersectionInfo;
  48782. }());
  48783. BABYLON.IntersectionInfo = IntersectionInfo;
  48784. var PickingInfo = /** @class */ (function () {
  48785. function PickingInfo() {
  48786. this.hit = false;
  48787. this.distance = 0;
  48788. this.pickedPoint = null;
  48789. this.pickedMesh = null;
  48790. this.bu = 0;
  48791. this.bv = 0;
  48792. this.faceId = -1;
  48793. this.subMeshId = 0;
  48794. this.pickedSprite = null;
  48795. }
  48796. // Methods
  48797. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48798. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48799. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48800. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48801. return null;
  48802. }
  48803. var indices = this.pickedMesh.getIndices();
  48804. if (!indices) {
  48805. return null;
  48806. }
  48807. var result;
  48808. if (useVerticesNormals) {
  48809. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48810. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48811. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48812. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48813. normal0 = normal0.scale(this.bu);
  48814. normal1 = normal1.scale(this.bv);
  48815. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48816. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48817. }
  48818. else {
  48819. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48820. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48821. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48822. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48823. var p1p2 = vertex1.subtract(vertex2);
  48824. var p3p2 = vertex3.subtract(vertex2);
  48825. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48826. }
  48827. if (useWorldCoordinates) {
  48828. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48829. }
  48830. return BABYLON.Vector3.Normalize(result);
  48831. };
  48832. PickingInfo.prototype.getTextureCoordinates = function () {
  48833. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48834. return null;
  48835. }
  48836. var indices = this.pickedMesh.getIndices();
  48837. if (!indices) {
  48838. return null;
  48839. }
  48840. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48841. if (!uvs) {
  48842. return null;
  48843. }
  48844. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48845. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48846. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48847. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48848. uv1 = uv1.scale(this.bu);
  48849. uv2 = uv2.scale(this.bv);
  48850. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48851. };
  48852. return PickingInfo;
  48853. }());
  48854. BABYLON.PickingInfo = PickingInfo;
  48855. })(BABYLON || (BABYLON = {}));
  48856. //# sourceMappingURL=babylon.pickingInfo.js.map
  48857. var BABYLON;
  48858. (function (BABYLON) {
  48859. var Ray = /** @class */ (function () {
  48860. function Ray(origin, direction, length) {
  48861. if (length === void 0) { length = Number.MAX_VALUE; }
  48862. this.origin = origin;
  48863. this.direction = direction;
  48864. this.length = length;
  48865. }
  48866. // Methods
  48867. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48868. var d = 0.0;
  48869. var maxValue = Number.MAX_VALUE;
  48870. var inv;
  48871. var min;
  48872. var max;
  48873. var temp;
  48874. if (Math.abs(this.direction.x) < 0.0000001) {
  48875. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48876. return false;
  48877. }
  48878. }
  48879. else {
  48880. inv = 1.0 / this.direction.x;
  48881. min = (minimum.x - this.origin.x) * inv;
  48882. max = (maximum.x - this.origin.x) * inv;
  48883. if (max === -Infinity) {
  48884. max = Infinity;
  48885. }
  48886. if (min > max) {
  48887. temp = min;
  48888. min = max;
  48889. max = temp;
  48890. }
  48891. d = Math.max(min, d);
  48892. maxValue = Math.min(max, maxValue);
  48893. if (d > maxValue) {
  48894. return false;
  48895. }
  48896. }
  48897. if (Math.abs(this.direction.y) < 0.0000001) {
  48898. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48899. return false;
  48900. }
  48901. }
  48902. else {
  48903. inv = 1.0 / this.direction.y;
  48904. min = (minimum.y - this.origin.y) * inv;
  48905. max = (maximum.y - this.origin.y) * inv;
  48906. if (max === -Infinity) {
  48907. max = Infinity;
  48908. }
  48909. if (min > max) {
  48910. temp = min;
  48911. min = max;
  48912. max = temp;
  48913. }
  48914. d = Math.max(min, d);
  48915. maxValue = Math.min(max, maxValue);
  48916. if (d > maxValue) {
  48917. return false;
  48918. }
  48919. }
  48920. if (Math.abs(this.direction.z) < 0.0000001) {
  48921. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48922. return false;
  48923. }
  48924. }
  48925. else {
  48926. inv = 1.0 / this.direction.z;
  48927. min = (minimum.z - this.origin.z) * inv;
  48928. max = (maximum.z - this.origin.z) * inv;
  48929. if (max === -Infinity) {
  48930. max = Infinity;
  48931. }
  48932. if (min > max) {
  48933. temp = min;
  48934. min = max;
  48935. max = temp;
  48936. }
  48937. d = Math.max(min, d);
  48938. maxValue = Math.min(max, maxValue);
  48939. if (d > maxValue) {
  48940. return false;
  48941. }
  48942. }
  48943. return true;
  48944. };
  48945. Ray.prototype.intersectsBox = function (box) {
  48946. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48947. };
  48948. Ray.prototype.intersectsSphere = function (sphere) {
  48949. var x = sphere.center.x - this.origin.x;
  48950. var y = sphere.center.y - this.origin.y;
  48951. var z = sphere.center.z - this.origin.z;
  48952. var pyth = (x * x) + (y * y) + (z * z);
  48953. var rr = sphere.radius * sphere.radius;
  48954. if (pyth <= rr) {
  48955. return true;
  48956. }
  48957. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48958. if (dot < 0.0) {
  48959. return false;
  48960. }
  48961. var temp = pyth - (dot * dot);
  48962. return temp <= rr;
  48963. };
  48964. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48965. if (!this._edge1) {
  48966. this._edge1 = BABYLON.Vector3.Zero();
  48967. this._edge2 = BABYLON.Vector3.Zero();
  48968. this._pvec = BABYLON.Vector3.Zero();
  48969. this._tvec = BABYLON.Vector3.Zero();
  48970. this._qvec = BABYLON.Vector3.Zero();
  48971. }
  48972. vertex1.subtractToRef(vertex0, this._edge1);
  48973. vertex2.subtractToRef(vertex0, this._edge2);
  48974. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48975. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48976. if (det === 0) {
  48977. return null;
  48978. }
  48979. var invdet = 1 / det;
  48980. this.origin.subtractToRef(vertex0, this._tvec);
  48981. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48982. if (bu < 0 || bu > 1.0) {
  48983. return null;
  48984. }
  48985. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48986. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48987. if (bv < 0 || bu + bv > 1.0) {
  48988. return null;
  48989. }
  48990. //check if the distance is longer than the predefined length.
  48991. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48992. if (distance > this.length) {
  48993. return null;
  48994. }
  48995. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48996. };
  48997. Ray.prototype.intersectsPlane = function (plane) {
  48998. var distance;
  48999. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49000. if (Math.abs(result1) < 9.99999997475243E-07) {
  49001. return null;
  49002. }
  49003. else {
  49004. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49005. distance = (-plane.d - result2) / result1;
  49006. if (distance < 0.0) {
  49007. if (distance < -9.99999997475243E-07) {
  49008. return null;
  49009. }
  49010. else {
  49011. return 0;
  49012. }
  49013. }
  49014. return distance;
  49015. }
  49016. };
  49017. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49018. var tm = BABYLON.Tmp.Matrix[0];
  49019. mesh.getWorldMatrix().invertToRef(tm);
  49020. if (this._tmpRay) {
  49021. Ray.TransformToRef(this, tm, this._tmpRay);
  49022. }
  49023. else {
  49024. this._tmpRay = Ray.Transform(this, tm);
  49025. }
  49026. return mesh.intersects(this._tmpRay, fastCheck);
  49027. };
  49028. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49029. if (results) {
  49030. results.length = 0;
  49031. }
  49032. else {
  49033. results = [];
  49034. }
  49035. for (var i = 0; i < meshes.length; i++) {
  49036. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49037. if (pickInfo.hit) {
  49038. results.push(pickInfo);
  49039. }
  49040. }
  49041. results.sort(this._comparePickingInfo);
  49042. return results;
  49043. };
  49044. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49045. if (pickingInfoA.distance < pickingInfoB.distance) {
  49046. return -1;
  49047. }
  49048. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49049. return 1;
  49050. }
  49051. else {
  49052. return 0;
  49053. }
  49054. };
  49055. /**
  49056. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49057. * @param sega the first point of the segment to test the intersection against
  49058. * @param segb the second point of the segment to test the intersection against
  49059. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49060. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49061. */
  49062. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49063. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49064. var u = segb.subtract(sega);
  49065. var v = rsegb.subtract(this.origin);
  49066. var w = sega.subtract(this.origin);
  49067. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49068. var b = BABYLON.Vector3.Dot(u, v);
  49069. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49070. var d = BABYLON.Vector3.Dot(u, w);
  49071. var e = BABYLON.Vector3.Dot(v, w);
  49072. var D = a * c - b * b; // always >= 0
  49073. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49074. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49075. // compute the line parameters of the two closest points
  49076. if (D < Ray.smallnum) {
  49077. sN = 0.0; // force using point P0 on segment S1
  49078. sD = 1.0; // to prevent possible division by 0.0 later
  49079. tN = e;
  49080. tD = c;
  49081. }
  49082. else {
  49083. sN = (b * e - c * d);
  49084. tN = (a * e - b * d);
  49085. if (sN < 0.0) {
  49086. sN = 0.0;
  49087. tN = e;
  49088. tD = c;
  49089. }
  49090. else if (sN > sD) {
  49091. sN = sD;
  49092. tN = e + b;
  49093. tD = c;
  49094. }
  49095. }
  49096. if (tN < 0.0) {
  49097. tN = 0.0;
  49098. // recompute sc for this edge
  49099. if (-d < 0.0) {
  49100. sN = 0.0;
  49101. }
  49102. else if (-d > a)
  49103. sN = sD;
  49104. else {
  49105. sN = -d;
  49106. sD = a;
  49107. }
  49108. }
  49109. else if (tN > tD) {
  49110. tN = tD;
  49111. // recompute sc for this edge
  49112. if ((-d + b) < 0.0) {
  49113. sN = 0;
  49114. }
  49115. else if ((-d + b) > a) {
  49116. sN = sD;
  49117. }
  49118. else {
  49119. sN = (-d + b);
  49120. sD = a;
  49121. }
  49122. }
  49123. // finally do the division to get sc and tc
  49124. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49125. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49126. // get the difference of the two closest points
  49127. var qtc = v.multiplyByFloats(tc, tc, tc);
  49128. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49129. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49130. if (isIntersected) {
  49131. return qtc.length();
  49132. }
  49133. return -1;
  49134. };
  49135. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49136. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49137. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49138. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49139. this.direction.normalize();
  49140. return this;
  49141. };
  49142. // Statics
  49143. Ray.Zero = function () {
  49144. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49145. };
  49146. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49147. var result = Ray.Zero();
  49148. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49149. };
  49150. /**
  49151. * 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
  49152. * transformed to the given world matrix.
  49153. * @param origin The origin point
  49154. * @param end The end point
  49155. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49156. */
  49157. Ray.CreateNewFromTo = function (origin, end, world) {
  49158. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49159. var direction = end.subtract(origin);
  49160. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49161. direction.normalize();
  49162. return Ray.Transform(new Ray(origin, direction, length), world);
  49163. };
  49164. Ray.Transform = function (ray, matrix) {
  49165. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49166. Ray.TransformToRef(ray, matrix, result);
  49167. return result;
  49168. };
  49169. Ray.TransformToRef = function (ray, matrix, result) {
  49170. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49171. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49172. result.length = ray.length;
  49173. var dir = result.direction;
  49174. var len = dir.length();
  49175. if (!(len === 0 || len === 1)) {
  49176. var num = 1.0 / len;
  49177. dir.x *= num;
  49178. dir.y *= num;
  49179. dir.z *= num;
  49180. result.length *= len;
  49181. }
  49182. };
  49183. Ray.smallnum = 0.00000001;
  49184. Ray.rayl = 10e8;
  49185. return Ray;
  49186. }());
  49187. BABYLON.Ray = Ray;
  49188. })(BABYLON || (BABYLON = {}));
  49189. //# sourceMappingURL=babylon.ray.js.map
  49190. var BABYLON;
  49191. (function (BABYLON) {
  49192. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49193. if (boxMin.x > sphereCenter.x + sphereRadius)
  49194. return false;
  49195. if (sphereCenter.x - sphereRadius > boxMax.x)
  49196. return false;
  49197. if (boxMin.y > sphereCenter.y + sphereRadius)
  49198. return false;
  49199. if (sphereCenter.y - sphereRadius > boxMax.y)
  49200. return false;
  49201. if (boxMin.z > sphereCenter.z + sphereRadius)
  49202. return false;
  49203. if (sphereCenter.z - sphereRadius > boxMax.z)
  49204. return false;
  49205. return true;
  49206. };
  49207. var getLowestRoot = (function () {
  49208. var result = { root: 0, found: false };
  49209. return function (a, b, c, maxR) {
  49210. result.root = 0;
  49211. result.found = false;
  49212. var determinant = b * b - 4.0 * a * c;
  49213. if (determinant < 0)
  49214. return result;
  49215. var sqrtD = Math.sqrt(determinant);
  49216. var r1 = (-b - sqrtD) / (2.0 * a);
  49217. var r2 = (-b + sqrtD) / (2.0 * a);
  49218. if (r1 > r2) {
  49219. var temp = r2;
  49220. r2 = r1;
  49221. r1 = temp;
  49222. }
  49223. if (r1 > 0 && r1 < maxR) {
  49224. result.root = r1;
  49225. result.found = true;
  49226. return result;
  49227. }
  49228. if (r2 > 0 && r2 < maxR) {
  49229. result.root = r2;
  49230. result.found = true;
  49231. return result;
  49232. }
  49233. return result;
  49234. };
  49235. })();
  49236. var Collider = /** @class */ (function () {
  49237. function Collider() {
  49238. this._collisionPoint = BABYLON.Vector3.Zero();
  49239. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49240. this._tempVector = BABYLON.Vector3.Zero();
  49241. this._tempVector2 = BABYLON.Vector3.Zero();
  49242. this._tempVector3 = BABYLON.Vector3.Zero();
  49243. this._tempVector4 = BABYLON.Vector3.Zero();
  49244. this._edge = BABYLON.Vector3.Zero();
  49245. this._baseToVertex = BABYLON.Vector3.Zero();
  49246. this._destinationPoint = BABYLON.Vector3.Zero();
  49247. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49248. this._displacementVector = BABYLON.Vector3.Zero();
  49249. this._radius = BABYLON.Vector3.One();
  49250. this._retry = 0;
  49251. this._basePointWorld = BABYLON.Vector3.Zero();
  49252. this._velocityWorld = BABYLON.Vector3.Zero();
  49253. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49254. this._collisionMask = -1;
  49255. }
  49256. Object.defineProperty(Collider.prototype, "collisionMask", {
  49257. get: function () {
  49258. return this._collisionMask;
  49259. },
  49260. set: function (mask) {
  49261. this._collisionMask = !isNaN(mask) ? mask : -1;
  49262. },
  49263. enumerable: true,
  49264. configurable: true
  49265. });
  49266. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49267. /**
  49268. * Gets the plane normal used to compute the sliding response (in local space)
  49269. */
  49270. get: function () {
  49271. return this._slidePlaneNormal;
  49272. },
  49273. enumerable: true,
  49274. configurable: true
  49275. });
  49276. // Methods
  49277. Collider.prototype._initialize = function (source, dir, e) {
  49278. this._velocity = dir;
  49279. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49280. this._basePoint = source;
  49281. source.multiplyToRef(this._radius, this._basePointWorld);
  49282. dir.multiplyToRef(this._radius, this._velocityWorld);
  49283. this._velocityWorldLength = this._velocityWorld.length();
  49284. this._epsilon = e;
  49285. this.collisionFound = false;
  49286. };
  49287. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49288. pa.subtractToRef(point, this._tempVector);
  49289. pb.subtractToRef(point, this._tempVector2);
  49290. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49291. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49292. if (d < 0)
  49293. return false;
  49294. pc.subtractToRef(point, this._tempVector3);
  49295. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49296. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49297. if (d < 0)
  49298. return false;
  49299. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49300. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49301. return d >= 0;
  49302. };
  49303. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49304. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49305. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49306. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49307. return false;
  49308. }
  49309. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49310. return false;
  49311. return true;
  49312. };
  49313. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49314. var t0;
  49315. var embeddedInPlane = false;
  49316. //defensive programming, actually not needed.
  49317. if (!trianglePlaneArray) {
  49318. trianglePlaneArray = [];
  49319. }
  49320. if (!trianglePlaneArray[faceIndex]) {
  49321. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49322. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49323. }
  49324. var trianglePlane = trianglePlaneArray[faceIndex];
  49325. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49326. return;
  49327. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49328. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49329. if (normalDotVelocity == 0) {
  49330. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49331. return;
  49332. embeddedInPlane = true;
  49333. t0 = 0;
  49334. }
  49335. else {
  49336. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49337. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49338. if (t0 > t1) {
  49339. var temp = t1;
  49340. t1 = t0;
  49341. t0 = temp;
  49342. }
  49343. if (t0 > 1.0 || t1 < 0.0)
  49344. return;
  49345. if (t0 < 0)
  49346. t0 = 0;
  49347. if (t0 > 1.0)
  49348. t0 = 1.0;
  49349. }
  49350. this._collisionPoint.copyFromFloats(0, 0, 0);
  49351. var found = false;
  49352. var t = 1.0;
  49353. if (!embeddedInPlane) {
  49354. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49355. this._velocity.scaleToRef(t0, this._tempVector);
  49356. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49357. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49358. found = true;
  49359. t = t0;
  49360. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49361. }
  49362. }
  49363. if (!found) {
  49364. var velocitySquaredLength = this._velocity.lengthSquared();
  49365. var a = velocitySquaredLength;
  49366. this._basePoint.subtractToRef(p1, this._tempVector);
  49367. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49368. var c = this._tempVector.lengthSquared() - 1.0;
  49369. var lowestRoot = getLowestRoot(a, b, c, t);
  49370. if (lowestRoot.found) {
  49371. t = lowestRoot.root;
  49372. found = true;
  49373. this._collisionPoint.copyFrom(p1);
  49374. }
  49375. this._basePoint.subtractToRef(p2, this._tempVector);
  49376. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49377. c = this._tempVector.lengthSquared() - 1.0;
  49378. lowestRoot = getLowestRoot(a, b, c, t);
  49379. if (lowestRoot.found) {
  49380. t = lowestRoot.root;
  49381. found = true;
  49382. this._collisionPoint.copyFrom(p2);
  49383. }
  49384. this._basePoint.subtractToRef(p3, this._tempVector);
  49385. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49386. c = this._tempVector.lengthSquared() - 1.0;
  49387. lowestRoot = getLowestRoot(a, b, c, t);
  49388. if (lowestRoot.found) {
  49389. t = lowestRoot.root;
  49390. found = true;
  49391. this._collisionPoint.copyFrom(p3);
  49392. }
  49393. p2.subtractToRef(p1, this._edge);
  49394. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49395. var edgeSquaredLength = this._edge.lengthSquared();
  49396. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49397. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49398. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49399. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49400. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49401. lowestRoot = getLowestRoot(a, b, c, t);
  49402. if (lowestRoot.found) {
  49403. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49404. if (f >= 0.0 && f <= 1.0) {
  49405. t = lowestRoot.root;
  49406. found = true;
  49407. this._edge.scaleInPlace(f);
  49408. p1.addToRef(this._edge, this._collisionPoint);
  49409. }
  49410. }
  49411. p3.subtractToRef(p2, this._edge);
  49412. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49413. edgeSquaredLength = this._edge.lengthSquared();
  49414. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49415. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49416. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49417. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49418. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49419. lowestRoot = getLowestRoot(a, b, c, t);
  49420. if (lowestRoot.found) {
  49421. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49422. if (f >= 0.0 && f <= 1.0) {
  49423. t = lowestRoot.root;
  49424. found = true;
  49425. this._edge.scaleInPlace(f);
  49426. p2.addToRef(this._edge, this._collisionPoint);
  49427. }
  49428. }
  49429. p1.subtractToRef(p3, this._edge);
  49430. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49431. edgeSquaredLength = this._edge.lengthSquared();
  49432. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49433. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49434. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49435. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49436. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49437. lowestRoot = getLowestRoot(a, b, c, t);
  49438. if (lowestRoot.found) {
  49439. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49440. if (f >= 0.0 && f <= 1.0) {
  49441. t = lowestRoot.root;
  49442. found = true;
  49443. this._edge.scaleInPlace(f);
  49444. p3.addToRef(this._edge, this._collisionPoint);
  49445. }
  49446. }
  49447. }
  49448. if (found) {
  49449. var distToCollision = t * this._velocity.length();
  49450. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49451. if (!this.intersectionPoint) {
  49452. this.intersectionPoint = this._collisionPoint.clone();
  49453. }
  49454. else {
  49455. this.intersectionPoint.copyFrom(this._collisionPoint);
  49456. }
  49457. this._nearestDistance = distToCollision;
  49458. this.collisionFound = true;
  49459. }
  49460. }
  49461. };
  49462. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49463. for (var i = indexStart; i < indexEnd; i += 3) {
  49464. var p1 = pts[indices[i] - decal];
  49465. var p2 = pts[indices[i + 1] - decal];
  49466. var p3 = pts[indices[i + 2] - decal];
  49467. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49468. }
  49469. };
  49470. Collider.prototype._getResponse = function (pos, vel) {
  49471. pos.addToRef(vel, this._destinationPoint);
  49472. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49473. this._basePoint.addToRef(vel, pos);
  49474. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49475. this._slidePlaneNormal.normalize();
  49476. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49477. pos.addInPlace(this._displacementVector);
  49478. this.intersectionPoint.addInPlace(this._displacementVector);
  49479. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49480. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49481. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49482. };
  49483. return Collider;
  49484. }());
  49485. BABYLON.Collider = Collider;
  49486. })(BABYLON || (BABYLON = {}));
  49487. //# sourceMappingURL=babylon.collider.js.map
  49488. var BABYLON;
  49489. (function (BABYLON) {
  49490. //WebWorker code will be inserted to this variable.
  49491. BABYLON.CollisionWorker = "";
  49492. var WorkerTaskType;
  49493. (function (WorkerTaskType) {
  49494. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49495. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49496. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49497. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49498. var WorkerReplyType;
  49499. (function (WorkerReplyType) {
  49500. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49501. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49502. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49503. var CollisionCoordinatorWorker = /** @class */ (function () {
  49504. function CollisionCoordinatorWorker() {
  49505. var _this = this;
  49506. this._scaledPosition = BABYLON.Vector3.Zero();
  49507. this._scaledVelocity = BABYLON.Vector3.Zero();
  49508. this.onMeshUpdated = function (transformNode) {
  49509. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49510. };
  49511. this.onGeometryUpdated = function (geometry) {
  49512. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49513. };
  49514. this._afterRender = function () {
  49515. if (!_this._init)
  49516. return;
  49517. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49518. return;
  49519. }
  49520. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49521. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49522. if (_this._runningUpdated > 4) {
  49523. return;
  49524. }
  49525. ++_this._runningUpdated;
  49526. var payload = {
  49527. updatedMeshes: _this._addUpdateMeshesList,
  49528. updatedGeometries: _this._addUpdateGeometriesList,
  49529. removedGeometries: _this._toRemoveGeometryArray,
  49530. removedMeshes: _this._toRemoveMeshesArray
  49531. };
  49532. var message = {
  49533. payload: payload,
  49534. taskType: WorkerTaskType.UPDATE
  49535. };
  49536. var serializable = [];
  49537. for (var id in payload.updatedGeometries) {
  49538. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49539. //prepare transferables
  49540. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49541. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49542. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49543. }
  49544. }
  49545. _this._worker.postMessage(message, serializable);
  49546. _this._addUpdateMeshesList = {};
  49547. _this._addUpdateGeometriesList = {};
  49548. _this._toRemoveGeometryArray = [];
  49549. _this._toRemoveMeshesArray = [];
  49550. };
  49551. this._onMessageFromWorker = function (e) {
  49552. var returnData = e.data;
  49553. if (returnData.error != WorkerReplyType.SUCCESS) {
  49554. //TODO what errors can be returned from the worker?
  49555. BABYLON.Tools.Warn("error returned from worker!");
  49556. return;
  49557. }
  49558. switch (returnData.taskType) {
  49559. case WorkerTaskType.INIT:
  49560. _this._init = true;
  49561. //Update the worked with ALL of the scene's current state
  49562. _this._scene.meshes.forEach(function (mesh) {
  49563. _this.onMeshAdded(mesh);
  49564. });
  49565. _this._scene.getGeometries().forEach(function (geometry) {
  49566. _this.onGeometryAdded(geometry);
  49567. });
  49568. break;
  49569. case WorkerTaskType.UPDATE:
  49570. _this._runningUpdated--;
  49571. break;
  49572. case WorkerTaskType.COLLIDE:
  49573. var returnPayload = returnData.payload;
  49574. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49575. return;
  49576. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49577. if (callback) {
  49578. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49579. if (mesh) {
  49580. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49581. }
  49582. }
  49583. //cleanup
  49584. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49585. break;
  49586. }
  49587. };
  49588. this._collisionsCallbackArray = [];
  49589. this._init = false;
  49590. this._runningUpdated = 0;
  49591. this._addUpdateMeshesList = {};
  49592. this._addUpdateGeometriesList = {};
  49593. this._toRemoveGeometryArray = [];
  49594. this._toRemoveMeshesArray = [];
  49595. }
  49596. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49597. if (!this._init)
  49598. return;
  49599. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49600. return;
  49601. position.divideToRef(collider._radius, this._scaledPosition);
  49602. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49603. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49604. var payload = {
  49605. collider: {
  49606. position: this._scaledPosition.asArray(),
  49607. velocity: this._scaledVelocity.asArray(),
  49608. radius: collider._radius.asArray()
  49609. },
  49610. collisionId: collisionIndex,
  49611. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49612. maximumRetry: maximumRetry
  49613. };
  49614. var message = {
  49615. payload: payload,
  49616. taskType: WorkerTaskType.COLLIDE
  49617. };
  49618. this._worker.postMessage(message);
  49619. };
  49620. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49621. this._scene = scene;
  49622. this._scene.registerAfterRender(this._afterRender);
  49623. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49624. this._worker = new Worker(workerUrl);
  49625. this._worker.onmessage = this._onMessageFromWorker;
  49626. var message = {
  49627. payload: {},
  49628. taskType: WorkerTaskType.INIT
  49629. };
  49630. this._worker.postMessage(message);
  49631. };
  49632. CollisionCoordinatorWorker.prototype.destroy = function () {
  49633. this._scene.unregisterAfterRender(this._afterRender);
  49634. this._worker.terminate();
  49635. };
  49636. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49637. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49638. this.onMeshUpdated(mesh);
  49639. };
  49640. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49641. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49642. };
  49643. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49644. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49645. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49646. this.onGeometryUpdated(geometry);
  49647. };
  49648. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49649. this._toRemoveGeometryArray.push(geometry.id);
  49650. };
  49651. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49652. var submeshes = [];
  49653. if (mesh.subMeshes) {
  49654. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49655. var boundingInfo = sm.getBoundingInfo();
  49656. return {
  49657. position: idx,
  49658. verticesStart: sm.verticesStart,
  49659. verticesCount: sm.verticesCount,
  49660. indexStart: sm.indexStart,
  49661. indexCount: sm.indexCount,
  49662. hasMaterial: !!sm.getMaterial(),
  49663. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49664. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49665. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49666. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49667. };
  49668. });
  49669. }
  49670. var geometryId = null;
  49671. if (mesh instanceof BABYLON.Mesh) {
  49672. var geometry = mesh.geometry;
  49673. geometryId = geometry ? geometry.id : null;
  49674. }
  49675. else if (mesh instanceof BABYLON.InstancedMesh) {
  49676. var geometry = mesh.sourceMesh.geometry;
  49677. geometryId = geometry ? geometry.id : null;
  49678. }
  49679. var boundingInfo = mesh.getBoundingInfo();
  49680. return {
  49681. uniqueId: mesh.uniqueId,
  49682. id: mesh.id,
  49683. name: mesh.name,
  49684. geometryId: geometryId,
  49685. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49686. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49687. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49688. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49689. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49690. subMeshes: submeshes,
  49691. checkCollisions: mesh.checkCollisions
  49692. };
  49693. };
  49694. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49695. return {
  49696. id: geometry.id,
  49697. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49698. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49699. indices: new Uint32Array(geometry.getIndices() || []),
  49700. };
  49701. };
  49702. return CollisionCoordinatorWorker;
  49703. }());
  49704. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49705. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49706. function CollisionCoordinatorLegacy() {
  49707. this._scaledPosition = BABYLON.Vector3.Zero();
  49708. this._scaledVelocity = BABYLON.Vector3.Zero();
  49709. this._finalPosition = BABYLON.Vector3.Zero();
  49710. }
  49711. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49712. position.divideToRef(collider._radius, this._scaledPosition);
  49713. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49714. collider.collidedMesh = null;
  49715. collider._retry = 0;
  49716. collider._initialVelocity = this._scaledVelocity;
  49717. collider._initialPosition = this._scaledPosition;
  49718. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49719. this._finalPosition.multiplyInPlace(collider._radius);
  49720. //run the callback
  49721. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49722. };
  49723. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49724. this._scene = scene;
  49725. };
  49726. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49727. //Legacy need no destruction method.
  49728. };
  49729. //No update in legacy mode
  49730. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49731. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49732. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49733. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49734. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49735. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49736. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49737. if (excludedMesh === void 0) { excludedMesh = null; }
  49738. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49739. if (collider._retry >= maximumRetry) {
  49740. finalPosition.copyFrom(position);
  49741. return;
  49742. }
  49743. // Check if this is a mesh else camera or -1
  49744. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49745. collider._initialize(position, velocity, closeDistance);
  49746. // Check all meshes
  49747. for (var index = 0; index < this._scene.meshes.length; index++) {
  49748. var mesh = this._scene.meshes[index];
  49749. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49750. mesh._checkCollision(collider);
  49751. }
  49752. }
  49753. if (!collider.collisionFound) {
  49754. position.addToRef(velocity, finalPosition);
  49755. return;
  49756. }
  49757. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49758. collider._getResponse(position, velocity);
  49759. }
  49760. if (velocity.length() <= closeDistance) {
  49761. finalPosition.copyFrom(position);
  49762. return;
  49763. }
  49764. collider._retry++;
  49765. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49766. };
  49767. return CollisionCoordinatorLegacy;
  49768. }());
  49769. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49770. })(BABYLON || (BABYLON = {}));
  49771. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49772. var BABYLON;
  49773. (function (BABYLON) {
  49774. /**
  49775. * A particle represents one of the element emitted by a particle system.
  49776. * This is mainly define by its coordinates, direction, velocity and age.
  49777. */
  49778. var Particle = /** @class */ (function () {
  49779. /**
  49780. * Creates a new instance of @see Particle
  49781. * @param particleSystem the particle system the particle belongs to
  49782. */
  49783. function Particle(particleSystem) {
  49784. this.particleSystem = particleSystem;
  49785. /**
  49786. * The world position of the particle in the scene.
  49787. */
  49788. this.position = BABYLON.Vector3.Zero();
  49789. /**
  49790. * The world direction of the particle in the scene.
  49791. */
  49792. this.direction = BABYLON.Vector3.Zero();
  49793. /**
  49794. * The color of the particle.
  49795. */
  49796. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49797. /**
  49798. * The color change of the particle per step.
  49799. */
  49800. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49801. /**
  49802. * Defines how long will the life of the particle be.
  49803. */
  49804. this.lifeTime = 1.0;
  49805. /**
  49806. * The current age of the particle.
  49807. */
  49808. this.age = 0;
  49809. /**
  49810. * The current size of the particle.
  49811. */
  49812. this.size = 0;
  49813. /**
  49814. * The current angle of the particle.
  49815. */
  49816. this.angle = 0;
  49817. /**
  49818. * Defines how fast is the angle changing.
  49819. */
  49820. this.angularSpeed = 0;
  49821. /**
  49822. * Defines the cell index used by the particle to be rendered from a sprite.
  49823. */
  49824. this.cellIndex = 0;
  49825. this._currentFrameCounter = 0;
  49826. if (!this.particleSystem.isAnimationSheetEnabled) {
  49827. return;
  49828. }
  49829. this.cellIndex = this.particleSystem.startSpriteCellID;
  49830. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49831. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49832. }
  49833. else {
  49834. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49835. }
  49836. }
  49837. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49838. // (ageOffset / scaledUpdateSpeed) / available cells
  49839. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49840. this._currentFrameCounter += scaledUpdateSpeed;
  49841. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49842. this._currentFrameCounter = 0;
  49843. this.cellIndex++;
  49844. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49845. this.cellIndex = this.particleSystem.endSpriteCellID;
  49846. }
  49847. }
  49848. };
  49849. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49850. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49851. this.cellIndex++;
  49852. this._currentFrameCounter = 0;
  49853. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49854. if (this.particleSystem.spriteCellLoop) {
  49855. this.cellIndex = this.particleSystem.startSpriteCellID;
  49856. }
  49857. else {
  49858. this.cellIndex = this.particleSystem.endSpriteCellID;
  49859. }
  49860. }
  49861. }
  49862. else {
  49863. this._currentFrameCounter++;
  49864. }
  49865. };
  49866. /**
  49867. * Copy the properties of particle to another one.
  49868. * @param other the particle to copy the information to.
  49869. */
  49870. Particle.prototype.copyTo = function (other) {
  49871. other.position.copyFrom(this.position);
  49872. other.direction.copyFrom(this.direction);
  49873. other.color.copyFrom(this.color);
  49874. other.colorStep.copyFrom(this.colorStep);
  49875. other.lifeTime = this.lifeTime;
  49876. other.age = this.age;
  49877. other.size = this.size;
  49878. other.angle = this.angle;
  49879. other.angularSpeed = this.angularSpeed;
  49880. other.particleSystem = this.particleSystem;
  49881. other.cellIndex = this.cellIndex;
  49882. };
  49883. return Particle;
  49884. }());
  49885. BABYLON.Particle = Particle;
  49886. })(BABYLON || (BABYLON = {}));
  49887. //# sourceMappingURL=babylon.particle.js.map
  49888. var BABYLON;
  49889. (function (BABYLON) {
  49890. /**
  49891. * This represents a particle system in Babylon.
  49892. * 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.
  49893. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49894. * @example https://doc.babylonjs.com/babylon101/particles
  49895. */
  49896. var ParticleSystem = /** @class */ (function () {
  49897. /**
  49898. * Instantiates a particle system.
  49899. * 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.
  49900. * @param name The name of the particle system
  49901. * @param capacity The max number of particles alive at the same time
  49902. * @param scene The scene the particle system belongs to
  49903. * @param customEffect a custom effect used to change the way particles are rendered by default
  49904. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49905. * @param epsilon Offset used to render the particles
  49906. */
  49907. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49908. if (customEffect === void 0) { customEffect = null; }
  49909. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49910. if (epsilon === void 0) { epsilon = 0.01; }
  49911. var _this = this;
  49912. /**
  49913. * List of animations used by the particle system.
  49914. */
  49915. this.animations = [];
  49916. /**
  49917. * The rendering group used by the Particle system to chose when to render.
  49918. */
  49919. this.renderingGroupId = 0;
  49920. /**
  49921. * The emitter represents the Mesh or position we are attaching the particle system to.
  49922. */
  49923. this.emitter = null;
  49924. /**
  49925. * The density of particles, the rate of particle flow
  49926. */
  49927. this.emitRate = 10;
  49928. /**
  49929. * If you want to launch only a few particles at once, that can be done, as well.
  49930. */
  49931. this.manualEmitCount = -1;
  49932. /**
  49933. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49934. */
  49935. this.updateSpeed = 0.01;
  49936. /**
  49937. * The amount of time the particle system is running (depends of the overall speed above).
  49938. */
  49939. this.targetStopDuration = 0;
  49940. /**
  49941. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49942. */
  49943. this.disposeOnStop = false;
  49944. /**
  49945. * Minimum power of emitting particles.
  49946. */
  49947. this.minEmitPower = 1;
  49948. /**
  49949. * Maximum power of emitting particles.
  49950. */
  49951. this.maxEmitPower = 1;
  49952. /**
  49953. * Minimum life time of emitting particles.
  49954. */
  49955. this.minLifeTime = 1;
  49956. /**
  49957. * Maximum life time of emitting particles.
  49958. */
  49959. this.maxLifeTime = 1;
  49960. /**
  49961. * Minimum Size of emitting particles.
  49962. */
  49963. this.minSize = 1;
  49964. /**
  49965. * Maximum Size of emitting particles.
  49966. */
  49967. this.maxSize = 1;
  49968. /**
  49969. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49970. */
  49971. this.minAngularSpeed = 0;
  49972. /**
  49973. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49974. */
  49975. this.maxAngularSpeed = 0;
  49976. /**
  49977. * The layer mask we are rendering the particles through.
  49978. */
  49979. this.layerMask = 0x0FFFFFFF;
  49980. /**
  49981. * This can help using your own shader to render the particle system.
  49982. * The according effect will be created
  49983. */
  49984. this.customShader = null;
  49985. /**
  49986. * By default particle system starts as soon as they are created. This prevents the
  49987. * automatic start to happen and let you decide when to start emitting particles.
  49988. */
  49989. this.preventAutoStart = false;
  49990. /**
  49991. * Callback triggered when the particle animation is ending.
  49992. */
  49993. this.onAnimationEnd = null;
  49994. /**
  49995. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49996. */
  49997. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49998. /**
  49999. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50000. * to override the particles.
  50001. */
  50002. this.forceDepthWrite = false;
  50003. /**
  50004. * You can use gravity if you want to give an orientation to your particles.
  50005. */
  50006. this.gravity = BABYLON.Vector3.Zero();
  50007. /**
  50008. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50009. */
  50010. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  50011. /**
  50012. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50013. */
  50014. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  50015. /**
  50016. * 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.
  50017. */
  50018. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  50019. /**
  50020. * 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.
  50021. */
  50022. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  50023. /**
  50024. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50025. */
  50026. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50027. /**
  50028. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50029. */
  50030. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50031. /**
  50032. * Color the particle will have at the end of its lifetime.
  50033. */
  50034. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50035. /**
  50036. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50037. */
  50038. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50039. /**
  50040. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50041. */
  50042. this.spriteCellLoop = true;
  50043. /**
  50044. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50045. */
  50046. this.spriteCellChangeSpeed = 0;
  50047. /**
  50048. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50049. */
  50050. this.startSpriteCellID = 0;
  50051. /**
  50052. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50053. */
  50054. this.endSpriteCellID = 0;
  50055. /**
  50056. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50057. */
  50058. this.spriteCellWidth = 0;
  50059. /**
  50060. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50061. */
  50062. this.spriteCellHeight = 0;
  50063. /**
  50064. * An event triggered when the system is disposed.
  50065. */
  50066. this.onDisposeObservable = new BABYLON.Observable();
  50067. this._particles = new Array();
  50068. this._stockParticles = new Array();
  50069. this._newPartsExcess = 0;
  50070. this._vertexBuffers = {};
  50071. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50072. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50073. this._scaledDirection = BABYLON.Vector3.Zero();
  50074. this._scaledGravity = BABYLON.Vector3.Zero();
  50075. this._currentRenderId = -1;
  50076. this._started = false;
  50077. this._stopped = false;
  50078. this._actualFrame = 0;
  50079. this._vertexBufferSize = 11;
  50080. this._appendParticleVertexes = null;
  50081. this.id = name;
  50082. this.name = name;
  50083. this._capacity = capacity;
  50084. this._epsilon = epsilon;
  50085. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50086. if (isAnimationSheetEnabled) {
  50087. this._vertexBufferSize = 12;
  50088. }
  50089. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50090. this._customEffect = customEffect;
  50091. scene.particleSystems.push(this);
  50092. this._createIndexBuffer();
  50093. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50094. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50095. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50096. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50097. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50098. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50099. if (this._isAnimationSheetEnabled) {
  50100. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50101. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50102. }
  50103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50104. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50105. this._vertexBuffers["options"] = options;
  50106. // Default behaviors
  50107. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50108. this.updateFunction = function (particles) {
  50109. for (var index = 0; index < particles.length; index++) {
  50110. var particle = particles[index];
  50111. particle.age += _this._scaledUpdateSpeed;
  50112. if (particle.age >= particle.lifeTime) {
  50113. _this.recycleParticle(particle);
  50114. index--;
  50115. continue;
  50116. }
  50117. else {
  50118. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50119. particle.color.addInPlace(_this._scaledColorStep);
  50120. if (particle.color.a < 0)
  50121. particle.color.a = 0;
  50122. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50123. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50124. particle.position.addInPlace(_this._scaledDirection);
  50125. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50126. particle.direction.addInPlace(_this._scaledGravity);
  50127. if (_this._isAnimationSheetEnabled) {
  50128. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50129. }
  50130. }
  50131. }
  50132. };
  50133. }
  50134. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50135. /**
  50136. * Sets a callback that will be triggered when the system is disposed.
  50137. */
  50138. set: function (callback) {
  50139. if (this._onDisposeObserver) {
  50140. this.onDisposeObservable.remove(this._onDisposeObserver);
  50141. }
  50142. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50143. },
  50144. enumerable: true,
  50145. configurable: true
  50146. });
  50147. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50148. /**
  50149. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50150. */
  50151. get: function () {
  50152. return this._isAnimationSheetEnabled;
  50153. },
  50154. enumerable: true,
  50155. configurable: true
  50156. });
  50157. ParticleSystem.prototype._createIndexBuffer = function () {
  50158. var indices = [];
  50159. var index = 0;
  50160. for (var count = 0; count < this._capacity; count++) {
  50161. indices.push(index);
  50162. indices.push(index + 1);
  50163. indices.push(index + 2);
  50164. indices.push(index);
  50165. indices.push(index + 2);
  50166. indices.push(index + 3);
  50167. index += 4;
  50168. }
  50169. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50170. };
  50171. /**
  50172. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50173. * Its lifetime will start back at 0.
  50174. * @param particle The particle to recycle
  50175. */
  50176. ParticleSystem.prototype.recycleParticle = function (particle) {
  50177. var lastParticle = this._particles.pop();
  50178. if (lastParticle !== particle) {
  50179. lastParticle.copyTo(particle);
  50180. this._stockParticles.push(lastParticle);
  50181. }
  50182. };
  50183. /**
  50184. * Gets the maximum number of particles active at the same time.
  50185. * @returns The max number of active particles.
  50186. */
  50187. ParticleSystem.prototype.getCapacity = function () {
  50188. return this._capacity;
  50189. };
  50190. /**
  50191. * Gets Wether there are still active particles in the system.
  50192. * @returns True if it is alive, otherwise false.
  50193. */
  50194. ParticleSystem.prototype.isAlive = function () {
  50195. return this._alive;
  50196. };
  50197. /**
  50198. * Gets Wether the system has been started.
  50199. * @returns True if it has been started, otherwise false.
  50200. */
  50201. ParticleSystem.prototype.isStarted = function () {
  50202. return this._started;
  50203. };
  50204. /**
  50205. * Starts the particle system and begins to emit.
  50206. */
  50207. ParticleSystem.prototype.start = function () {
  50208. this._started = true;
  50209. this._stopped = false;
  50210. this._actualFrame = 0;
  50211. };
  50212. /**
  50213. * Stops the particle system.
  50214. */
  50215. ParticleSystem.prototype.stop = function () {
  50216. this._stopped = true;
  50217. };
  50218. /**
  50219. * Remove all active particles
  50220. */
  50221. ParticleSystem.prototype.reset = function () {
  50222. this._stockParticles = [];
  50223. this._particles = [];
  50224. };
  50225. /**
  50226. * @ignore (for internal use only)
  50227. */
  50228. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50229. var offset = index * this._vertexBufferSize;
  50230. this._vertexData[offset] = particle.position.x;
  50231. this._vertexData[offset + 1] = particle.position.y;
  50232. this._vertexData[offset + 2] = particle.position.z;
  50233. this._vertexData[offset + 3] = particle.color.r;
  50234. this._vertexData[offset + 4] = particle.color.g;
  50235. this._vertexData[offset + 5] = particle.color.b;
  50236. this._vertexData[offset + 6] = particle.color.a;
  50237. this._vertexData[offset + 7] = particle.angle;
  50238. this._vertexData[offset + 8] = particle.size;
  50239. this._vertexData[offset + 9] = offsetX;
  50240. this._vertexData[offset + 10] = offsetY;
  50241. };
  50242. /**
  50243. * @ignore (for internal use only)
  50244. */
  50245. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50246. if (offsetX === 0)
  50247. offsetX = this._epsilon;
  50248. else if (offsetX === 1)
  50249. offsetX = 1 - this._epsilon;
  50250. if (offsetY === 0)
  50251. offsetY = this._epsilon;
  50252. else if (offsetY === 1)
  50253. offsetY = 1 - this._epsilon;
  50254. var offset = index * this._vertexBufferSize;
  50255. this._vertexData[offset] = particle.position.x;
  50256. this._vertexData[offset + 1] = particle.position.y;
  50257. this._vertexData[offset + 2] = particle.position.z;
  50258. this._vertexData[offset + 3] = particle.color.r;
  50259. this._vertexData[offset + 4] = particle.color.g;
  50260. this._vertexData[offset + 5] = particle.color.b;
  50261. this._vertexData[offset + 6] = particle.color.a;
  50262. this._vertexData[offset + 7] = particle.angle;
  50263. this._vertexData[offset + 8] = particle.size;
  50264. this._vertexData[offset + 9] = offsetX;
  50265. this._vertexData[offset + 10] = offsetY;
  50266. this._vertexData[offset + 11] = particle.cellIndex;
  50267. };
  50268. ParticleSystem.prototype._update = function (newParticles) {
  50269. // Update current
  50270. this._alive = this._particles.length > 0;
  50271. this.updateFunction(this._particles);
  50272. // Add new ones
  50273. var worldMatrix;
  50274. if (this.emitter.position) {
  50275. var emitterMesh = this.emitter;
  50276. worldMatrix = emitterMesh.getWorldMatrix();
  50277. }
  50278. else {
  50279. var emitterPosition = this.emitter;
  50280. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50281. }
  50282. var particle;
  50283. for (var index = 0; index < newParticles; index++) {
  50284. if (this._particles.length === this._capacity) {
  50285. break;
  50286. }
  50287. if (this._stockParticles.length !== 0) {
  50288. particle = this._stockParticles.pop();
  50289. particle.age = 0;
  50290. particle.cellIndex = this.startSpriteCellID;
  50291. }
  50292. else {
  50293. particle = new BABYLON.Particle(this);
  50294. }
  50295. this._particles.push(particle);
  50296. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50297. if (this.startPositionFunction) {
  50298. this.startPositionFunction(worldMatrix, particle.position, particle);
  50299. }
  50300. else {
  50301. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50302. }
  50303. if (this.startDirectionFunction) {
  50304. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50305. }
  50306. else {
  50307. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50308. }
  50309. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50310. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50311. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50312. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50313. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50314. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50315. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50316. }
  50317. };
  50318. ParticleSystem.prototype._getEffect = function () {
  50319. if (this._customEffect) {
  50320. return this._customEffect;
  50321. }
  50322. ;
  50323. var defines = [];
  50324. if (this._scene.clipPlane) {
  50325. defines.push("#define CLIPPLANE");
  50326. }
  50327. if (this._isAnimationSheetEnabled) {
  50328. defines.push("#define ANIMATESHEET");
  50329. }
  50330. // Effect
  50331. var join = defines.join("\n");
  50332. if (this._cachedDefines !== join) {
  50333. this._cachedDefines = join;
  50334. var attributesNamesOrOptions;
  50335. var effectCreationOption;
  50336. if (this._isAnimationSheetEnabled) {
  50337. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50338. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50339. }
  50340. else {
  50341. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50342. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50343. }
  50344. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50345. }
  50346. return this._effect;
  50347. };
  50348. /**
  50349. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50350. */
  50351. ParticleSystem.prototype.animate = function () {
  50352. if (!this._started)
  50353. return;
  50354. var effect = this._getEffect();
  50355. // Check
  50356. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50357. return;
  50358. if (this._currentRenderId === this._scene.getRenderId()) {
  50359. return;
  50360. }
  50361. this._currentRenderId = this._scene.getRenderId();
  50362. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50363. // determine the number of particles we need to create
  50364. var newParticles;
  50365. if (this.manualEmitCount > -1) {
  50366. newParticles = this.manualEmitCount;
  50367. this._newPartsExcess = 0;
  50368. this.manualEmitCount = 0;
  50369. }
  50370. else {
  50371. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50372. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50373. }
  50374. if (this._newPartsExcess > 1.0) {
  50375. newParticles += this._newPartsExcess >> 0;
  50376. this._newPartsExcess -= this._newPartsExcess >> 0;
  50377. }
  50378. this._alive = false;
  50379. if (!this._stopped) {
  50380. this._actualFrame += this._scaledUpdateSpeed;
  50381. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50382. this.stop();
  50383. }
  50384. else {
  50385. newParticles = 0;
  50386. }
  50387. this._update(newParticles);
  50388. // Stopped?
  50389. if (this._stopped) {
  50390. if (!this._alive) {
  50391. this._started = false;
  50392. if (this.onAnimationEnd) {
  50393. this.onAnimationEnd();
  50394. }
  50395. if (this.disposeOnStop) {
  50396. this._scene._toBeDisposed.push(this);
  50397. }
  50398. }
  50399. }
  50400. // Animation sheet
  50401. if (this._isAnimationSheetEnabled) {
  50402. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50403. }
  50404. else {
  50405. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50406. }
  50407. // Update VBO
  50408. var offset = 0;
  50409. for (var index = 0; index < this._particles.length; index++) {
  50410. var particle = this._particles[index];
  50411. this._appendParticleVertexes(offset, particle);
  50412. offset += 4;
  50413. }
  50414. if (this._vertexBuffer) {
  50415. this._vertexBuffer.update(this._vertexData);
  50416. }
  50417. };
  50418. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50419. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50420. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50421. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50422. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50423. };
  50424. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50425. this._appendParticleVertex(offset++, particle, 0, 0);
  50426. this._appendParticleVertex(offset++, particle, 1, 0);
  50427. this._appendParticleVertex(offset++, particle, 1, 1);
  50428. this._appendParticleVertex(offset++, particle, 0, 1);
  50429. };
  50430. /**
  50431. * Rebuilds the particle system.
  50432. */
  50433. ParticleSystem.prototype.rebuild = function () {
  50434. this._createIndexBuffer();
  50435. if (this._vertexBuffer) {
  50436. this._vertexBuffer._rebuild();
  50437. }
  50438. };
  50439. /**
  50440. * Renders the particle system in its current state.
  50441. * @returns the current number of particles.
  50442. */
  50443. ParticleSystem.prototype.render = function () {
  50444. var effect = this._getEffect();
  50445. // Check
  50446. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50447. return 0;
  50448. var engine = this._scene.getEngine();
  50449. // Render
  50450. engine.enableEffect(effect);
  50451. engine.setState(false);
  50452. var viewMatrix = this._scene.getViewMatrix();
  50453. effect.setTexture("diffuseSampler", this.particleTexture);
  50454. effect.setMatrix("view", viewMatrix);
  50455. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50456. if (this._isAnimationSheetEnabled) {
  50457. var baseSize = this.particleTexture.getBaseSize();
  50458. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50459. }
  50460. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50461. if (this._scene.clipPlane) {
  50462. var clipPlane = this._scene.clipPlane;
  50463. var invView = viewMatrix.clone();
  50464. invView.invert();
  50465. effect.setMatrix("invView", invView);
  50466. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50467. }
  50468. // VBOs
  50469. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50470. // Draw order
  50471. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50472. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50473. }
  50474. else {
  50475. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50476. }
  50477. if (this.forceDepthWrite) {
  50478. engine.setDepthWrite(true);
  50479. }
  50480. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50481. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50482. return this._particles.length;
  50483. };
  50484. /**
  50485. * Disposes the particle system and free the associated resources.
  50486. */
  50487. ParticleSystem.prototype.dispose = function () {
  50488. if (this._vertexBuffer) {
  50489. this._vertexBuffer.dispose();
  50490. this._vertexBuffer = null;
  50491. }
  50492. if (this._indexBuffer) {
  50493. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50494. this._indexBuffer = null;
  50495. }
  50496. if (this.particleTexture) {
  50497. this.particleTexture.dispose();
  50498. this.particleTexture = null;
  50499. }
  50500. // Remove from scene
  50501. var index = this._scene.particleSystems.indexOf(this);
  50502. if (index > -1) {
  50503. this._scene.particleSystems.splice(index, 1);
  50504. }
  50505. // Callback
  50506. this.onDisposeObservable.notifyObservers(this);
  50507. this.onDisposeObservable.clear();
  50508. };
  50509. /**
  50510. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50511. * @param radius The radius of the sphere to emit from
  50512. * @returns the emitter
  50513. */
  50514. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50515. if (radius === void 0) { radius = 1; }
  50516. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50517. this.particleEmitterType = particleEmitter;
  50518. return particleEmitter;
  50519. };
  50520. /**
  50521. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50522. * @param radius The radius of the sphere to emit from
  50523. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50524. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50525. * @returns the emitter
  50526. */
  50527. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50528. if (radius === void 0) { radius = 1; }
  50529. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50530. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50531. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50532. this.particleEmitterType = particleEmitter;
  50533. return particleEmitter;
  50534. };
  50535. /**
  50536. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50537. * @param radius The radius of the cone to emit from
  50538. * @param angle The base angle of the cone
  50539. * @returns the emitter
  50540. */
  50541. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50542. if (radius === void 0) { radius = 1; }
  50543. if (angle === void 0) { angle = Math.PI / 4; }
  50544. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50545. this.particleEmitterType = particleEmitter;
  50546. return particleEmitter;
  50547. };
  50548. // 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.
  50549. /**
  50550. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50551. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50552. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50553. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50554. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50555. * @returns the emitter
  50556. */
  50557. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50558. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50559. this.direction1 = direction1;
  50560. this.direction2 = direction2;
  50561. this.minEmitBox = minEmitBox;
  50562. this.maxEmitBox = maxEmitBox;
  50563. this.particleEmitterType = particleEmitter;
  50564. return particleEmitter;
  50565. };
  50566. /**
  50567. * Clones the particle system.
  50568. * @param name The name of the cloned object
  50569. * @param newEmitter The new emitter to use
  50570. * @returns the cloned particle system
  50571. */
  50572. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50573. var custom = null;
  50574. var program = null;
  50575. if (this.customShader != null) {
  50576. program = this.customShader;
  50577. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50578. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50579. }
  50580. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50581. result.customShader = program;
  50582. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50583. if (newEmitter === undefined) {
  50584. newEmitter = this.emitter;
  50585. }
  50586. result.emitter = newEmitter;
  50587. if (this.particleTexture) {
  50588. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50589. }
  50590. if (!this.preventAutoStart) {
  50591. result.start();
  50592. }
  50593. return result;
  50594. };
  50595. /**
  50596. * Serializes the particle system to a JSON object.
  50597. * @returns the JSON object
  50598. */
  50599. ParticleSystem.prototype.serialize = function () {
  50600. var serializationObject = {};
  50601. serializationObject.name = this.name;
  50602. serializationObject.id = this.id;
  50603. // Emitter
  50604. if (this.emitter.position) {
  50605. var emitterMesh = this.emitter;
  50606. serializationObject.emitterId = emitterMesh.id;
  50607. }
  50608. else {
  50609. var emitterPosition = this.emitter;
  50610. serializationObject.emitter = emitterPosition.asArray();
  50611. }
  50612. serializationObject.capacity = this.getCapacity();
  50613. if (this.particleTexture) {
  50614. serializationObject.textureName = this.particleTexture.name;
  50615. }
  50616. // Animations
  50617. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50618. // Particle system
  50619. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50620. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50621. serializationObject.minSize = this.minSize;
  50622. serializationObject.maxSize = this.maxSize;
  50623. serializationObject.minEmitPower = this.minEmitPower;
  50624. serializationObject.maxEmitPower = this.maxEmitPower;
  50625. serializationObject.minLifeTime = this.minLifeTime;
  50626. serializationObject.maxLifeTime = this.maxLifeTime;
  50627. serializationObject.emitRate = this.emitRate;
  50628. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50629. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50630. serializationObject.gravity = this.gravity.asArray();
  50631. serializationObject.direction1 = this.direction1.asArray();
  50632. serializationObject.direction2 = this.direction2.asArray();
  50633. serializationObject.color1 = this.color1.asArray();
  50634. serializationObject.color2 = this.color2.asArray();
  50635. serializationObject.colorDead = this.colorDead.asArray();
  50636. serializationObject.updateSpeed = this.updateSpeed;
  50637. serializationObject.targetStopDuration = this.targetStopDuration;
  50638. serializationObject.textureMask = this.textureMask.asArray();
  50639. serializationObject.blendMode = this.blendMode;
  50640. serializationObject.customShader = this.customShader;
  50641. serializationObject.preventAutoStart = this.preventAutoStart;
  50642. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50643. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50644. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50645. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50646. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50647. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50648. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50649. return serializationObject;
  50650. };
  50651. /**
  50652. * Parses a JSON object to create a particle system.
  50653. * @param parsedParticleSystem The JSON object to parse
  50654. * @param scene The scene to create the particle system in
  50655. * @param rootUrl The root url to use to load external dependencies like texture
  50656. * @returns the Parsed particle system
  50657. */
  50658. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50659. var name = parsedParticleSystem.name;
  50660. var custom = null;
  50661. var program = null;
  50662. if (parsedParticleSystem.customShader) {
  50663. program = parsedParticleSystem.customShader;
  50664. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50665. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50666. }
  50667. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50668. particleSystem.customShader = program;
  50669. if (parsedParticleSystem.id) {
  50670. particleSystem.id = parsedParticleSystem.id;
  50671. }
  50672. // Auto start
  50673. if (parsedParticleSystem.preventAutoStart) {
  50674. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50675. }
  50676. // Texture
  50677. if (parsedParticleSystem.textureName) {
  50678. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50679. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50680. }
  50681. // Emitter
  50682. if (parsedParticleSystem.emitterId) {
  50683. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50684. }
  50685. else {
  50686. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50687. }
  50688. // Animations
  50689. if (parsedParticleSystem.animations) {
  50690. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50691. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50692. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50693. }
  50694. }
  50695. if (parsedParticleSystem.autoAnimate) {
  50696. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50697. }
  50698. // Particle system
  50699. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50700. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50701. particleSystem.minSize = parsedParticleSystem.minSize;
  50702. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50703. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50704. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50705. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50706. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50707. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50708. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50709. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50710. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50711. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50712. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50713. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50714. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50715. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50716. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50717. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50718. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50719. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50720. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50721. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50722. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50723. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50724. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50725. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50726. if (!particleSystem.preventAutoStart) {
  50727. particleSystem.start();
  50728. }
  50729. return particleSystem;
  50730. };
  50731. /**
  50732. * Source color is added to the destination color without alpha affecting the result.
  50733. */
  50734. ParticleSystem.BLENDMODE_ONEONE = 0;
  50735. /**
  50736. * Blend current color and particle color using particle’s alpha.
  50737. */
  50738. ParticleSystem.BLENDMODE_STANDARD = 1;
  50739. return ParticleSystem;
  50740. }());
  50741. BABYLON.ParticleSystem = ParticleSystem;
  50742. })(BABYLON || (BABYLON = {}));
  50743. //# sourceMappingURL=babylon.particleSystem.js.map
  50744. var BABYLON;
  50745. (function (BABYLON) {
  50746. /**
  50747. * Particle emitter emitting particles from the inside of a box.
  50748. * It emits the particles randomly between 2 given directions.
  50749. */
  50750. var BoxParticleEmitter = /** @class */ (function () {
  50751. // to be updated like the rest of emitters when breaking changes.
  50752. // all property should be come public variables and passed through constructor.
  50753. /**
  50754. * Creates a new instance of @see BoxParticleEmitter
  50755. * @param _particleSystem the particle system associated with the emitter
  50756. */
  50757. function BoxParticleEmitter(_particleSystem) {
  50758. this._particleSystem = _particleSystem;
  50759. }
  50760. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50761. /**
  50762. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50763. */
  50764. get: function () {
  50765. return this._particleSystem.direction1;
  50766. },
  50767. /**
  50768. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50769. */
  50770. set: function (value) {
  50771. this._particleSystem.direction1 = value;
  50772. },
  50773. enumerable: true,
  50774. configurable: true
  50775. });
  50776. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50777. /**
  50778. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50779. */
  50780. get: function () {
  50781. return this._particleSystem.direction2;
  50782. },
  50783. /**
  50784. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50785. */
  50786. set: function (value) {
  50787. this._particleSystem.direction2 = value;
  50788. },
  50789. enumerable: true,
  50790. configurable: true
  50791. });
  50792. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50793. /**
  50794. * 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.
  50795. */
  50796. get: function () {
  50797. return this._particleSystem.minEmitBox;
  50798. },
  50799. /**
  50800. * 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.
  50801. */
  50802. set: function (value) {
  50803. this._particleSystem.minEmitBox = value;
  50804. },
  50805. enumerable: true,
  50806. configurable: true
  50807. });
  50808. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50809. /**
  50810. * 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.
  50811. */
  50812. get: function () {
  50813. return this._particleSystem.maxEmitBox;
  50814. },
  50815. /**
  50816. * 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.
  50817. */
  50818. set: function (value) {
  50819. this._particleSystem.maxEmitBox = value;
  50820. },
  50821. enumerable: true,
  50822. configurable: true
  50823. });
  50824. /**
  50825. * Called by the particle System when the direction is computed for the created particle.
  50826. * @param emitPower is the power of the particle (speed)
  50827. * @param worldMatrix is the world matrix of the particle system
  50828. * @param directionToUpdate is the direction vector to update with the result
  50829. * @param particle is the particle we are computed the direction for
  50830. */
  50831. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50832. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50833. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50834. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50835. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50836. };
  50837. /**
  50838. * Called by the particle System when the position is computed for the created particle.
  50839. * @param worldMatrix is the world matrix of the particle system
  50840. * @param positionToUpdate is the position vector to update with the result
  50841. * @param particle is the particle we are computed the position for
  50842. */
  50843. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50844. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50845. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50846. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50847. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50848. };
  50849. /**
  50850. * Clones the current emitter and returns a copy of it
  50851. * @returns the new emitter
  50852. */
  50853. BoxParticleEmitter.prototype.clone = function () {
  50854. var newOne = new BoxParticleEmitter(this._particleSystem);
  50855. BABYLON.Tools.DeepCopy(this, newOne);
  50856. return newOne;
  50857. };
  50858. return BoxParticleEmitter;
  50859. }());
  50860. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50861. })(BABYLON || (BABYLON = {}));
  50862. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50863. var BABYLON;
  50864. (function (BABYLON) {
  50865. /**
  50866. * Particle emitter emitting particles from the inside of a cone.
  50867. * It emits the particles alongside the cone volume from the base to the particle.
  50868. * The emission direction might be randomized.
  50869. */
  50870. var ConeParticleEmitter = /** @class */ (function () {
  50871. /**
  50872. * Creates a new instance of @see ConeParticleEmitter
  50873. * @param radius the radius of the emission cone
  50874. * @param angles the cone base angle
  50875. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50876. */
  50877. function ConeParticleEmitter(radius,
  50878. /**
  50879. * The radius of the emission cone.
  50880. */
  50881. angle,
  50882. /**
  50883. * The cone base angle.
  50884. */
  50885. directionRandomizer) {
  50886. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50887. this.angle = angle;
  50888. this.directionRandomizer = directionRandomizer;
  50889. this.radius = radius;
  50890. }
  50891. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50892. /**
  50893. * Gets the radius of the emission cone.
  50894. */
  50895. get: function () {
  50896. return this._radius;
  50897. },
  50898. /**
  50899. * Sets the radius of the emission cone.
  50900. */
  50901. set: function (value) {
  50902. this._radius = value;
  50903. if (this.angle !== 0) {
  50904. this._height = value / Math.tan(this.angle / 2);
  50905. }
  50906. else {
  50907. this._height = 1;
  50908. }
  50909. },
  50910. enumerable: true,
  50911. configurable: true
  50912. });
  50913. /**
  50914. * Called by the particle System when the direction is computed for the created particle.
  50915. * @param emitPower is the power of the particle (speed)
  50916. * @param worldMatrix is the world matrix of the particle system
  50917. * @param directionToUpdate is the direction vector to update with the result
  50918. * @param particle is the particle we are computed the direction for
  50919. */
  50920. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50921. if (this.angle === 0) {
  50922. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50923. }
  50924. else {
  50925. // measure the direction Vector from the emitter to the particle.
  50926. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50927. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50928. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50929. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50930. direction.x += randX;
  50931. direction.y += randY;
  50932. direction.z += randZ;
  50933. direction.normalize();
  50934. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50935. }
  50936. };
  50937. /**
  50938. * Called by the particle System when the position is computed for the created particle.
  50939. * @param worldMatrix is the world matrix of the particle system
  50940. * @param positionToUpdate is the position vector to update with the result
  50941. * @param particle is the particle we are computed the position for
  50942. */
  50943. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50944. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50945. var h = BABYLON.Scalar.RandomRange(0, 1);
  50946. // Better distribution in a cone at normal angles.
  50947. h = 1 - h * h;
  50948. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50949. radius = radius * h / this._height;
  50950. var randX = radius * Math.sin(s);
  50951. var randZ = radius * Math.cos(s);
  50952. var randY = h;
  50953. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50954. };
  50955. /**
  50956. * Clones the current emitter and returns a copy of it
  50957. * @returns the new emitter
  50958. */
  50959. ConeParticleEmitter.prototype.clone = function () {
  50960. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50961. BABYLON.Tools.DeepCopy(this, newOne);
  50962. return newOne;
  50963. };
  50964. return ConeParticleEmitter;
  50965. }());
  50966. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50967. })(BABYLON || (BABYLON = {}));
  50968. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50969. var BABYLON;
  50970. (function (BABYLON) {
  50971. /**
  50972. * Particle emitter emitting particles from the inside of a sphere.
  50973. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50974. */
  50975. var SphereParticleEmitter = /** @class */ (function () {
  50976. /**
  50977. * Creates a new instance of @see SphereParticleEmitter
  50978. * @param radius the radius of the emission sphere
  50979. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50980. */
  50981. function SphereParticleEmitter(
  50982. /**
  50983. * The radius of the emission sphere.
  50984. */
  50985. radius,
  50986. /**
  50987. * How much to randomize the particle direction [0-1].
  50988. */
  50989. directionRandomizer) {
  50990. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50991. this.radius = radius;
  50992. this.directionRandomizer = directionRandomizer;
  50993. }
  50994. /**
  50995. * Called by the particle System when the direction is computed for the created particle.
  50996. * @param emitPower is the power of the particle (speed)
  50997. * @param worldMatrix is the world matrix of the particle system
  50998. * @param directionToUpdate is the direction vector to update with the result
  50999. * @param particle is the particle we are computed the direction for
  51000. */
  51001. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51002. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51003. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51004. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51005. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51006. direction.x += randX;
  51007. direction.y += randY;
  51008. direction.z += randZ;
  51009. direction.normalize();
  51010. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51011. };
  51012. /**
  51013. * Called by the particle System when the position is computed for the created particle.
  51014. * @param worldMatrix is the world matrix of the particle system
  51015. * @param positionToUpdate is the position vector to update with the result
  51016. * @param particle is the particle we are computed the position for
  51017. */
  51018. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51019. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51020. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51021. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  51022. var randY = this.radius * Math.cos(theta);
  51023. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51024. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51025. };
  51026. /**
  51027. * Clones the current emitter and returns a copy of it
  51028. * @returns the new emitter
  51029. */
  51030. SphereParticleEmitter.prototype.clone = function () {
  51031. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51032. BABYLON.Tools.DeepCopy(this, newOne);
  51033. return newOne;
  51034. };
  51035. return SphereParticleEmitter;
  51036. }());
  51037. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51038. /**
  51039. * Particle emitter emitting particles from the inside of a sphere.
  51040. * It emits the particles randomly between two vectors.
  51041. */
  51042. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51043. __extends(SphereDirectedParticleEmitter, _super);
  51044. /**
  51045. * Creates a new instance of @see SphereDirectedParticleEmitter
  51046. * @param radius the radius of the emission sphere
  51047. * @param direction1 the min limit of the emission direction
  51048. * @param direction2 the max limit of the emission direction
  51049. */
  51050. function SphereDirectedParticleEmitter(radius,
  51051. /**
  51052. * The min limit of the emission direction.
  51053. */
  51054. direction1,
  51055. /**
  51056. * The max limit of the emission direction.
  51057. */
  51058. direction2) {
  51059. var _this = _super.call(this, radius) || this;
  51060. _this.direction1 = direction1;
  51061. _this.direction2 = direction2;
  51062. return _this;
  51063. }
  51064. /**
  51065. * Called by the particle System when the direction is computed for the created particle.
  51066. * @param emitPower is the power of the particle (speed)
  51067. * @param worldMatrix is the world matrix of the particle system
  51068. * @param directionToUpdate is the direction vector to update with the result
  51069. * @param particle is the particle we are computed the direction for
  51070. */
  51071. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51072. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51073. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51074. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51075. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51076. };
  51077. /**
  51078. * Clones the current emitter and returns a copy of it
  51079. * @returns the new emitter
  51080. */
  51081. SphereDirectedParticleEmitter.prototype.clone = function () {
  51082. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51083. BABYLON.Tools.DeepCopy(this, newOne);
  51084. return newOne;
  51085. };
  51086. return SphereDirectedParticleEmitter;
  51087. }(SphereParticleEmitter));
  51088. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51089. })(BABYLON || (BABYLON = {}));
  51090. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51091. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  51092. var BABYLON;
  51093. (function (BABYLON) {
  51094. /**
  51095. * Represents one particle of a solid particle system.
  51096. * @see SolidParticleSystem
  51097. */
  51098. var SolidParticle = /** @class */ (function () {
  51099. /**
  51100. * Creates a Solid Particle object.
  51101. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51102. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51103. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51104. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51105. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51106. * @param shapeId (integer) is the model shape identifier in the SPS.
  51107. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51108. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51109. */
  51110. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51111. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51112. /**
  51113. * particle global index
  51114. */
  51115. this.idx = 0;
  51116. /**
  51117. * The color of the particle
  51118. */
  51119. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51120. /**
  51121. * The world space position of the particle.
  51122. */
  51123. this.position = BABYLON.Vector3.Zero();
  51124. /**
  51125. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51126. */
  51127. this.rotation = BABYLON.Vector3.Zero();
  51128. /**
  51129. * The scaling of the particle.
  51130. */
  51131. this.scaling = BABYLON.Vector3.One();
  51132. /**
  51133. * The uvs of the particle.
  51134. */
  51135. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51136. /**
  51137. * The current speed of the particle.
  51138. */
  51139. this.velocity = BABYLON.Vector3.Zero();
  51140. /**
  51141. * The pivot point in the particle local space.
  51142. */
  51143. this.pivot = BABYLON.Vector3.Zero();
  51144. /**
  51145. * Must the particle be translated from its pivot point in its local space ?
  51146. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51147. * Default : false
  51148. */
  51149. this.translateFromPivot = false;
  51150. /**
  51151. * Is the particle active or not ?
  51152. */
  51153. this.alive = true;
  51154. /**
  51155. * Is the particle visible or not ?
  51156. */
  51157. this.isVisible = true;
  51158. /**
  51159. * Index of this particle in the global "positions" array (Internal use)
  51160. */
  51161. this._pos = 0;
  51162. /**
  51163. * Index of this particle in the global "indices" array (Internal use)
  51164. */
  51165. this._ind = 0;
  51166. /**
  51167. * ModelShape id of this particle
  51168. */
  51169. this.shapeId = 0;
  51170. /**
  51171. * Index of the particle in its shape id (Internal use)
  51172. */
  51173. this.idxInShape = 0;
  51174. /**
  51175. * Still set as invisible in order to skip useless computations (Internal use)
  51176. */
  51177. this._stillInvisible = false;
  51178. /**
  51179. * Last computed particle rotation matrix
  51180. */
  51181. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51182. /**
  51183. * Parent particle Id, if any.
  51184. * Default null.
  51185. */
  51186. this.parentId = null;
  51187. /**
  51188. * Internal global position in the SPS.
  51189. */
  51190. this._globalPosition = BABYLON.Vector3.Zero();
  51191. this.idx = particleIndex;
  51192. this._pos = positionIndex;
  51193. this._ind = indiceIndex;
  51194. this._model = model;
  51195. this.shapeId = shapeId;
  51196. this.idxInShape = idxInShape;
  51197. this._sps = sps;
  51198. if (modelBoundingInfo) {
  51199. this._modelBoundingInfo = modelBoundingInfo;
  51200. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51201. }
  51202. }
  51203. Object.defineProperty(SolidParticle.prototype, "scale", {
  51204. /**
  51205. * Legacy support, changed scale to scaling
  51206. */
  51207. get: function () {
  51208. return this.scaling;
  51209. },
  51210. /**
  51211. * Legacy support, changed scale to scaling
  51212. */
  51213. set: function (scale) {
  51214. this.scaling = scale;
  51215. },
  51216. enumerable: true,
  51217. configurable: true
  51218. });
  51219. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51220. /**
  51221. * Legacy support, changed quaternion to rotationQuaternion
  51222. */
  51223. get: function () {
  51224. return this.rotationQuaternion;
  51225. },
  51226. /**
  51227. * Legacy support, changed quaternion to rotationQuaternion
  51228. */
  51229. set: function (q) {
  51230. this.rotationQuaternion = q;
  51231. },
  51232. enumerable: true,
  51233. configurable: true
  51234. });
  51235. /**
  51236. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51237. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51238. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51239. * @returns true if it intersects
  51240. */
  51241. SolidParticle.prototype.intersectsMesh = function (target) {
  51242. if (!this._boundingInfo || !target._boundingInfo) {
  51243. return false;
  51244. }
  51245. if (this._sps._bSphereOnly) {
  51246. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51247. }
  51248. return this._boundingInfo.intersects(target._boundingInfo, false);
  51249. };
  51250. return SolidParticle;
  51251. }());
  51252. BABYLON.SolidParticle = SolidParticle;
  51253. /**
  51254. * Represents the shape of the model used by one particle of a solid particle system.
  51255. * SPS internal tool, don't use it manually.
  51256. * @see SolidParticleSystem
  51257. */
  51258. var ModelShape = /** @class */ (function () {
  51259. /**
  51260. * 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.
  51261. * SPS internal tool, don't use it manually.
  51262. * @ignore
  51263. */
  51264. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51265. /**
  51266. * length of the shape in the model indices array (internal use)
  51267. */
  51268. this._indicesLength = 0;
  51269. this.shapeID = id;
  51270. this._shape = shape;
  51271. this._indicesLength = indicesLength;
  51272. this._shapeUV = shapeUV;
  51273. this._positionFunction = posFunction;
  51274. this._vertexFunction = vtxFunction;
  51275. }
  51276. return ModelShape;
  51277. }());
  51278. BABYLON.ModelShape = ModelShape;
  51279. /**
  51280. * Represents a Depth Sorted Particle in the solid particle system.
  51281. * @see SolidParticleSystem
  51282. */
  51283. var DepthSortedParticle = /** @class */ (function () {
  51284. function DepthSortedParticle() {
  51285. /**
  51286. * Index of the particle in the "indices" array
  51287. */
  51288. this.ind = 0;
  51289. /**
  51290. * Length of the particle shape in the "indices" array
  51291. */
  51292. this.indicesLength = 0;
  51293. /**
  51294. * Squared distance from the particle to the camera
  51295. */
  51296. this.sqDistance = 0.0;
  51297. }
  51298. return DepthSortedParticle;
  51299. }());
  51300. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51301. })(BABYLON || (BABYLON = {}));
  51302. //# sourceMappingURL=babylon.solidParticle.js.map
  51303. var BABYLON;
  51304. (function (BABYLON) {
  51305. /**
  51306. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51307. *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.
  51308. * The SPS is also a particle system. It provides some methods to manage the particles.
  51309. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51310. *
  51311. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51312. */
  51313. var SolidParticleSystem = /** @class */ (function () {
  51314. /**
  51315. * Creates a SPS (Solid Particle System) object.
  51316. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51317. * @param scene (Scene) is the scene in which the SPS is added.
  51318. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51319. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51320. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51321. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51322. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51323. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51324. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51325. */
  51326. function SolidParticleSystem(name, scene, options) {
  51327. /**
  51328. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51329. * Example : var p = SPS.particles[i];
  51330. */
  51331. this.particles = new Array();
  51332. /**
  51333. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51334. */
  51335. this.nbParticles = 0;
  51336. /**
  51337. * If the particles must ever face the camera (default false). Useful for planar particles.
  51338. */
  51339. this.billboard = false;
  51340. /**
  51341. * Recompute normals when adding a shape
  51342. */
  51343. this.recomputeNormals = true;
  51344. /**
  51345. * This a counter ofr your own usage. It's not set by any SPS functions.
  51346. */
  51347. this.counter = 0;
  51348. /**
  51349. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51350. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51351. */
  51352. this.vars = {};
  51353. /**
  51354. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51355. */
  51356. this._bSphereOnly = false;
  51357. /**
  51358. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51359. */
  51360. this._bSphereRadiusFactor = 1.0;
  51361. this._positions = new Array();
  51362. this._indices = new Array();
  51363. this._normals = new Array();
  51364. this._colors = new Array();
  51365. this._uvs = new Array();
  51366. this._index = 0; // indices index
  51367. this._updatable = true;
  51368. this._pickable = false;
  51369. this._isVisibilityBoxLocked = false;
  51370. this._alwaysVisible = false;
  51371. this._depthSort = false;
  51372. this._shapeCounter = 0;
  51373. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51374. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51375. this._computeParticleColor = true;
  51376. this._computeParticleTexture = true;
  51377. this._computeParticleRotation = true;
  51378. this._computeParticleVertex = false;
  51379. this._computeBoundingBox = false;
  51380. this._depthSortParticles = true;
  51381. this._cam_axisZ = BABYLON.Vector3.Zero();
  51382. this._cam_axisY = BABYLON.Vector3.Zero();
  51383. this._cam_axisX = BABYLON.Vector3.Zero();
  51384. this._axisZ = BABYLON.Axis.Z;
  51385. this._camDir = BABYLON.Vector3.Zero();
  51386. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51387. this._rotMatrix = new BABYLON.Matrix();
  51388. this._invertMatrix = new BABYLON.Matrix();
  51389. this._rotated = BABYLON.Vector3.Zero();
  51390. this._quaternion = new BABYLON.Quaternion();
  51391. this._vertex = BABYLON.Vector3.Zero();
  51392. this._normal = BABYLON.Vector3.Zero();
  51393. this._yaw = 0.0;
  51394. this._pitch = 0.0;
  51395. this._roll = 0.0;
  51396. this._halfroll = 0.0;
  51397. this._halfpitch = 0.0;
  51398. this._halfyaw = 0.0;
  51399. this._sinRoll = 0.0;
  51400. this._cosRoll = 0.0;
  51401. this._sinPitch = 0.0;
  51402. this._cosPitch = 0.0;
  51403. this._sinYaw = 0.0;
  51404. this._cosYaw = 0.0;
  51405. this._mustUnrotateFixedNormals = false;
  51406. this._minimum = BABYLON.Vector3.Zero();
  51407. this._maximum = BABYLON.Vector3.Zero();
  51408. this._minBbox = BABYLON.Vector3.Zero();
  51409. this._maxBbox = BABYLON.Vector3.Zero();
  51410. this._particlesIntersect = false;
  51411. this._depthSortFunction = function (p1, p2) {
  51412. return (p2.sqDistance - p1.sqDistance);
  51413. };
  51414. this._needs32Bits = false;
  51415. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51416. this._scaledPivot = BABYLON.Vector3.Zero();
  51417. this._particleHasParent = false;
  51418. this.name = name;
  51419. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51420. this._camera = scene.activeCamera;
  51421. this._pickable = options ? options.isPickable : false;
  51422. this._depthSort = options ? options.enableDepthSort : false;
  51423. this._particlesIntersect = options ? options.particleIntersection : false;
  51424. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51425. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51426. if (options && options.updatable) {
  51427. this._updatable = options.updatable;
  51428. }
  51429. else {
  51430. this._updatable = true;
  51431. }
  51432. if (this._pickable) {
  51433. this.pickedParticles = [];
  51434. }
  51435. if (this._depthSort) {
  51436. this.depthSortedParticles = [];
  51437. }
  51438. }
  51439. /**
  51440. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51441. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51442. * @returns the created mesh
  51443. */
  51444. SolidParticleSystem.prototype.buildMesh = function () {
  51445. if (this.nbParticles === 0) {
  51446. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51447. this.addShape(triangle, 1);
  51448. triangle.dispose();
  51449. }
  51450. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51451. this._positions32 = new Float32Array(this._positions);
  51452. this._uvs32 = new Float32Array(this._uvs);
  51453. this._colors32 = new Float32Array(this._colors);
  51454. if (this.recomputeNormals) {
  51455. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51456. }
  51457. this._normals32 = new Float32Array(this._normals);
  51458. this._fixedNormal32 = new Float32Array(this._normals);
  51459. if (this._mustUnrotateFixedNormals) {
  51460. this._unrotateFixedNormals();
  51461. }
  51462. var vertexData = new BABYLON.VertexData();
  51463. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51464. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51465. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51466. if (this._uvs32) {
  51467. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51468. ;
  51469. }
  51470. if (this._colors32) {
  51471. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51472. }
  51473. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51474. vertexData.applyToMesh(mesh, this._updatable);
  51475. this.mesh = mesh;
  51476. this.mesh.isPickable = this._pickable;
  51477. // free memory
  51478. if (!this._depthSort) {
  51479. this._indices = null;
  51480. }
  51481. this._positions = null;
  51482. this._normals = null;
  51483. this._uvs = null;
  51484. this._colors = null;
  51485. if (!this._updatable) {
  51486. this.particles.length = 0;
  51487. }
  51488. return mesh;
  51489. };
  51490. /**
  51491. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51492. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51493. * Thus the particles generated from `digest()` have their property `position` set yet.
  51494. * @param mesh ( Mesh ) is the mesh to be digested
  51495. * @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
  51496. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51497. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51498. * @returns the current SPS
  51499. */
  51500. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51501. var size = (options && options.facetNb) || 1;
  51502. var number = (options && options.number) || 0;
  51503. var delta = (options && options.delta) || 0;
  51504. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51505. var meshInd = mesh.getIndices();
  51506. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51507. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51508. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51509. var f = 0; // facet counter
  51510. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51511. // compute size from number
  51512. if (number) {
  51513. number = (number > totalFacets) ? totalFacets : number;
  51514. size = Math.round(totalFacets / number);
  51515. delta = 0;
  51516. }
  51517. else {
  51518. size = (size > totalFacets) ? totalFacets : size;
  51519. }
  51520. var facetPos = []; // submesh positions
  51521. var facetInd = []; // submesh indices
  51522. var facetUV = []; // submesh UV
  51523. var facetCol = []; // submesh colors
  51524. var barycenter = BABYLON.Vector3.Zero();
  51525. var sizeO = size;
  51526. while (f < totalFacets) {
  51527. size = sizeO + Math.floor((1 + delta) * Math.random());
  51528. if (f > totalFacets - size) {
  51529. size = totalFacets - f;
  51530. }
  51531. // reset temp arrays
  51532. facetPos.length = 0;
  51533. facetInd.length = 0;
  51534. facetUV.length = 0;
  51535. facetCol.length = 0;
  51536. // iterate over "size" facets
  51537. var fi = 0;
  51538. for (var j = f * 3; j < (f + size) * 3; j++) {
  51539. facetInd.push(fi);
  51540. var i = meshInd[j];
  51541. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51542. if (meshUV) {
  51543. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51544. }
  51545. if (meshCol) {
  51546. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51547. }
  51548. fi++;
  51549. }
  51550. // create a model shape for each single particle
  51551. var idx = this.nbParticles;
  51552. var shape = this._posToShape(facetPos);
  51553. var shapeUV = this._uvsToShapeUV(facetUV);
  51554. // compute the barycenter of the shape
  51555. var v;
  51556. for (v = 0; v < shape.length; v++) {
  51557. barycenter.addInPlace(shape[v]);
  51558. }
  51559. barycenter.scaleInPlace(1 / shape.length);
  51560. // shift the shape from its barycenter to the origin
  51561. for (v = 0; v < shape.length; v++) {
  51562. shape[v].subtractInPlace(barycenter);
  51563. }
  51564. var bInfo;
  51565. if (this._particlesIntersect) {
  51566. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51567. }
  51568. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51569. // add the particle in the SPS
  51570. var currentPos = this._positions.length;
  51571. var currentInd = this._indices.length;
  51572. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51573. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51574. // initialize the particle position
  51575. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51576. this._index += shape.length;
  51577. idx++;
  51578. this.nbParticles++;
  51579. this._shapeCounter++;
  51580. f += size;
  51581. }
  51582. return this;
  51583. };
  51584. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51585. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51586. var index = 0;
  51587. var idx = 0;
  51588. for (var p = 0; p < this.particles.length; p++) {
  51589. this._particle = this.particles[p];
  51590. this._shape = this._particle._model._shape;
  51591. if (this._particle.rotationQuaternion) {
  51592. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51593. }
  51594. else {
  51595. this._yaw = this._particle.rotation.y;
  51596. this._pitch = this._particle.rotation.x;
  51597. this._roll = this._particle.rotation.z;
  51598. this._quaternionRotationYPR();
  51599. }
  51600. this._quaternionToRotationMatrix();
  51601. this._rotMatrix.invertToRef(this._invertMatrix);
  51602. for (var pt = 0; pt < this._shape.length; pt++) {
  51603. idx = index + pt * 3;
  51604. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51605. this._fixedNormal32[idx] = this._normal.x;
  51606. this._fixedNormal32[idx + 1] = this._normal.y;
  51607. this._fixedNormal32[idx + 2] = this._normal.z;
  51608. }
  51609. index = idx + 3;
  51610. }
  51611. };
  51612. //reset copy
  51613. SolidParticleSystem.prototype._resetCopy = function () {
  51614. this._copy.position.x = 0;
  51615. this._copy.position.y = 0;
  51616. this._copy.position.z = 0;
  51617. this._copy.rotation.x = 0;
  51618. this._copy.rotation.y = 0;
  51619. this._copy.rotation.z = 0;
  51620. this._copy.rotationQuaternion = null;
  51621. this._copy.scaling.x = 1.0;
  51622. this._copy.scaling.y = 1.0;
  51623. this._copy.scaling.z = 1.0;
  51624. this._copy.uvs.x = 0;
  51625. this._copy.uvs.y = 0;
  51626. this._copy.uvs.z = 1.0;
  51627. this._copy.uvs.w = 1.0;
  51628. this._copy.color = null;
  51629. this._copy.translateFromPivot = false;
  51630. };
  51631. // _meshBuilder : inserts the shape model in the global SPS mesh
  51632. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51633. var i;
  51634. var u = 0;
  51635. var c = 0;
  51636. var n = 0;
  51637. this._resetCopy();
  51638. if (options && options.positionFunction) {
  51639. options.positionFunction(this._copy, idx, idxInShape);
  51640. this._mustUnrotateFixedNormals = true;
  51641. }
  51642. if (this._copy.rotationQuaternion) {
  51643. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51644. }
  51645. else {
  51646. this._yaw = this._copy.rotation.y;
  51647. this._pitch = this._copy.rotation.x;
  51648. this._roll = this._copy.rotation.z;
  51649. this._quaternionRotationYPR();
  51650. }
  51651. this._quaternionToRotationMatrix();
  51652. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  51653. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  51654. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  51655. if (this._copy.translateFromPivot) {
  51656. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51657. }
  51658. else {
  51659. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  51660. }
  51661. for (i = 0; i < shape.length; i++) {
  51662. this._vertex.x = shape[i].x;
  51663. this._vertex.y = shape[i].y;
  51664. this._vertex.z = shape[i].z;
  51665. if (options && options.vertexFunction) {
  51666. options.vertexFunction(this._copy, this._vertex, i);
  51667. }
  51668. this._vertex.x *= this._copy.scaling.x;
  51669. this._vertex.y *= this._copy.scaling.y;
  51670. this._vertex.z *= this._copy.scaling.z;
  51671. this._vertex.x -= this._scaledPivot.x;
  51672. this._vertex.y -= this._scaledPivot.y;
  51673. this._vertex.z -= this._scaledPivot.z;
  51674. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51675. this._rotated.addInPlace(this._pivotBackTranslation);
  51676. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51677. if (meshUV) {
  51678. 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);
  51679. u += 2;
  51680. }
  51681. if (this._copy.color) {
  51682. this._color = this._copy.color;
  51683. }
  51684. else if (meshCol && meshCol[c] !== undefined) {
  51685. this._color.r = meshCol[c];
  51686. this._color.g = meshCol[c + 1];
  51687. this._color.b = meshCol[c + 2];
  51688. this._color.a = meshCol[c + 3];
  51689. }
  51690. else {
  51691. this._color.r = 1.0;
  51692. this._color.g = 1.0;
  51693. this._color.b = 1.0;
  51694. this._color.a = 1.0;
  51695. }
  51696. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51697. c += 4;
  51698. if (!this.recomputeNormals && meshNor) {
  51699. this._normal.x = meshNor[n];
  51700. this._normal.y = meshNor[n + 1];
  51701. this._normal.z = meshNor[n + 2];
  51702. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51703. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51704. n += 3;
  51705. }
  51706. }
  51707. for (i = 0; i < meshInd.length; i++) {
  51708. var current_ind = p + meshInd[i];
  51709. indices.push(current_ind);
  51710. if (current_ind > 65535) {
  51711. this._needs32Bits = true;
  51712. }
  51713. }
  51714. if (this._pickable) {
  51715. var nbfaces = meshInd.length / 3;
  51716. for (i = 0; i < nbfaces; i++) {
  51717. this.pickedParticles.push({ idx: idx, faceId: i });
  51718. }
  51719. }
  51720. if (this._depthSort) {
  51721. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51722. }
  51723. return this._copy;
  51724. };
  51725. // returns a shape array from positions array
  51726. SolidParticleSystem.prototype._posToShape = function (positions) {
  51727. var shape = [];
  51728. for (var i = 0; i < positions.length; i += 3) {
  51729. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51730. }
  51731. return shape;
  51732. };
  51733. // returns a shapeUV array from a Vector4 uvs
  51734. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51735. var shapeUV = [];
  51736. if (uvs) {
  51737. for (var i = 0; i < uvs.length; i++)
  51738. shapeUV.push(uvs[i]);
  51739. }
  51740. return shapeUV;
  51741. };
  51742. // adds a new particle object in the particles array
  51743. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51744. if (bInfo === void 0) { bInfo = null; }
  51745. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51746. this.particles.push(sp);
  51747. return sp;
  51748. };
  51749. /**
  51750. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51751. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51752. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51753. * @param nb (positive integer) the number of particles to be created from this model
  51754. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51755. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51756. * @returns the number of shapes in the system
  51757. */
  51758. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51759. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51760. var meshInd = mesh.getIndices();
  51761. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51762. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51763. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51764. var bbInfo;
  51765. if (this._particlesIntersect) {
  51766. bbInfo = mesh.getBoundingInfo();
  51767. }
  51768. var shape = this._posToShape(meshPos);
  51769. var shapeUV = this._uvsToShapeUV(meshUV);
  51770. var posfunc = options ? options.positionFunction : null;
  51771. var vtxfunc = options ? options.vertexFunction : null;
  51772. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51773. // particles
  51774. var sp;
  51775. var currentCopy;
  51776. var idx = this.nbParticles;
  51777. for (var i = 0; i < nb; i++) {
  51778. var currentPos = this._positions.length;
  51779. var currentInd = this._indices.length;
  51780. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51781. if (this._updatable) {
  51782. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51783. sp.position.copyFrom(currentCopy.position);
  51784. sp.rotation.copyFrom(currentCopy.rotation);
  51785. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51786. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51787. }
  51788. if (currentCopy.color && sp.color) {
  51789. sp.color.copyFrom(currentCopy.color);
  51790. }
  51791. sp.scaling.copyFrom(currentCopy.scaling);
  51792. sp.uvs.copyFrom(currentCopy.uvs);
  51793. }
  51794. this._index += shape.length;
  51795. idx++;
  51796. }
  51797. this.nbParticles += nb;
  51798. this._shapeCounter++;
  51799. return this._shapeCounter - 1;
  51800. };
  51801. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51802. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51803. this._resetCopy();
  51804. if (particle._model._positionFunction) {
  51805. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51806. }
  51807. if (this._copy.rotationQuaternion) {
  51808. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51809. }
  51810. else {
  51811. this._yaw = this._copy.rotation.y;
  51812. this._pitch = this._copy.rotation.x;
  51813. this._roll = this._copy.rotation.z;
  51814. this._quaternionRotationYPR();
  51815. }
  51816. this._quaternionToRotationMatrix();
  51817. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  51818. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  51819. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  51820. if (this._copy.translateFromPivot) {
  51821. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51822. }
  51823. else {
  51824. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  51825. }
  51826. this._shape = particle._model._shape;
  51827. for (var pt = 0; pt < this._shape.length; pt++) {
  51828. this._vertex.x = this._shape[pt].x;
  51829. this._vertex.y = this._shape[pt].y;
  51830. this._vertex.z = this._shape[pt].z;
  51831. if (particle._model._vertexFunction) {
  51832. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51833. }
  51834. this._vertex.x *= this._copy.scaling.x;
  51835. this._vertex.y *= this._copy.scaling.y;
  51836. this._vertex.z *= this._copy.scaling.z;
  51837. this._vertex.x -= this._scaledPivot.x;
  51838. this._vertex.y -= this._scaledPivot.y;
  51839. this._vertex.z -= this._scaledPivot.z;
  51840. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51841. this._rotated.addInPlace(this._pivotBackTranslation);
  51842. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51843. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51844. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51845. }
  51846. particle.position.x = 0.0;
  51847. particle.position.y = 0.0;
  51848. particle.position.z = 0.0;
  51849. particle.rotation.x = 0.0;
  51850. particle.rotation.y = 0.0;
  51851. particle.rotation.z = 0.0;
  51852. particle.rotationQuaternion = null;
  51853. particle.scaling.x = 1.0;
  51854. particle.scaling.y = 1.0;
  51855. particle.scaling.z = 1.0;
  51856. particle.uvs.x = 0.0;
  51857. particle.uvs.y = 0.0;
  51858. particle.uvs.z = 1.0;
  51859. particle.uvs.w = 1.0;
  51860. particle.pivot.x = 0.0;
  51861. particle.pivot.y = 0.0;
  51862. particle.pivot.z = 0.0;
  51863. particle.translateFromPivot = false;
  51864. particle.parentId = null;
  51865. };
  51866. /**
  51867. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51868. * @returns the SPS.
  51869. */
  51870. SolidParticleSystem.prototype.rebuildMesh = function () {
  51871. for (var p = 0; p < this.particles.length; p++) {
  51872. this._rebuildParticle(this.particles[p]);
  51873. }
  51874. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51875. return this;
  51876. };
  51877. /**
  51878. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51879. * This method calls `updateParticle()` for each particle of the SPS.
  51880. * For an animated SPS, it is usually called within the render loop.
  51881. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51882. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51883. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51884. * @returns the SPS.
  51885. */
  51886. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51887. if (start === void 0) { start = 0; }
  51888. if (end === void 0) { end = this.nbParticles - 1; }
  51889. if (update === void 0) { update = true; }
  51890. if (!this._updatable) {
  51891. return this;
  51892. }
  51893. // custom beforeUpdate
  51894. this.beforeUpdateParticles(start, end, update);
  51895. this._cam_axisX.x = 1.0;
  51896. this._cam_axisX.y = 0.0;
  51897. this._cam_axisX.z = 0.0;
  51898. this._cam_axisY.x = 0.0;
  51899. this._cam_axisY.y = 1.0;
  51900. this._cam_axisY.z = 0.0;
  51901. this._cam_axisZ.x = 0.0;
  51902. this._cam_axisZ.y = 0.0;
  51903. this._cam_axisZ.z = 1.0;
  51904. // cases when the World Matrix is to be computed first
  51905. if (this.billboard || this._depthSort) {
  51906. this.mesh.computeWorldMatrix(true);
  51907. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51908. }
  51909. // if the particles will always face the camera
  51910. if (this.billboard) {
  51911. // compute the camera position and un-rotate it by the current mesh rotation
  51912. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51913. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51914. this._cam_axisZ.normalize();
  51915. // same for camera up vector extracted from the cam view matrix
  51916. var view = this._camera.getViewMatrix(true);
  51917. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51918. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51919. this._cam_axisY.normalize();
  51920. this._cam_axisX.normalize();
  51921. }
  51922. // if depthSort, compute the camera global position in the mesh local system
  51923. if (this._depthSort) {
  51924. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  51925. }
  51926. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51927. var idx = 0; // current position index in the global array positions32
  51928. var index = 0; // position start index in the global array positions32 of the current particle
  51929. var colidx = 0; // current color index in the global array colors32
  51930. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  51931. var uvidx = 0; // current uv index in the global array uvs32
  51932. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  51933. var pt = 0; // current index in the particle model shape
  51934. if (this.mesh.isFacetDataEnabled) {
  51935. this._computeBoundingBox = true;
  51936. }
  51937. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  51938. if (this._computeBoundingBox) {
  51939. if (start == 0 && end == this.nbParticles - 1) {
  51940. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  51941. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  51942. }
  51943. else {
  51944. if (this.mesh._boundingInfo) {
  51945. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  51946. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  51947. }
  51948. }
  51949. }
  51950. // particle loop
  51951. index = this.particles[start]._pos;
  51952. var vpos = (index / 3) | 0;
  51953. colorIndex = vpos * 4;
  51954. uvIndex = vpos * 2;
  51955. for (var p = start; p <= end; p++) {
  51956. this._particle = this.particles[p];
  51957. this._shape = this._particle._model._shape;
  51958. this._shapeUV = this._particle._model._shapeUV;
  51959. // call to custom user function to update the particle properties
  51960. this.updateParticle(this._particle);
  51961. // camera-particle distance for depth sorting
  51962. if (this._depthSort && this._depthSortParticles) {
  51963. var dsp = this.depthSortedParticles[p];
  51964. dsp.ind = this._particle._ind;
  51965. dsp.indicesLength = this._particle._model._indicesLength;
  51966. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  51967. }
  51968. // skip the computations for inactive or already invisible particles
  51969. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  51970. // increment indexes for the next particle
  51971. pt = this._shape.length;
  51972. index += pt * 3;
  51973. colorIndex += pt * 4;
  51974. uvIndex += pt * 2;
  51975. continue;
  51976. }
  51977. if (this._particle.isVisible) {
  51978. this._particle._stillInvisible = false; // un-mark permanent invisibility
  51979. this._particleHasParent = (this._particle.parentId !== null);
  51980. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  51981. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  51982. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  51983. // particle rotation matrix
  51984. if (this.billboard) {
  51985. this._particle.rotation.x = 0.0;
  51986. this._particle.rotation.y = 0.0;
  51987. }
  51988. if (this._computeParticleRotation || this.billboard) {
  51989. if (this._particle.rotationQuaternion) {
  51990. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51991. }
  51992. else {
  51993. this._yaw = this._particle.rotation.y;
  51994. this._pitch = this._particle.rotation.x;
  51995. this._roll = this._particle.rotation.z;
  51996. this._quaternionRotationYPR();
  51997. }
  51998. this._quaternionToRotationMatrix();
  51999. }
  52000. if (this._particleHasParent) {
  52001. this._parent = this.particles[this._particle.parentId];
  52002. 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];
  52003. 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];
  52004. 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];
  52005. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52006. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52007. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52008. if (this._computeParticleRotation || this.billboard) {
  52009. 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];
  52010. 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];
  52011. 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];
  52012. 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];
  52013. 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];
  52014. 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];
  52015. 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];
  52016. 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];
  52017. 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];
  52018. }
  52019. }
  52020. else {
  52021. this._particle._globalPosition.x = this._particle.position.x;
  52022. this._particle._globalPosition.y = this._particle.position.y;
  52023. this._particle._globalPosition.z = this._particle.position.z;
  52024. if (this._computeParticleRotation || this.billboard) {
  52025. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52026. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52027. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52028. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52029. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52030. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52031. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52032. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52033. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52034. }
  52035. }
  52036. if (this._particle.translateFromPivot) {
  52037. this._pivotBackTranslation.x = 0.0;
  52038. this._pivotBackTranslation.y = 0.0;
  52039. this._pivotBackTranslation.z = 0.0;
  52040. }
  52041. else {
  52042. this._pivotBackTranslation.x = this._scaledPivot.x;
  52043. this._pivotBackTranslation.y = this._scaledPivot.y;
  52044. this._pivotBackTranslation.z = this._scaledPivot.z;
  52045. }
  52046. // particle vertex loop
  52047. for (pt = 0; pt < this._shape.length; pt++) {
  52048. idx = index + pt * 3;
  52049. colidx = colorIndex + pt * 4;
  52050. uvidx = uvIndex + pt * 2;
  52051. this._vertex.x = this._shape[pt].x;
  52052. this._vertex.y = this._shape[pt].y;
  52053. this._vertex.z = this._shape[pt].z;
  52054. if (this._computeParticleVertex) {
  52055. this.updateParticleVertex(this._particle, this._vertex, pt);
  52056. }
  52057. // positions
  52058. this._vertex.x *= this._particle.scaling.x;
  52059. this._vertex.y *= this._particle.scaling.y;
  52060. this._vertex.z *= this._particle.scaling.z;
  52061. this._vertex.x -= this._scaledPivot.x;
  52062. this._vertex.y -= this._scaledPivot.y;
  52063. this._vertex.z -= this._scaledPivot.z;
  52064. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52065. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52066. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52067. this._rotated.x += this._pivotBackTranslation.x;
  52068. this._rotated.y += this._pivotBackTranslation.y;
  52069. this._rotated.z += this._pivotBackTranslation.z;
  52070. 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;
  52071. 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;
  52072. 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;
  52073. if (this._computeBoundingBox) {
  52074. if (this._positions32[idx] < this._minimum.x) {
  52075. this._minimum.x = this._positions32[idx];
  52076. }
  52077. if (this._positions32[idx] > this._maximum.x) {
  52078. this._maximum.x = this._positions32[idx];
  52079. }
  52080. if (this._positions32[idx + 1] < this._minimum.y) {
  52081. this._minimum.y = this._positions32[idx + 1];
  52082. }
  52083. if (this._positions32[idx + 1] > this._maximum.y) {
  52084. this._maximum.y = this._positions32[idx + 1];
  52085. }
  52086. if (this._positions32[idx + 2] < this._minimum.z) {
  52087. this._minimum.z = this._positions32[idx + 2];
  52088. }
  52089. if (this._positions32[idx + 2] > this._maximum.z) {
  52090. this._maximum.z = this._positions32[idx + 2];
  52091. }
  52092. }
  52093. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52094. if (!this._computeParticleVertex) {
  52095. this._normal.x = this._fixedNormal32[idx];
  52096. this._normal.y = this._fixedNormal32[idx + 1];
  52097. this._normal.z = this._fixedNormal32[idx + 2];
  52098. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52099. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52100. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52101. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52102. 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;
  52103. 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;
  52104. }
  52105. if (this._computeParticleColor && this._particle.color) {
  52106. this._colors32[colidx] = this._particle.color.r;
  52107. this._colors32[colidx + 1] = this._particle.color.g;
  52108. this._colors32[colidx + 2] = this._particle.color.b;
  52109. this._colors32[colidx + 3] = this._particle.color.a;
  52110. }
  52111. if (this._computeParticleTexture) {
  52112. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52113. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52114. }
  52115. }
  52116. }
  52117. else {
  52118. this._particle._stillInvisible = true; // mark the particle as invisible
  52119. for (pt = 0; pt < this._shape.length; pt++) {
  52120. idx = index + pt * 3;
  52121. colidx = colorIndex + pt * 4;
  52122. uvidx = uvIndex + pt * 2;
  52123. this._positions32[idx] = 0.0;
  52124. this._positions32[idx + 1] = 0.0;
  52125. this._positions32[idx + 2] = 0.0;
  52126. this._normals32[idx] = 0.0;
  52127. this._normals32[idx + 1] = 0.0;
  52128. this._normals32[idx + 2] = 0.0;
  52129. if (this._computeParticleColor && this._particle.color) {
  52130. this._colors32[colidx] = this._particle.color.r;
  52131. this._colors32[colidx + 1] = this._particle.color.g;
  52132. this._colors32[colidx + 2] = this._particle.color.b;
  52133. this._colors32[colidx + 3] = this._particle.color.a;
  52134. }
  52135. if (this._computeParticleTexture) {
  52136. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52137. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52138. }
  52139. }
  52140. }
  52141. // if the particle intersections must be computed : update the bbInfo
  52142. if (this._particlesIntersect) {
  52143. var bInfo = this._particle._boundingInfo;
  52144. var bBox = bInfo.boundingBox;
  52145. var bSphere = bInfo.boundingSphere;
  52146. if (!this._bSphereOnly) {
  52147. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52148. for (var b = 0; b < bBox.vectors.length; b++) {
  52149. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52150. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52151. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52152. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52153. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52154. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52155. 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;
  52156. 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;
  52157. 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;
  52158. }
  52159. bBox._update(this.mesh._worldMatrix);
  52160. }
  52161. // place and scale the particle bouding sphere in the SPS local system, then update it
  52162. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52163. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52164. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52165. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52166. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52167. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52168. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52169. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52170. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52171. 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));
  52172. bSphere._update(this.mesh._worldMatrix);
  52173. }
  52174. // increment indexes for the next particle
  52175. index = idx + 3;
  52176. colorIndex = colidx + 4;
  52177. uvIndex = uvidx + 2;
  52178. }
  52179. // if the VBO must be updated
  52180. if (update) {
  52181. if (this._computeParticleColor) {
  52182. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52183. }
  52184. if (this._computeParticleTexture) {
  52185. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52186. }
  52187. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52188. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52189. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52190. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52191. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52192. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52193. for (var i = 0; i < this._normals32.length; i++) {
  52194. this._fixedNormal32[i] = this._normals32[i];
  52195. }
  52196. }
  52197. if (!this.mesh.areNormalsFrozen) {
  52198. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52199. }
  52200. }
  52201. if (this._depthSort && this._depthSortParticles) {
  52202. this.depthSortedParticles.sort(this._depthSortFunction);
  52203. var dspl = this.depthSortedParticles.length;
  52204. var sorted = 0;
  52205. var lind = 0;
  52206. var sind = 0;
  52207. var sid = 0;
  52208. for (sorted = 0; sorted < dspl; sorted++) {
  52209. lind = this.depthSortedParticles[sorted].indicesLength;
  52210. sind = this.depthSortedParticles[sorted].ind;
  52211. for (var i = 0; i < lind; i++) {
  52212. this._indices32[sid] = this._indices[sind + i];
  52213. sid++;
  52214. }
  52215. }
  52216. this.mesh.updateIndices(this._indices32);
  52217. }
  52218. }
  52219. if (this._computeBoundingBox) {
  52220. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52221. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52222. }
  52223. this.afterUpdateParticles(start, end, update);
  52224. return this;
  52225. };
  52226. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52227. this._halfroll = this._roll * 0.5;
  52228. this._halfpitch = this._pitch * 0.5;
  52229. this._halfyaw = this._yaw * 0.5;
  52230. this._sinRoll = Math.sin(this._halfroll);
  52231. this._cosRoll = Math.cos(this._halfroll);
  52232. this._sinPitch = Math.sin(this._halfpitch);
  52233. this._cosPitch = Math.cos(this._halfpitch);
  52234. this._sinYaw = Math.sin(this._halfyaw);
  52235. this._cosYaw = Math.cos(this._halfyaw);
  52236. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52237. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52238. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52239. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52240. };
  52241. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52242. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52243. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52244. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52245. this._rotMatrix.m[3] = 0;
  52246. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52247. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52248. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52249. this._rotMatrix.m[7] = 0;
  52250. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52251. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52252. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52253. this._rotMatrix.m[11] = 0;
  52254. this._rotMatrix.m[12] = 0;
  52255. this._rotMatrix.m[13] = 0;
  52256. this._rotMatrix.m[14] = 0;
  52257. this._rotMatrix.m[15] = 1.0;
  52258. };
  52259. /**
  52260. * Disposes the SPS.
  52261. */
  52262. SolidParticleSystem.prototype.dispose = function () {
  52263. this.mesh.dispose();
  52264. this.vars = null;
  52265. // drop references to internal big arrays for the GC
  52266. this._positions = null;
  52267. this._indices = null;
  52268. this._normals = null;
  52269. this._uvs = null;
  52270. this._colors = null;
  52271. this._indices32 = null;
  52272. this._positions32 = null;
  52273. this._normals32 = null;
  52274. this._fixedNormal32 = null;
  52275. this._uvs32 = null;
  52276. this._colors32 = null;
  52277. this.pickedParticles = null;
  52278. };
  52279. /**
  52280. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52281. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52282. * @returns the SPS.
  52283. */
  52284. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52285. if (!this._isVisibilityBoxLocked) {
  52286. this.mesh.refreshBoundingInfo();
  52287. }
  52288. return this;
  52289. };
  52290. /**
  52291. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52292. * @param size the size (float) of the visibility box
  52293. * note : this doesn't lock the SPS mesh bounding box.
  52294. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52295. */
  52296. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52297. var vis = size / 2;
  52298. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52299. };
  52300. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52301. /**
  52302. * Gets whether the SPS as always visible or not
  52303. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52304. */
  52305. get: function () {
  52306. return this._alwaysVisible;
  52307. },
  52308. /**
  52309. * Sets the SPS as always visible or not
  52310. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52311. */
  52312. set: function (val) {
  52313. this._alwaysVisible = val;
  52314. this.mesh.alwaysSelectAsActiveMesh = val;
  52315. },
  52316. enumerable: true,
  52317. configurable: true
  52318. });
  52319. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52320. /**
  52321. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52322. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52323. */
  52324. get: function () {
  52325. return this._isVisibilityBoxLocked;
  52326. },
  52327. /**
  52328. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52329. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52330. */
  52331. set: function (val) {
  52332. this._isVisibilityBoxLocked = val;
  52333. var boundingInfo = this.mesh.getBoundingInfo();
  52334. boundingInfo.isLocked = val;
  52335. },
  52336. enumerable: true,
  52337. configurable: true
  52338. });
  52339. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52340. /**
  52341. * Gets if `setParticles()` computes the particle rotations or not.
  52342. * Default value : true. The SPS is faster when it's set to false.
  52343. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52344. */
  52345. get: function () {
  52346. return this._computeParticleRotation;
  52347. },
  52348. /**
  52349. * Tells to `setParticles()` to compute the particle rotations or not.
  52350. * Default value : true. The SPS is faster when it's set to false.
  52351. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52352. */
  52353. set: function (val) {
  52354. this._computeParticleRotation = val;
  52355. },
  52356. enumerable: true,
  52357. configurable: true
  52358. });
  52359. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52360. /**
  52361. * Gets if `setParticles()` computes the particle colors or not.
  52362. * Default value : true. The SPS is faster when it's set to false.
  52363. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52364. */
  52365. get: function () {
  52366. return this._computeParticleColor;
  52367. },
  52368. /**
  52369. * Tells to `setParticles()` to compute the particle colors or not.
  52370. * Default value : true. The SPS is faster when it's set to false.
  52371. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52372. */
  52373. set: function (val) {
  52374. this._computeParticleColor = val;
  52375. },
  52376. enumerable: true,
  52377. configurable: true
  52378. });
  52379. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52380. /**
  52381. * Gets if `setParticles()` computes the particle textures or not.
  52382. * Default value : true. The SPS is faster when it's set to false.
  52383. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52384. */
  52385. get: function () {
  52386. return this._computeParticleTexture;
  52387. },
  52388. set: function (val) {
  52389. this._computeParticleTexture = val;
  52390. },
  52391. enumerable: true,
  52392. configurable: true
  52393. });
  52394. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52395. /**
  52396. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52397. * Default value : false. The SPS is faster when it's set to false.
  52398. * Note : the particle custom vertex positions aren't stored values.
  52399. */
  52400. get: function () {
  52401. return this._computeParticleVertex;
  52402. },
  52403. /**
  52404. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52405. * Default value : false. The SPS is faster when it's set to false.
  52406. * Note : the particle custom vertex positions aren't stored values.
  52407. */
  52408. set: function (val) {
  52409. this._computeParticleVertex = val;
  52410. },
  52411. enumerable: true,
  52412. configurable: true
  52413. });
  52414. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52415. /**
  52416. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52417. */
  52418. get: function () {
  52419. return this._computeBoundingBox;
  52420. },
  52421. /**
  52422. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52423. */
  52424. set: function (val) {
  52425. this._computeBoundingBox = val;
  52426. },
  52427. enumerable: true,
  52428. configurable: true
  52429. });
  52430. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52431. /**
  52432. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52433. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52434. * Default : `true`
  52435. */
  52436. get: function () {
  52437. return this._depthSortParticles;
  52438. },
  52439. /**
  52440. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52441. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52442. * Default : `true`
  52443. */
  52444. set: function (val) {
  52445. this._depthSortParticles = val;
  52446. },
  52447. enumerable: true,
  52448. configurable: true
  52449. });
  52450. // =======================================================================
  52451. // Particle behavior logic
  52452. // these following methods may be overwritten by the user to fit his needs
  52453. /**
  52454. * This function does nothing. It may be overwritten to set all the particle first values.
  52455. * The SPS doesn't call this function, you may have to call it by your own.
  52456. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52457. */
  52458. SolidParticleSystem.prototype.initParticles = function () {
  52459. };
  52460. /**
  52461. * This function does nothing. It may be overwritten to recycle a particle.
  52462. * The SPS doesn't call this function, you may have to call it by your own.
  52463. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52464. * @param particle The particle to recycle
  52465. * @returns the recycled particle
  52466. */
  52467. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52468. return particle;
  52469. };
  52470. /**
  52471. * Updates a particle : this function should be overwritten by the user.
  52472. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52473. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52474. * @example : just set a particle position or velocity and recycle conditions
  52475. * @param particle The particle to update
  52476. * @returns the updated particle
  52477. */
  52478. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52479. return particle;
  52480. };
  52481. /**
  52482. * Updates a vertex of a particle : it can be overwritten by the user.
  52483. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52484. * @param particle the current particle
  52485. * @param vertex the current index of the current particle
  52486. * @param pt the index of the current vertex in the particle shape
  52487. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52488. * @example : just set a vertex particle position
  52489. * @returns the updated vertex
  52490. */
  52491. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52492. return vertex;
  52493. };
  52494. /**
  52495. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52496. * This does nothing and may be overwritten by the user.
  52497. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52498. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52499. * @param update the boolean update value actually passed to setParticles()
  52500. */
  52501. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52502. };
  52503. /**
  52504. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52505. * This will be passed three parameters.
  52506. * This does nothing and may be overwritten by the user.
  52507. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52508. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52509. * @param update the boolean update value actually passed to setParticles()
  52510. */
  52511. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52512. };
  52513. return SolidParticleSystem;
  52514. }());
  52515. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52516. })(BABYLON || (BABYLON = {}));
  52517. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52518. var BABYLON;
  52519. (function (BABYLON) {
  52520. var ShaderMaterial = /** @class */ (function (_super) {
  52521. __extends(ShaderMaterial, _super);
  52522. function ShaderMaterial(name, scene, shaderPath, options) {
  52523. var _this = _super.call(this, name, scene) || this;
  52524. _this._textures = {};
  52525. _this._textureArrays = {};
  52526. _this._floats = {};
  52527. _this._ints = {};
  52528. _this._floatsArrays = {};
  52529. _this._colors3 = {};
  52530. _this._colors3Arrays = {};
  52531. _this._colors4 = {};
  52532. _this._vectors2 = {};
  52533. _this._vectors3 = {};
  52534. _this._vectors4 = {};
  52535. _this._matrices = {};
  52536. _this._matrices3x3 = {};
  52537. _this._matrices2x2 = {};
  52538. _this._vectors2Arrays = {};
  52539. _this._vectors3Arrays = {};
  52540. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52541. _this._shaderPath = shaderPath;
  52542. options.needAlphaBlending = options.needAlphaBlending || false;
  52543. options.needAlphaTesting = options.needAlphaTesting || false;
  52544. options.attributes = options.attributes || ["position", "normal", "uv"];
  52545. options.uniforms = options.uniforms || ["worldViewProjection"];
  52546. options.uniformBuffers = options.uniformBuffers || [];
  52547. options.samplers = options.samplers || [];
  52548. options.defines = options.defines || [];
  52549. _this._options = options;
  52550. return _this;
  52551. }
  52552. ShaderMaterial.prototype.getClassName = function () {
  52553. return "ShaderMaterial";
  52554. };
  52555. ShaderMaterial.prototype.needAlphaBlending = function () {
  52556. return this._options.needAlphaBlending;
  52557. };
  52558. ShaderMaterial.prototype.needAlphaTesting = function () {
  52559. return this._options.needAlphaTesting;
  52560. };
  52561. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52562. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52563. this._options.uniforms.push(uniformName);
  52564. }
  52565. };
  52566. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52567. if (this._options.samplers.indexOf(name) === -1) {
  52568. this._options.samplers.push(name);
  52569. }
  52570. this._textures[name] = texture;
  52571. return this;
  52572. };
  52573. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52574. if (this._options.samplers.indexOf(name) === -1) {
  52575. this._options.samplers.push(name);
  52576. }
  52577. this._checkUniform(name);
  52578. this._textureArrays[name] = textures;
  52579. return this;
  52580. };
  52581. ShaderMaterial.prototype.setFloat = function (name, value) {
  52582. this._checkUniform(name);
  52583. this._floats[name] = value;
  52584. return this;
  52585. };
  52586. ShaderMaterial.prototype.setInt = function (name, value) {
  52587. this._checkUniform(name);
  52588. this._ints[name] = value;
  52589. return this;
  52590. };
  52591. ShaderMaterial.prototype.setFloats = function (name, value) {
  52592. this._checkUniform(name);
  52593. this._floatsArrays[name] = value;
  52594. return this;
  52595. };
  52596. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52597. this._checkUniform(name);
  52598. this._colors3[name] = value;
  52599. return this;
  52600. };
  52601. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52602. this._checkUniform(name);
  52603. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52604. color.toArray(arr, arr.length);
  52605. return arr;
  52606. }, []);
  52607. return this;
  52608. };
  52609. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52610. this._checkUniform(name);
  52611. this._colors4[name] = value;
  52612. return this;
  52613. };
  52614. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52615. this._checkUniform(name);
  52616. this._vectors2[name] = value;
  52617. return this;
  52618. };
  52619. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52620. this._checkUniform(name);
  52621. this._vectors3[name] = value;
  52622. return this;
  52623. };
  52624. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52625. this._checkUniform(name);
  52626. this._vectors4[name] = value;
  52627. return this;
  52628. };
  52629. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52630. this._checkUniform(name);
  52631. this._matrices[name] = value;
  52632. return this;
  52633. };
  52634. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52635. this._checkUniform(name);
  52636. this._matrices3x3[name] = value;
  52637. return this;
  52638. };
  52639. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52640. this._checkUniform(name);
  52641. this._matrices2x2[name] = value;
  52642. return this;
  52643. };
  52644. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52645. this._checkUniform(name);
  52646. this._vectors2Arrays[name] = value;
  52647. return this;
  52648. };
  52649. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52650. this._checkUniform(name);
  52651. this._vectors3Arrays[name] = value;
  52652. return this;
  52653. };
  52654. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52655. if (!mesh) {
  52656. return true;
  52657. }
  52658. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52659. return false;
  52660. }
  52661. return false;
  52662. };
  52663. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52664. var scene = this.getScene();
  52665. var engine = scene.getEngine();
  52666. if (!this.checkReadyOnEveryCall) {
  52667. if (this._renderId === scene.getRenderId()) {
  52668. if (this._checkCache(scene, mesh, useInstances)) {
  52669. return true;
  52670. }
  52671. }
  52672. }
  52673. // Instances
  52674. var defines = [];
  52675. var attribs = [];
  52676. var fallbacks = new BABYLON.EffectFallbacks();
  52677. if (useInstances) {
  52678. defines.push("#define INSTANCES");
  52679. }
  52680. for (var index = 0; index < this._options.defines.length; index++) {
  52681. defines.push(this._options.defines[index]);
  52682. }
  52683. for (var index = 0; index < this._options.attributes.length; index++) {
  52684. attribs.push(this._options.attributes[index]);
  52685. }
  52686. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52687. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52688. defines.push("#define VERTEXCOLOR");
  52689. }
  52690. // Bones
  52691. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52692. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52693. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52694. if (mesh.numBoneInfluencers > 4) {
  52695. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52696. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52697. }
  52698. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52699. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52700. fallbacks.addCPUSkinningFallback(0, mesh);
  52701. if (this._options.uniforms.indexOf("mBones") === -1) {
  52702. this._options.uniforms.push("mBones");
  52703. }
  52704. }
  52705. else {
  52706. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52707. }
  52708. // Textures
  52709. for (var name in this._textures) {
  52710. if (!this._textures[name].isReady()) {
  52711. return false;
  52712. }
  52713. }
  52714. // Alpha test
  52715. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52716. defines.push("#define ALPHATEST");
  52717. }
  52718. var previousEffect = this._effect;
  52719. var join = defines.join("\n");
  52720. this._effect = engine.createEffect(this._shaderPath, {
  52721. attributes: attribs,
  52722. uniformsNames: this._options.uniforms,
  52723. uniformBuffersNames: this._options.uniformBuffers,
  52724. samplers: this._options.samplers,
  52725. defines: join,
  52726. fallbacks: fallbacks,
  52727. onCompiled: this.onCompiled,
  52728. onError: this.onError
  52729. }, engine);
  52730. if (!this._effect.isReady()) {
  52731. return false;
  52732. }
  52733. if (previousEffect !== this._effect) {
  52734. scene.resetCachedMaterial();
  52735. }
  52736. this._renderId = scene.getRenderId();
  52737. return true;
  52738. };
  52739. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52740. var scene = this.getScene();
  52741. if (!this._effect) {
  52742. return;
  52743. }
  52744. if (this._options.uniforms.indexOf("world") !== -1) {
  52745. this._effect.setMatrix("world", world);
  52746. }
  52747. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52748. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52749. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52750. }
  52751. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52752. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52753. }
  52754. };
  52755. ShaderMaterial.prototype.bind = function (world, mesh) {
  52756. // Std values
  52757. this.bindOnlyWorldMatrix(world);
  52758. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52759. if (this._options.uniforms.indexOf("view") !== -1) {
  52760. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52761. }
  52762. if (this._options.uniforms.indexOf("projection") !== -1) {
  52763. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52764. }
  52765. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52766. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52767. }
  52768. // Bones
  52769. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52770. var name;
  52771. // Texture
  52772. for (name in this._textures) {
  52773. this._effect.setTexture(name, this._textures[name]);
  52774. }
  52775. // Texture arrays
  52776. for (name in this._textureArrays) {
  52777. this._effect.setTextureArray(name, this._textureArrays[name]);
  52778. }
  52779. // Int
  52780. for (name in this._ints) {
  52781. this._effect.setInt(name, this._ints[name]);
  52782. }
  52783. // Float
  52784. for (name in this._floats) {
  52785. this._effect.setFloat(name, this._floats[name]);
  52786. }
  52787. // Floats
  52788. for (name in this._floatsArrays) {
  52789. this._effect.setArray(name, this._floatsArrays[name]);
  52790. }
  52791. // Color3
  52792. for (name in this._colors3) {
  52793. this._effect.setColor3(name, this._colors3[name]);
  52794. }
  52795. for (name in this._colors3Arrays) {
  52796. this._effect.setArray3(name, this._colors3Arrays[name]);
  52797. }
  52798. // Color4
  52799. for (name in this._colors4) {
  52800. var color = this._colors4[name];
  52801. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52802. }
  52803. // Vector2
  52804. for (name in this._vectors2) {
  52805. this._effect.setVector2(name, this._vectors2[name]);
  52806. }
  52807. // Vector3
  52808. for (name in this._vectors3) {
  52809. this._effect.setVector3(name, this._vectors3[name]);
  52810. }
  52811. // Vector4
  52812. for (name in this._vectors4) {
  52813. this._effect.setVector4(name, this._vectors4[name]);
  52814. }
  52815. // Matrix
  52816. for (name in this._matrices) {
  52817. this._effect.setMatrix(name, this._matrices[name]);
  52818. }
  52819. // Matrix 3x3
  52820. for (name in this._matrices3x3) {
  52821. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52822. }
  52823. // Matrix 2x2
  52824. for (name in this._matrices2x2) {
  52825. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52826. }
  52827. // Vector2Array
  52828. for (name in this._vectors2Arrays) {
  52829. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52830. }
  52831. // Vector3Array
  52832. for (name in this._vectors3Arrays) {
  52833. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52834. }
  52835. }
  52836. this._afterBind(mesh);
  52837. };
  52838. ShaderMaterial.prototype.getActiveTextures = function () {
  52839. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52840. for (var name in this._textures) {
  52841. activeTextures.push(this._textures[name]);
  52842. }
  52843. for (var name in this._textureArrays) {
  52844. var array = this._textureArrays[name];
  52845. for (var index = 0; index < array.length; index++) {
  52846. activeTextures.push(array[index]);
  52847. }
  52848. }
  52849. return activeTextures;
  52850. };
  52851. ShaderMaterial.prototype.hasTexture = function (texture) {
  52852. if (_super.prototype.hasTexture.call(this, texture)) {
  52853. return true;
  52854. }
  52855. for (var name in this._textures) {
  52856. if (this._textures[name] === texture) {
  52857. return true;
  52858. }
  52859. }
  52860. for (var name in this._textureArrays) {
  52861. var array = this._textureArrays[name];
  52862. for (var index = 0; index < array.length; index++) {
  52863. if (array[index] === texture) {
  52864. return true;
  52865. }
  52866. }
  52867. }
  52868. return false;
  52869. };
  52870. ShaderMaterial.prototype.clone = function (name) {
  52871. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52872. return newShaderMaterial;
  52873. };
  52874. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52875. if (forceDisposeTextures) {
  52876. var name;
  52877. for (name in this._textures) {
  52878. this._textures[name].dispose();
  52879. }
  52880. for (name in this._textureArrays) {
  52881. var array = this._textureArrays[name];
  52882. for (var index = 0; index < array.length; index++) {
  52883. array[index].dispose();
  52884. }
  52885. }
  52886. }
  52887. this._textures = {};
  52888. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52889. };
  52890. ShaderMaterial.prototype.serialize = function () {
  52891. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52892. serializationObject.customType = "BABYLON.ShaderMaterial";
  52893. serializationObject.options = this._options;
  52894. serializationObject.shaderPath = this._shaderPath;
  52895. var name;
  52896. // Texture
  52897. serializationObject.textures = {};
  52898. for (name in this._textures) {
  52899. serializationObject.textures[name] = this._textures[name].serialize();
  52900. }
  52901. // Texture arrays
  52902. serializationObject.textureArrays = {};
  52903. for (name in this._textureArrays) {
  52904. serializationObject.textureArrays[name] = [];
  52905. var array = this._textureArrays[name];
  52906. for (var index = 0; index < array.length; index++) {
  52907. serializationObject.textureArrays[name].push(array[index].serialize());
  52908. }
  52909. }
  52910. // Float
  52911. serializationObject.floats = {};
  52912. for (name in this._floats) {
  52913. serializationObject.floats[name] = this._floats[name];
  52914. }
  52915. // Float s
  52916. serializationObject.FloatArrays = {};
  52917. for (name in this._floatsArrays) {
  52918. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52919. }
  52920. // Color3
  52921. serializationObject.colors3 = {};
  52922. for (name in this._colors3) {
  52923. serializationObject.colors3[name] = this._colors3[name].asArray();
  52924. }
  52925. // Color3 array
  52926. serializationObject.colors3Arrays = {};
  52927. for (name in this._colors3Arrays) {
  52928. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52929. }
  52930. // Color4
  52931. serializationObject.colors4 = {};
  52932. for (name in this._colors4) {
  52933. serializationObject.colors4[name] = this._colors4[name].asArray();
  52934. }
  52935. // Vector2
  52936. serializationObject.vectors2 = {};
  52937. for (name in this._vectors2) {
  52938. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  52939. }
  52940. // Vector3
  52941. serializationObject.vectors3 = {};
  52942. for (name in this._vectors3) {
  52943. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  52944. }
  52945. // Vector4
  52946. serializationObject.vectors4 = {};
  52947. for (name in this._vectors4) {
  52948. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  52949. }
  52950. // Matrix
  52951. serializationObject.matrices = {};
  52952. for (name in this._matrices) {
  52953. serializationObject.matrices[name] = this._matrices[name].asArray();
  52954. }
  52955. // Matrix 3x3
  52956. serializationObject.matrices3x3 = {};
  52957. for (name in this._matrices3x3) {
  52958. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  52959. }
  52960. // Matrix 2x2
  52961. serializationObject.matrices2x2 = {};
  52962. for (name in this._matrices2x2) {
  52963. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  52964. }
  52965. // Vector2Array
  52966. serializationObject.vectors2Arrays = {};
  52967. for (name in this._vectors2Arrays) {
  52968. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  52969. }
  52970. // Vector3Array
  52971. serializationObject.vectors3Arrays = {};
  52972. for (name in this._vectors3Arrays) {
  52973. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  52974. }
  52975. return serializationObject;
  52976. };
  52977. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  52978. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  52979. var name;
  52980. // Texture
  52981. for (name in source.textures) {
  52982. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  52983. }
  52984. // Texture arrays
  52985. for (name in source.textureArrays) {
  52986. var array = source.textureArrays[name];
  52987. var textureArray = new Array();
  52988. for (var index = 0; index < array.length; index++) {
  52989. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  52990. }
  52991. material.setTextureArray(name, textureArray);
  52992. }
  52993. // Float
  52994. for (name in source.floats) {
  52995. material.setFloat(name, source.floats[name]);
  52996. }
  52997. // Float s
  52998. for (name in source.floatsArrays) {
  52999. material.setFloats(name, source.floatsArrays[name]);
  53000. }
  53001. // Color3
  53002. for (name in source.colors3) {
  53003. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53004. }
  53005. // Color3 arrays
  53006. for (name in source.colors3Arrays) {
  53007. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53008. if (i % 3 === 0) {
  53009. arr.push([num]);
  53010. }
  53011. else {
  53012. arr[arr.length - 1].push(num);
  53013. }
  53014. return arr;
  53015. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53016. material.setColor3Array(name, colors);
  53017. }
  53018. // Color4
  53019. for (name in source.colors4) {
  53020. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53021. }
  53022. // Vector2
  53023. for (name in source.vectors2) {
  53024. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53025. }
  53026. // Vector3
  53027. for (name in source.vectors3) {
  53028. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53029. }
  53030. // Vector4
  53031. for (name in source.vectors4) {
  53032. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53033. }
  53034. // Matrix
  53035. for (name in source.matrices) {
  53036. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53037. }
  53038. // Matrix 3x3
  53039. for (name in source.matrices3x3) {
  53040. material.setMatrix3x3(name, source.matrices3x3[name]);
  53041. }
  53042. // Matrix 2x2
  53043. for (name in source.matrices2x2) {
  53044. material.setMatrix2x2(name, source.matrices2x2[name]);
  53045. }
  53046. // Vector2Array
  53047. for (name in source.vectors2Arrays) {
  53048. material.setArray2(name, source.vectors2Arrays[name]);
  53049. }
  53050. // Vector3Array
  53051. for (name in source.vectors3Arrays) {
  53052. material.setArray3(name, source.vectors3Arrays[name]);
  53053. }
  53054. return material;
  53055. };
  53056. return ShaderMaterial;
  53057. }(BABYLON.Material));
  53058. BABYLON.ShaderMaterial = ShaderMaterial;
  53059. })(BABYLON || (BABYLON = {}));
  53060. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53061. var BABYLON;
  53062. (function (BABYLON) {
  53063. var GroundMesh = /** @class */ (function (_super) {
  53064. __extends(GroundMesh, _super);
  53065. function GroundMesh(name, scene) {
  53066. var _this = _super.call(this, name, scene) || this;
  53067. _this.generateOctree = false;
  53068. return _this;
  53069. }
  53070. GroundMesh.prototype.getClassName = function () {
  53071. return "GroundMesh";
  53072. };
  53073. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53074. get: function () {
  53075. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53076. },
  53077. enumerable: true,
  53078. configurable: true
  53079. });
  53080. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53081. get: function () {
  53082. return this._subdivisionsX;
  53083. },
  53084. enumerable: true,
  53085. configurable: true
  53086. });
  53087. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53088. get: function () {
  53089. return this._subdivisionsY;
  53090. },
  53091. enumerable: true,
  53092. configurable: true
  53093. });
  53094. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53095. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53096. this._subdivisionsX = chunksCount;
  53097. this._subdivisionsY = chunksCount;
  53098. this.subdivide(chunksCount);
  53099. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53100. };
  53101. /**
  53102. * Returns a height (y) value in the Worl system :
  53103. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53104. * Returns the ground y position if (x, z) are outside the ground surface.
  53105. */
  53106. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53107. var world = this.getWorldMatrix();
  53108. var invMat = BABYLON.Tmp.Matrix[5];
  53109. world.invertToRef(invMat);
  53110. var tmpVect = BABYLON.Tmp.Vector3[8];
  53111. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53112. x = tmpVect.x;
  53113. z = tmpVect.z;
  53114. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53115. return this.position.y;
  53116. }
  53117. if (!this._heightQuads || this._heightQuads.length == 0) {
  53118. this._initHeightQuads();
  53119. this._computeHeightQuads();
  53120. }
  53121. var facet = this._getFacetAt(x, z);
  53122. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53123. // return y in the World system
  53124. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53125. return tmpVect.y;
  53126. };
  53127. /**
  53128. * Returns a normalized vector (Vector3) orthogonal to the ground
  53129. * at the ground coordinates (x, z) expressed in the World system.
  53130. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53131. */
  53132. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53133. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53134. this.getNormalAtCoordinatesToRef(x, z, normal);
  53135. return normal;
  53136. };
  53137. /**
  53138. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53139. * at the ground coordinates (x, z) expressed in the World system.
  53140. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53141. * Returns the GroundMesh.
  53142. */
  53143. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53144. var world = this.getWorldMatrix();
  53145. var tmpMat = BABYLON.Tmp.Matrix[5];
  53146. world.invertToRef(tmpMat);
  53147. var tmpVect = BABYLON.Tmp.Vector3[8];
  53148. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53149. x = tmpVect.x;
  53150. z = tmpVect.z;
  53151. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53152. return this;
  53153. }
  53154. if (!this._heightQuads || this._heightQuads.length == 0) {
  53155. this._initHeightQuads();
  53156. this._computeHeightQuads();
  53157. }
  53158. var facet = this._getFacetAt(x, z);
  53159. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53160. return this;
  53161. };
  53162. /**
  53163. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53164. * if the ground has been updated.
  53165. * This can be used in the render loop.
  53166. * Returns the GroundMesh.
  53167. */
  53168. GroundMesh.prototype.updateCoordinateHeights = function () {
  53169. if (!this._heightQuads || this._heightQuads.length == 0) {
  53170. this._initHeightQuads();
  53171. }
  53172. this._computeHeightQuads();
  53173. return this;
  53174. };
  53175. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53176. GroundMesh.prototype._getFacetAt = function (x, z) {
  53177. // retrieve col and row from x, z coordinates in the ground local system
  53178. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53179. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53180. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53181. var facet;
  53182. if (z < quad.slope.x * x + quad.slope.y) {
  53183. facet = quad.facet1;
  53184. }
  53185. else {
  53186. facet = quad.facet2;
  53187. }
  53188. return facet;
  53189. };
  53190. // Creates and populates the heightMap array with "facet" elements :
  53191. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53192. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53193. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53194. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53195. // Returns the GroundMesh.
  53196. GroundMesh.prototype._initHeightQuads = function () {
  53197. var subdivisionsX = this._subdivisionsX;
  53198. var subdivisionsY = this._subdivisionsY;
  53199. this._heightQuads = new Array();
  53200. for (var row = 0; row < subdivisionsY; row++) {
  53201. for (var col = 0; col < subdivisionsX; col++) {
  53202. 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) };
  53203. this._heightQuads[row * subdivisionsX + col] = quad;
  53204. }
  53205. }
  53206. return this;
  53207. };
  53208. // Compute each quad element values and update the the heightMap array :
  53209. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53210. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53211. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53212. // Returns the GroundMesh.
  53213. GroundMesh.prototype._computeHeightQuads = function () {
  53214. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53215. if (!positions) {
  53216. return this;
  53217. }
  53218. var v1 = BABYLON.Tmp.Vector3[3];
  53219. var v2 = BABYLON.Tmp.Vector3[2];
  53220. var v3 = BABYLON.Tmp.Vector3[1];
  53221. var v4 = BABYLON.Tmp.Vector3[0];
  53222. var v1v2 = BABYLON.Tmp.Vector3[4];
  53223. var v1v3 = BABYLON.Tmp.Vector3[5];
  53224. var v1v4 = BABYLON.Tmp.Vector3[6];
  53225. var norm1 = BABYLON.Tmp.Vector3[7];
  53226. var norm2 = BABYLON.Tmp.Vector3[8];
  53227. var i = 0;
  53228. var j = 0;
  53229. var k = 0;
  53230. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53231. var h = 0;
  53232. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53233. var d2 = 0;
  53234. var subdivisionsX = this._subdivisionsX;
  53235. var subdivisionsY = this._subdivisionsY;
  53236. for (var row = 0; row < subdivisionsY; row++) {
  53237. for (var col = 0; col < subdivisionsX; col++) {
  53238. i = col * 3;
  53239. j = row * (subdivisionsX + 1) * 3;
  53240. k = (row + 1) * (subdivisionsX + 1) * 3;
  53241. v1.x = positions[j + i];
  53242. v1.y = positions[j + i + 1];
  53243. v1.z = positions[j + i + 2];
  53244. v2.x = positions[j + i + 3];
  53245. v2.y = positions[j + i + 4];
  53246. v2.z = positions[j + i + 5];
  53247. v3.x = positions[k + i];
  53248. v3.y = positions[k + i + 1];
  53249. v3.z = positions[k + i + 2];
  53250. v4.x = positions[k + i + 3];
  53251. v4.y = positions[k + i + 4];
  53252. v4.z = positions[k + i + 5];
  53253. // 2D slope V1V4
  53254. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53255. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53256. // facet equations :
  53257. // we compute each facet normal vector
  53258. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53259. // we compute the value d by applying the equation to v1 which belongs to the plane
  53260. // then we store the facet equation in a Vector4
  53261. v2.subtractToRef(v1, v1v2);
  53262. v3.subtractToRef(v1, v1v3);
  53263. v4.subtractToRef(v1, v1v4);
  53264. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53265. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53266. norm1.normalize();
  53267. norm2.normalize();
  53268. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53269. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53270. var quad = this._heightQuads[row * subdivisionsX + col];
  53271. quad.slope.copyFromFloats(cd, h);
  53272. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53273. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53274. }
  53275. }
  53276. return this;
  53277. };
  53278. GroundMesh.prototype.serialize = function (serializationObject) {
  53279. _super.prototype.serialize.call(this, serializationObject);
  53280. serializationObject.subdivisionsX = this._subdivisionsX;
  53281. serializationObject.subdivisionsY = this._subdivisionsY;
  53282. serializationObject.minX = this._minX;
  53283. serializationObject.maxX = this._maxX;
  53284. serializationObject.minZ = this._minZ;
  53285. serializationObject.maxZ = this._maxZ;
  53286. serializationObject.width = this._width;
  53287. serializationObject.height = this._height;
  53288. };
  53289. GroundMesh.Parse = function (parsedMesh, scene) {
  53290. var result = new GroundMesh(parsedMesh.name, scene);
  53291. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53292. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53293. result._minX = parsedMesh.minX;
  53294. result._maxX = parsedMesh.maxX;
  53295. result._minZ = parsedMesh.minZ;
  53296. result._maxZ = parsedMesh.maxZ;
  53297. result._width = parsedMesh.width;
  53298. result._height = parsedMesh.height;
  53299. return result;
  53300. };
  53301. return GroundMesh;
  53302. }(BABYLON.Mesh));
  53303. BABYLON.GroundMesh = GroundMesh;
  53304. })(BABYLON || (BABYLON = {}));
  53305. //# sourceMappingURL=babylon.groundMesh.js.map
  53306. var BABYLON;
  53307. (function (BABYLON) {
  53308. /**
  53309. * Creates an instance based on a source mesh.
  53310. */
  53311. var InstancedMesh = /** @class */ (function (_super) {
  53312. __extends(InstancedMesh, _super);
  53313. function InstancedMesh(name, source) {
  53314. var _this = _super.call(this, name, source.getScene()) || this;
  53315. source.instances.push(_this);
  53316. _this._sourceMesh = source;
  53317. _this.position.copyFrom(source.position);
  53318. _this.rotation.copyFrom(source.rotation);
  53319. _this.scaling.copyFrom(source.scaling);
  53320. if (source.rotationQuaternion) {
  53321. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53322. }
  53323. _this.infiniteDistance = source.infiniteDistance;
  53324. _this.setPivotMatrix(source.getPivotMatrix());
  53325. _this.refreshBoundingInfo();
  53326. _this._syncSubMeshes();
  53327. return _this;
  53328. }
  53329. /**
  53330. * Returns the string "InstancedMesh".
  53331. */
  53332. InstancedMesh.prototype.getClassName = function () {
  53333. return "InstancedMesh";
  53334. };
  53335. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53336. // Methods
  53337. get: function () {
  53338. return this._sourceMesh.receiveShadows;
  53339. },
  53340. enumerable: true,
  53341. configurable: true
  53342. });
  53343. Object.defineProperty(InstancedMesh.prototype, "material", {
  53344. get: function () {
  53345. return this._sourceMesh.material;
  53346. },
  53347. enumerable: true,
  53348. configurable: true
  53349. });
  53350. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53351. get: function () {
  53352. return this._sourceMesh.visibility;
  53353. },
  53354. enumerable: true,
  53355. configurable: true
  53356. });
  53357. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53358. get: function () {
  53359. return this._sourceMesh.skeleton;
  53360. },
  53361. enumerable: true,
  53362. configurable: true
  53363. });
  53364. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53365. get: function () {
  53366. return this._sourceMesh.renderingGroupId;
  53367. },
  53368. enumerable: true,
  53369. configurable: true
  53370. });
  53371. /**
  53372. * Returns the total number of vertices (integer).
  53373. */
  53374. InstancedMesh.prototype.getTotalVertices = function () {
  53375. return this._sourceMesh.getTotalVertices();
  53376. };
  53377. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53378. get: function () {
  53379. return this._sourceMesh;
  53380. },
  53381. enumerable: true,
  53382. configurable: true
  53383. });
  53384. /**
  53385. * Is this node ready to be used/rendered
  53386. * @return {boolean} is it ready
  53387. */
  53388. InstancedMesh.prototype.isReady = function () {
  53389. return this._sourceMesh.isReady(true);
  53390. };
  53391. /**
  53392. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53393. */
  53394. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53395. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53396. };
  53397. /**
  53398. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53399. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53400. * The `data` are either a numeric array either a Float32Array.
  53401. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53402. * 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).
  53403. * Note that a new underlying VertexBuffer object is created each call.
  53404. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53405. *
  53406. * Possible `kind` values :
  53407. * - BABYLON.VertexBuffer.PositionKind
  53408. * - BABYLON.VertexBuffer.UVKind
  53409. * - BABYLON.VertexBuffer.UV2Kind
  53410. * - BABYLON.VertexBuffer.UV3Kind
  53411. * - BABYLON.VertexBuffer.UV4Kind
  53412. * - BABYLON.VertexBuffer.UV5Kind
  53413. * - BABYLON.VertexBuffer.UV6Kind
  53414. * - BABYLON.VertexBuffer.ColorKind
  53415. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53416. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53417. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53418. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53419. *
  53420. * Returns the Mesh.
  53421. */
  53422. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53423. if (this.sourceMesh) {
  53424. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53425. }
  53426. return this.sourceMesh;
  53427. };
  53428. /**
  53429. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53430. * If the mesh has no geometry, it is simply returned as it is.
  53431. * The `data` are either a numeric array either a Float32Array.
  53432. * No new underlying VertexBuffer object is created.
  53433. * 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.
  53434. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53435. *
  53436. * Possible `kind` values :
  53437. * - BABYLON.VertexBuffer.PositionKind
  53438. * - BABYLON.VertexBuffer.UVKind
  53439. * - BABYLON.VertexBuffer.UV2Kind
  53440. * - BABYLON.VertexBuffer.UV3Kind
  53441. * - BABYLON.VertexBuffer.UV4Kind
  53442. * - BABYLON.VertexBuffer.UV5Kind
  53443. * - BABYLON.VertexBuffer.UV6Kind
  53444. * - BABYLON.VertexBuffer.ColorKind
  53445. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53446. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53447. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53448. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53449. *
  53450. * Returns the Mesh.
  53451. */
  53452. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53453. if (this.sourceMesh) {
  53454. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53455. }
  53456. return this.sourceMesh;
  53457. };
  53458. /**
  53459. * Sets the mesh indices.
  53460. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53461. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53462. * This method creates a new index buffer each call.
  53463. * Returns the Mesh.
  53464. */
  53465. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53466. if (totalVertices === void 0) { totalVertices = null; }
  53467. if (this.sourceMesh) {
  53468. this.sourceMesh.setIndices(indices, totalVertices);
  53469. }
  53470. return this.sourceMesh;
  53471. };
  53472. /**
  53473. * Boolean : True if the mesh owns the requested kind of data.
  53474. */
  53475. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53476. return this._sourceMesh.isVerticesDataPresent(kind);
  53477. };
  53478. /**
  53479. * Returns an array of indices (IndicesArray).
  53480. */
  53481. InstancedMesh.prototype.getIndices = function () {
  53482. return this._sourceMesh.getIndices();
  53483. };
  53484. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53485. get: function () {
  53486. return this._sourceMesh._positions;
  53487. },
  53488. enumerable: true,
  53489. configurable: true
  53490. });
  53491. /**
  53492. * Sets a new updated BoundingInfo to the mesh.
  53493. * Returns the mesh.
  53494. */
  53495. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53496. var meshBB = this._sourceMesh.getBoundingInfo();
  53497. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53498. this._updateBoundingInfo();
  53499. return this;
  53500. };
  53501. InstancedMesh.prototype._preActivate = function () {
  53502. if (this._currentLOD) {
  53503. this._currentLOD._preActivate();
  53504. }
  53505. return this;
  53506. };
  53507. InstancedMesh.prototype._activate = function (renderId) {
  53508. if (this._currentLOD) {
  53509. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53510. }
  53511. return this;
  53512. };
  53513. /**
  53514. * Returns the current associated LOD AbstractMesh.
  53515. */
  53516. InstancedMesh.prototype.getLOD = function (camera) {
  53517. if (!camera) {
  53518. return this;
  53519. }
  53520. var boundingInfo = this.getBoundingInfo();
  53521. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53522. if (this._currentLOD === this.sourceMesh) {
  53523. return this;
  53524. }
  53525. return this._currentLOD;
  53526. };
  53527. InstancedMesh.prototype._syncSubMeshes = function () {
  53528. this.releaseSubMeshes();
  53529. if (this._sourceMesh.subMeshes) {
  53530. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53531. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53532. }
  53533. }
  53534. return this;
  53535. };
  53536. InstancedMesh.prototype._generatePointsArray = function () {
  53537. return this._sourceMesh._generatePointsArray();
  53538. };
  53539. /**
  53540. * Creates a new InstancedMesh from the current mesh.
  53541. * - name (string) : the cloned mesh name
  53542. * - newParent (optional Node) : the optional Node to parent the clone to.
  53543. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53544. *
  53545. * Returns the clone.
  53546. */
  53547. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53548. var result = this._sourceMesh.createInstance(name);
  53549. // Deep copy
  53550. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53551. // Bounding info
  53552. this.refreshBoundingInfo();
  53553. // Parent
  53554. if (newParent) {
  53555. result.parent = newParent;
  53556. }
  53557. if (!doNotCloneChildren) {
  53558. // Children
  53559. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53560. var mesh = this.getScene().meshes[index];
  53561. if (mesh.parent === this) {
  53562. mesh.clone(mesh.name, result);
  53563. }
  53564. }
  53565. }
  53566. result.computeWorldMatrix(true);
  53567. return result;
  53568. };
  53569. /**
  53570. * Disposes the InstancedMesh.
  53571. * Returns nothing.
  53572. */
  53573. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53574. // Remove from mesh
  53575. var index = this._sourceMesh.instances.indexOf(this);
  53576. this._sourceMesh.instances.splice(index, 1);
  53577. _super.prototype.dispose.call(this, doNotRecurse);
  53578. };
  53579. return InstancedMesh;
  53580. }(BABYLON.AbstractMesh));
  53581. BABYLON.InstancedMesh = InstancedMesh;
  53582. })(BABYLON || (BABYLON = {}));
  53583. //# sourceMappingURL=babylon.instancedMesh.js.map
  53584. var BABYLON;
  53585. (function (BABYLON) {
  53586. var LinesMesh = /** @class */ (function (_super) {
  53587. __extends(LinesMesh, _super);
  53588. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53589. if (scene === void 0) { scene = null; }
  53590. if (parent === void 0) { parent = null; }
  53591. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53592. _this.useVertexColor = useVertexColor;
  53593. _this.useVertexAlpha = useVertexAlpha;
  53594. _this.color = new BABYLON.Color3(1, 1, 1);
  53595. _this.alpha = 1;
  53596. if (source) {
  53597. _this.color = source.color.clone();
  53598. _this.alpha = source.alpha;
  53599. _this.useVertexColor = source.useVertexColor;
  53600. _this.useVertexAlpha = source.useVertexAlpha;
  53601. }
  53602. _this._intersectionThreshold = 0.1;
  53603. var defines = [];
  53604. var options = {
  53605. attributes: [BABYLON.VertexBuffer.PositionKind],
  53606. uniforms: ["world", "viewProjection"],
  53607. needAlphaBlending: true,
  53608. defines: defines
  53609. };
  53610. if (useVertexAlpha === false) {
  53611. options.needAlphaBlending = false;
  53612. }
  53613. if (!useVertexColor) {
  53614. options.uniforms.push("color");
  53615. }
  53616. else {
  53617. options.defines.push("#define VERTEXCOLOR");
  53618. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53619. }
  53620. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53621. return _this;
  53622. }
  53623. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53624. /**
  53625. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53626. * This margin is expressed in world space coordinates, so its value may vary.
  53627. * Default value is 0.1
  53628. * @returns the intersection Threshold value.
  53629. */
  53630. get: function () {
  53631. return this._intersectionThreshold;
  53632. },
  53633. /**
  53634. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53635. * This margin is expressed in world space coordinates, so its value may vary.
  53636. * @param value the new threshold to apply
  53637. */
  53638. set: function (value) {
  53639. if (this._intersectionThreshold === value) {
  53640. return;
  53641. }
  53642. this._intersectionThreshold = value;
  53643. if (this.geometry) {
  53644. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53645. }
  53646. },
  53647. enumerable: true,
  53648. configurable: true
  53649. });
  53650. /**
  53651. * Returns the string "LineMesh"
  53652. */
  53653. LinesMesh.prototype.getClassName = function () {
  53654. return "LinesMesh";
  53655. };
  53656. Object.defineProperty(LinesMesh.prototype, "material", {
  53657. get: function () {
  53658. return this._colorShader;
  53659. },
  53660. set: function (value) {
  53661. // Do nothing
  53662. },
  53663. enumerable: true,
  53664. configurable: true
  53665. });
  53666. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53667. get: function () {
  53668. return false;
  53669. },
  53670. enumerable: true,
  53671. configurable: true
  53672. });
  53673. LinesMesh.prototype.createInstance = function (name) {
  53674. throw new Error("LinesMeshes do not support createInstance.");
  53675. };
  53676. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53677. if (!this._geometry) {
  53678. return this;
  53679. }
  53680. // VBOs
  53681. this._geometry._bind(this._colorShader.getEffect());
  53682. // Color
  53683. if (!this.useVertexColor) {
  53684. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53685. }
  53686. return this;
  53687. };
  53688. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53689. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53690. return this;
  53691. }
  53692. var engine = this.getScene().getEngine();
  53693. // Draw order
  53694. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53695. return this;
  53696. };
  53697. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53698. this._colorShader.dispose();
  53699. _super.prototype.dispose.call(this, doNotRecurse);
  53700. };
  53701. /**
  53702. * Returns a new LineMesh object cloned from the current one.
  53703. */
  53704. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53705. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53706. };
  53707. return LinesMesh;
  53708. }(BABYLON.Mesh));
  53709. BABYLON.LinesMesh = LinesMesh;
  53710. })(BABYLON || (BABYLON = {}));
  53711. //# sourceMappingURL=babylon.linesMesh.js.map
  53712. var BABYLON;
  53713. (function (BABYLON) {
  53714. var MeshBuilder = /** @class */ (function () {
  53715. function MeshBuilder() {
  53716. }
  53717. MeshBuilder.updateSideOrientation = function (orientation) {
  53718. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53719. return BABYLON.Mesh.DOUBLESIDE;
  53720. }
  53721. if (orientation === undefined || orientation === null) {
  53722. return BABYLON.Mesh.FRONTSIDE;
  53723. }
  53724. return orientation;
  53725. };
  53726. /**
  53727. * Creates a box mesh.
  53728. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53729. * The parameter `size` sets the size (float) of each box side (default 1).
  53730. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53731. * 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).
  53732. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53733. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53734. * 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).
  53735. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53737. */
  53738. MeshBuilder.CreateBox = function (name, options, scene) {
  53739. if (scene === void 0) { scene = null; }
  53740. var box = new BABYLON.Mesh(name, scene);
  53741. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53742. box._originalBuilderSideOrientation = options.sideOrientation;
  53743. var vertexData = BABYLON.VertexData.CreateBox(options);
  53744. vertexData.applyToMesh(box, options.updatable);
  53745. return box;
  53746. };
  53747. /**
  53748. * Creates a sphere mesh.
  53749. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53750. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53751. * 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`).
  53752. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53753. * 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
  53754. * 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).
  53755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53756. * 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).
  53757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53759. */
  53760. MeshBuilder.CreateSphere = function (name, options, scene) {
  53761. var sphere = new BABYLON.Mesh(name, scene);
  53762. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53763. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53764. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53765. vertexData.applyToMesh(sphere, options.updatable);
  53766. return sphere;
  53767. };
  53768. /**
  53769. * Creates a plane polygonal mesh. By default, this is a disc.
  53770. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53771. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53772. * 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.
  53773. * 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
  53774. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53775. * 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).
  53776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53778. */
  53779. MeshBuilder.CreateDisc = function (name, options, scene) {
  53780. if (scene === void 0) { scene = null; }
  53781. var disc = new BABYLON.Mesh(name, scene);
  53782. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53783. disc._originalBuilderSideOrientation = options.sideOrientation;
  53784. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53785. vertexData.applyToMesh(disc, options.updatable);
  53786. return disc;
  53787. };
  53788. /**
  53789. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53790. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53791. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53792. * 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`).
  53793. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53794. * 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.
  53795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53796. * 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).
  53797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53799. */
  53800. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53801. var sphere = new BABYLON.Mesh(name, scene);
  53802. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53803. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53804. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53805. vertexData.applyToMesh(sphere, options.updatable);
  53806. return sphere;
  53807. };
  53808. ;
  53809. /**
  53810. * Creates a ribbon mesh.
  53811. * 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.
  53812. *
  53813. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53814. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53815. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53816. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53817. * 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.
  53818. * 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.
  53819. * 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
  53820. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53821. * 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).
  53822. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53823. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53824. * 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.
  53825. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53826. * 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
  53827. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53828. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53830. */
  53831. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53832. if (scene === void 0) { scene = null; }
  53833. var pathArray = options.pathArray;
  53834. var closeArray = options.closeArray;
  53835. var closePath = options.closePath;
  53836. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53837. var instance = options.instance;
  53838. var updatable = options.updatable;
  53839. if (instance) {
  53840. // positionFunction : ribbon case
  53841. // only pathArray and sideOrientation parameters are taken into account for positions update
  53842. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53843. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53844. var positionFunction = function (positions) {
  53845. var minlg = pathArray[0].length;
  53846. var i = 0;
  53847. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53848. for (var si = 1; si <= ns; si++) {
  53849. for (var p = 0; p < pathArray.length; p++) {
  53850. var path = pathArray[p];
  53851. var l = path.length;
  53852. minlg = (minlg < l) ? minlg : l;
  53853. var j = 0;
  53854. while (j < minlg) {
  53855. positions[i] = path[j].x;
  53856. positions[i + 1] = path[j].y;
  53857. positions[i + 2] = path[j].z;
  53858. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53859. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53860. }
  53861. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53862. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53863. }
  53864. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53865. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53866. }
  53867. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53868. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53869. }
  53870. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53871. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53872. }
  53873. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53874. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53875. }
  53876. j++;
  53877. i += 3;
  53878. }
  53879. if (instance._closePath) {
  53880. positions[i] = path[0].x;
  53881. positions[i + 1] = path[0].y;
  53882. positions[i + 2] = path[0].z;
  53883. i += 3;
  53884. }
  53885. }
  53886. }
  53887. };
  53888. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53889. positionFunction(positions);
  53890. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53891. instance._boundingInfo.update(instance._worldMatrix);
  53892. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53893. if (options.colors) {
  53894. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53895. for (var c = 0; c < options.colors.length; c++) {
  53896. colors[c * 4] = options.colors[c].r;
  53897. colors[c * 4 + 1] = options.colors[c].g;
  53898. colors[c * 4 + 2] = options.colors[c].b;
  53899. colors[c * 4 + 3] = options.colors[c].a;
  53900. }
  53901. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53902. }
  53903. if (options.uvs) {
  53904. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53905. for (var i = 0; i < options.uvs.length; i++) {
  53906. uvs[i * 2] = options.uvs[i].x;
  53907. uvs[i * 2 + 1] = options.uvs[i].y;
  53908. }
  53909. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53910. }
  53911. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53912. var indices = instance.getIndices();
  53913. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53914. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53915. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53916. if (instance._closePath) {
  53917. var indexFirst = 0;
  53918. var indexLast = 0;
  53919. for (var p = 0; p < pathArray.length; p++) {
  53920. indexFirst = instance._idx[p] * 3;
  53921. if (p + 1 < pathArray.length) {
  53922. indexLast = (instance._idx[p + 1] - 1) * 3;
  53923. }
  53924. else {
  53925. indexLast = normals.length - 3;
  53926. }
  53927. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53928. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53929. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53930. normals[indexLast] = normals[indexFirst];
  53931. normals[indexLast + 1] = normals[indexFirst + 1];
  53932. normals[indexLast + 2] = normals[indexFirst + 2];
  53933. }
  53934. }
  53935. if (!(instance.areNormalsFrozen)) {
  53936. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  53937. }
  53938. }
  53939. return instance;
  53940. }
  53941. else {
  53942. var ribbon = new BABYLON.Mesh(name, scene);
  53943. ribbon._originalBuilderSideOrientation = sideOrientation;
  53944. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  53945. if (closePath) {
  53946. ribbon._idx = vertexData._idx;
  53947. }
  53948. ribbon._closePath = closePath;
  53949. ribbon._closeArray = closeArray;
  53950. vertexData.applyToMesh(ribbon, updatable);
  53951. return ribbon;
  53952. }
  53953. };
  53954. /**
  53955. * Creates a cylinder or a cone mesh.
  53956. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  53957. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  53958. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  53959. * 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.
  53960. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  53961. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  53962. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  53963. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  53964. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  53965. * 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).
  53966. * 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
  53967. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  53968. * 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
  53969. * 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.
  53970. * If `enclose` is false, a ring surface is one element.
  53971. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  53972. * 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
  53973. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53974. * 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).
  53975. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53977. */
  53978. MeshBuilder.CreateCylinder = function (name, options, scene) {
  53979. var cylinder = new BABYLON.Mesh(name, scene);
  53980. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53981. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  53982. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  53983. vertexData.applyToMesh(cylinder, options.updatable);
  53984. return cylinder;
  53985. };
  53986. /**
  53987. * Creates a torus mesh.
  53988. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  53989. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  53990. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  53991. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  53992. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53993. * 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).
  53994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53996. */
  53997. MeshBuilder.CreateTorus = function (name, options, scene) {
  53998. var torus = new BABYLON.Mesh(name, scene);
  53999. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54000. torus._originalBuilderSideOrientation = options.sideOrientation;
  54001. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54002. vertexData.applyToMesh(torus, options.updatable);
  54003. return torus;
  54004. };
  54005. /**
  54006. * Creates a torus knot mesh.
  54007. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54008. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54009. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54010. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54011. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54013. * 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).
  54014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54016. */
  54017. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54018. var torusKnot = new BABYLON.Mesh(name, scene);
  54019. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54020. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54021. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54022. vertexData.applyToMesh(torusKnot, options.updatable);
  54023. return torusKnot;
  54024. };
  54025. /**
  54026. * Creates a line system mesh.
  54027. * A line system is a pool of many lines gathered in a single mesh.
  54028. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54029. * 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.
  54030. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54031. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54032. * 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
  54033. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54034. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54035. * 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
  54036. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54037. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54038. */
  54039. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54040. var instance = options.instance;
  54041. var lines = options.lines;
  54042. var colors = options.colors;
  54043. if (instance) {
  54044. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54045. var vertexColor;
  54046. var lineColors;
  54047. if (colors) {
  54048. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54049. }
  54050. var i = 0;
  54051. var c = 0;
  54052. for (var l = 0; l < lines.length; l++) {
  54053. var points = lines[l];
  54054. for (var p = 0; p < points.length; p++) {
  54055. positions[i] = points[p].x;
  54056. positions[i + 1] = points[p].y;
  54057. positions[i + 2] = points[p].z;
  54058. if (colors && vertexColor) {
  54059. lineColors = colors[l];
  54060. vertexColor[c] = lineColors[p].r;
  54061. vertexColor[c + 1] = lineColors[p].g;
  54062. vertexColor[c + 2] = lineColors[p].b;
  54063. vertexColor[c + 3] = lineColors[p].a;
  54064. c += 4;
  54065. }
  54066. i += 3;
  54067. }
  54068. }
  54069. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54070. if (colors && vertexColor) {
  54071. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54072. }
  54073. return instance;
  54074. }
  54075. // line system creation
  54076. var useVertexColor = (colors) ? true : false;
  54077. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54078. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54079. vertexData.applyToMesh(lineSystem, options.updatable);
  54080. return lineSystem;
  54081. };
  54082. /**
  54083. * Creates a line mesh.
  54084. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54085. * 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.
  54086. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54087. * The parameter `points` is an array successive Vector3.
  54088. * 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
  54089. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54090. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54091. * When updating an instance, remember that only point positions can change, not the number of points.
  54092. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54093. */
  54094. MeshBuilder.CreateLines = function (name, options, scene) {
  54095. if (scene === void 0) { scene = null; }
  54096. var colors = (options.colors) ? [options.colors] : null;
  54097. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54098. return lines;
  54099. };
  54100. /**
  54101. * Creates a dashed line mesh.
  54102. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54103. * 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.
  54104. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54105. * The parameter `points` is an array successive Vector3.
  54106. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54107. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54108. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54109. * 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
  54110. * When updating an instance, remember that only point positions can change, not the number of points.
  54111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54112. */
  54113. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54114. if (scene === void 0) { scene = null; }
  54115. var points = options.points;
  54116. var instance = options.instance;
  54117. var gapSize = options.gapSize || 1;
  54118. var dashSize = options.dashSize || 3;
  54119. if (instance) {
  54120. var positionFunction = function (positions) {
  54121. var curvect = BABYLON.Vector3.Zero();
  54122. var nbSeg = positions.length / 6;
  54123. var lg = 0;
  54124. var nb = 0;
  54125. var shft = 0;
  54126. var dashshft = 0;
  54127. var curshft = 0;
  54128. var p = 0;
  54129. var i = 0;
  54130. var j = 0;
  54131. for (i = 0; i < points.length - 1; i++) {
  54132. points[i + 1].subtractToRef(points[i], curvect);
  54133. lg += curvect.length();
  54134. }
  54135. shft = lg / nbSeg;
  54136. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54137. for (i = 0; i < points.length - 1; i++) {
  54138. points[i + 1].subtractToRef(points[i], curvect);
  54139. nb = Math.floor(curvect.length() / shft);
  54140. curvect.normalize();
  54141. j = 0;
  54142. while (j < nb && p < positions.length) {
  54143. curshft = shft * j;
  54144. positions[p] = points[i].x + curshft * curvect.x;
  54145. positions[p + 1] = points[i].y + curshft * curvect.y;
  54146. positions[p + 2] = points[i].z + curshft * curvect.z;
  54147. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54148. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54149. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54150. p += 6;
  54151. j++;
  54152. }
  54153. }
  54154. while (p < positions.length) {
  54155. positions[p] = points[i].x;
  54156. positions[p + 1] = points[i].y;
  54157. positions[p + 2] = points[i].z;
  54158. p += 3;
  54159. }
  54160. };
  54161. instance.updateMeshPositions(positionFunction, false);
  54162. return instance;
  54163. }
  54164. // dashed lines creation
  54165. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54166. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54167. vertexData.applyToMesh(dashedLines, options.updatable);
  54168. dashedLines.dashSize = dashSize;
  54169. dashedLines.gapSize = gapSize;
  54170. return dashedLines;
  54171. };
  54172. /**
  54173. * Creates an extruded shape mesh.
  54174. * 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.
  54175. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54176. *
  54177. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54178. * 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
  54179. * extruded along the Z axis.
  54180. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54181. * 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.
  54182. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54183. * 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
  54184. * 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
  54185. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54186. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54187. * 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).
  54188. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54189. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54191. */
  54192. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54193. if (scene === void 0) { scene = null; }
  54194. var path = options.path;
  54195. var shape = options.shape;
  54196. var scale = options.scale || 1;
  54197. var rotation = options.rotation || 0;
  54198. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54199. var updatable = options.updatable;
  54200. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54201. var instance = options.instance || null;
  54202. var invertUV = options.invertUV || false;
  54203. 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);
  54204. };
  54205. /**
  54206. * Creates an custom extruded shape mesh.
  54207. * 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.
  54208. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54209. *
  54210. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54211. * 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
  54212. * extruded along the Z axis.
  54213. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54214. * 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
  54215. * and the distance of this point from the begining of the path :
  54216. * ```javascript
  54217. * var rotationFunction = function(i, distance) {
  54218. * // do things
  54219. * return rotationValue; }
  54220. * ```
  54221. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54222. * 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
  54223. * and the distance of this point from the begining of the path :
  54224. * ```javascript
  54225. * var scaleFunction = function(i, distance) {
  54226. * // do things
  54227. * return scaleValue;}
  54228. * ```
  54229. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54230. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54231. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54232. * 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
  54233. * 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
  54234. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54236. * 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).
  54237. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54238. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54240. */
  54241. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54242. var path = options.path;
  54243. var shape = options.shape;
  54244. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54245. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54246. var ribbonCloseArray = options.ribbonCloseArray || false;
  54247. var ribbonClosePath = options.ribbonClosePath || false;
  54248. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54249. var updatable = options.updatable;
  54250. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54251. var instance = options.instance;
  54252. var invertUV = options.invertUV || false;
  54253. 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);
  54254. };
  54255. /**
  54256. * Creates lathe mesh.
  54257. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54258. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54259. *
  54260. * 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
  54261. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54262. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54263. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54264. * 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.
  54265. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54266. * 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
  54267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54268. * 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).
  54269. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54270. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54272. */
  54273. MeshBuilder.CreateLathe = function (name, options, scene) {
  54274. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54275. var closed = (options.closed === undefined) ? true : options.closed;
  54276. var shape = options.shape;
  54277. var radius = options.radius || 1;
  54278. var tessellation = options.tessellation || 64;
  54279. var updatable = options.updatable;
  54280. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54281. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54282. var pi2 = Math.PI * 2;
  54283. var paths = new Array();
  54284. var invertUV = options.invertUV || false;
  54285. var i = 0;
  54286. var p = 0;
  54287. var step = pi2 / tessellation * arc;
  54288. var rotated;
  54289. var path = new Array();
  54290. ;
  54291. for (i = 0; i <= tessellation; i++) {
  54292. var path = [];
  54293. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54294. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54295. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54296. }
  54297. for (p = 0; p < shape.length; p++) {
  54298. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54299. path.push(rotated);
  54300. }
  54301. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54302. 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));
  54303. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54304. }
  54305. paths.push(path);
  54306. }
  54307. // lathe ribbon
  54308. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54309. return lathe;
  54310. };
  54311. /**
  54312. * Creates a plane mesh.
  54313. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54314. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54315. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54316. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54317. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54318. * 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).
  54319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54321. */
  54322. MeshBuilder.CreatePlane = function (name, options, scene) {
  54323. var plane = new BABYLON.Mesh(name, scene);
  54324. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54325. plane._originalBuilderSideOrientation = options.sideOrientation;
  54326. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54327. vertexData.applyToMesh(plane, options.updatable);
  54328. if (options.sourcePlane) {
  54329. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54330. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54331. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54332. plane.rotate(vectorProduct, product);
  54333. }
  54334. return plane;
  54335. };
  54336. /**
  54337. * Creates a ground mesh.
  54338. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54339. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54340. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54342. */
  54343. MeshBuilder.CreateGround = function (name, options, scene) {
  54344. var ground = new BABYLON.GroundMesh(name, scene);
  54345. ground._setReady(false);
  54346. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54347. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54348. ground._width = options.width || 1;
  54349. ground._height = options.height || 1;
  54350. ground._maxX = ground._width / 2;
  54351. ground._maxZ = ground._height / 2;
  54352. ground._minX = -ground._maxX;
  54353. ground._minZ = -ground._maxZ;
  54354. var vertexData = BABYLON.VertexData.CreateGround(options);
  54355. vertexData.applyToMesh(ground, options.updatable);
  54356. ground._setReady(true);
  54357. return ground;
  54358. };
  54359. /**
  54360. * Creates a tiled ground mesh.
  54361. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54362. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54363. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54364. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54365. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54366. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54367. * numbers of subdivisions on the ground width and height of each tile.
  54368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54369. */
  54370. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54371. var tiledGround = new BABYLON.Mesh(name, scene);
  54372. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54373. vertexData.applyToMesh(tiledGround, options.updatable);
  54374. return tiledGround;
  54375. };
  54376. /**
  54377. * Creates a ground mesh from a height map.
  54378. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54379. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54380. * The parameter `url` sets the URL of the height map image resource.
  54381. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54382. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54383. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54384. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54385. * 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.
  54386. * 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).
  54387. * This function is passed the newly built mesh :
  54388. * ```javascript
  54389. * function(mesh) { // do things
  54390. * return; }
  54391. * ```
  54392. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54393. */
  54394. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54395. var width = options.width || 10.0;
  54396. var height = options.height || 10.0;
  54397. var subdivisions = options.subdivisions || 1 | 0;
  54398. var minHeight = options.minHeight || 0.0;
  54399. var maxHeight = options.maxHeight || 1.0;
  54400. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54401. var updatable = options.updatable;
  54402. var onReady = options.onReady;
  54403. var ground = new BABYLON.GroundMesh(name, scene);
  54404. ground._subdivisionsX = subdivisions;
  54405. ground._subdivisionsY = subdivisions;
  54406. ground._width = width;
  54407. ground._height = height;
  54408. ground._maxX = ground._width / 2.0;
  54409. ground._maxZ = ground._height / 2.0;
  54410. ground._minX = -ground._maxX;
  54411. ground._minZ = -ground._maxZ;
  54412. ground._setReady(false);
  54413. var onload = function (img) {
  54414. // Getting height map data
  54415. var canvas = document.createElement("canvas");
  54416. var context = canvas.getContext("2d");
  54417. if (!context) {
  54418. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54419. }
  54420. if (scene.isDisposed) {
  54421. return;
  54422. }
  54423. var bufferWidth = img.width;
  54424. var bufferHeight = img.height;
  54425. canvas.width = bufferWidth;
  54426. canvas.height = bufferHeight;
  54427. context.drawImage(img, 0, 0);
  54428. // Create VertexData from map data
  54429. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54430. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54431. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54432. width: width, height: height,
  54433. subdivisions: subdivisions,
  54434. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54435. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54436. });
  54437. vertexData.applyToMesh(ground, updatable);
  54438. ground._setReady(true);
  54439. //execute ready callback, if set
  54440. if (onReady) {
  54441. onReady(ground);
  54442. }
  54443. };
  54444. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54445. return ground;
  54446. };
  54447. /**
  54448. * Creates a polygon mesh.
  54449. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54450. * 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.
  54451. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54453. * 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).
  54454. * Remember you can only change the shape positions, not their number when updating a polygon.
  54455. */
  54456. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54457. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54458. var shape = options.shape;
  54459. var holes = options.holes || [];
  54460. var depth = options.depth || 0;
  54461. var contours = [];
  54462. var hole = [];
  54463. for (var i = 0; i < shape.length; i++) {
  54464. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54465. }
  54466. var epsilon = 0.00000001;
  54467. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54468. contours.pop();
  54469. }
  54470. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54471. for (var hNb = 0; hNb < holes.length; hNb++) {
  54472. hole = [];
  54473. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54474. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54475. }
  54476. polygonTriangulation.addHole(hole);
  54477. }
  54478. var polygon = polygonTriangulation.build(options.updatable, depth);
  54479. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54480. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54481. vertexData.applyToMesh(polygon, options.updatable);
  54482. return polygon;
  54483. };
  54484. ;
  54485. /**
  54486. * Creates an extruded polygon mesh, with depth in the Y direction.
  54487. * 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).
  54488. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54489. */
  54490. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54491. return MeshBuilder.CreatePolygon(name, options, scene);
  54492. };
  54493. ;
  54494. /**
  54495. * Creates a tube mesh.
  54496. * 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.
  54497. *
  54498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54499. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54500. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54501. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54502. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54503. * 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.
  54504. * It must return a radius value (positive float) :
  54505. * ```javascript
  54506. * var radiusFunction = function(i, distance) {
  54507. * // do things
  54508. * return radius; }
  54509. * ```
  54510. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54511. * 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
  54512. * 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
  54513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54514. * 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).
  54515. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54516. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54518. */
  54519. MeshBuilder.CreateTube = function (name, options, scene) {
  54520. var path = options.path;
  54521. var instance = options.instance;
  54522. var radius = 1.0;
  54523. if (instance) {
  54524. radius = instance.radius;
  54525. }
  54526. if (options.radius !== undefined) {
  54527. radius = options.radius;
  54528. }
  54529. ;
  54530. var tessellation = options.tessellation || 64 | 0;
  54531. var radiusFunction = options.radiusFunction || null;
  54532. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54533. var invertUV = options.invertUV || false;
  54534. var updatable = options.updatable;
  54535. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54536. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54537. // tube geometry
  54538. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54539. var tangents = path3D.getTangents();
  54540. var normals = path3D.getNormals();
  54541. var distances = path3D.getDistances();
  54542. var pi2 = Math.PI * 2;
  54543. var step = pi2 / tessellation * arc;
  54544. var returnRadius = function () { return radius; };
  54545. var radiusFunctionFinal = radiusFunction || returnRadius;
  54546. var circlePath;
  54547. var rad;
  54548. var normal;
  54549. var rotated;
  54550. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54551. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54552. for (var i = 0; i < path.length; i++) {
  54553. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54554. circlePath = Array(); // current circle array
  54555. normal = normals[i]; // current normal
  54556. for (var t = 0; t < tessellation; t++) {
  54557. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54558. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54559. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54560. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54561. circlePath[t] = rotated;
  54562. }
  54563. circlePaths[index] = circlePath;
  54564. index++;
  54565. }
  54566. // cap
  54567. var capPath = function (nbPoints, pathIndex) {
  54568. var pointCap = Array();
  54569. for (var i = 0; i < nbPoints; i++) {
  54570. pointCap.push(path[pathIndex]);
  54571. }
  54572. return pointCap;
  54573. };
  54574. switch (cap) {
  54575. case BABYLON.Mesh.NO_CAP:
  54576. break;
  54577. case BABYLON.Mesh.CAP_START:
  54578. circlePaths[0] = capPath(tessellation, 0);
  54579. circlePaths[1] = circlePaths[2].slice(0);
  54580. break;
  54581. case BABYLON.Mesh.CAP_END:
  54582. circlePaths[index] = circlePaths[index - 1].slice(0);
  54583. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54584. break;
  54585. case BABYLON.Mesh.CAP_ALL:
  54586. circlePaths[0] = capPath(tessellation, 0);
  54587. circlePaths[1] = circlePaths[2].slice(0);
  54588. circlePaths[index] = circlePaths[index - 1].slice(0);
  54589. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54590. break;
  54591. default:
  54592. break;
  54593. }
  54594. return circlePaths;
  54595. };
  54596. var path3D;
  54597. var pathArray;
  54598. if (instance) {
  54599. var arc = options.arc || instance.arc;
  54600. path3D = (instance.path3D).update(path);
  54601. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54602. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54603. instance.path3D = path3D;
  54604. instance.pathArray = pathArray;
  54605. instance.arc = arc;
  54606. instance.radius = radius;
  54607. return instance;
  54608. }
  54609. // tube creation
  54610. path3D = new BABYLON.Path3D(path);
  54611. var newPathArray = new Array();
  54612. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54613. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54614. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54615. tube.pathArray = pathArray;
  54616. tube.path3D = path3D;
  54617. tube.tessellation = tessellation;
  54618. tube.cap = cap;
  54619. tube.arc = options.arc;
  54620. tube.radius = radius;
  54621. return tube;
  54622. };
  54623. /**
  54624. * Creates a polyhedron mesh.
  54625. *
  54626. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54627. * 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
  54628. * to choose the wanted type.
  54629. * The parameter `size` (positive float, default 1) sets the polygon size.
  54630. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54631. * 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`.
  54632. * 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
  54633. * 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)`).
  54634. * 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
  54635. * 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.
  54636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54637. * 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).
  54638. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54640. */
  54641. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54642. var polyhedron = new BABYLON.Mesh(name, scene);
  54643. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54644. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54645. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54646. vertexData.applyToMesh(polyhedron, options.updatable);
  54647. return polyhedron;
  54648. };
  54649. /**
  54650. * Creates a decal mesh.
  54651. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54652. * 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.
  54653. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54654. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54655. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54656. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54657. */
  54658. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54659. var indices = sourceMesh.getIndices();
  54660. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54661. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54662. var position = options.position || BABYLON.Vector3.Zero();
  54663. var normal = options.normal || BABYLON.Vector3.Up();
  54664. var size = options.size || BABYLON.Vector3.One();
  54665. var angle = options.angle || 0;
  54666. // Getting correct rotation
  54667. if (!normal) {
  54668. var target = new BABYLON.Vector3(0, 0, 1);
  54669. var camera = sourceMesh.getScene().activeCamera;
  54670. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54671. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54672. }
  54673. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54674. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54675. var pitch = Math.atan2(normal.y, len);
  54676. // Matrix
  54677. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54678. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54679. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54680. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54681. var vertexData = new BABYLON.VertexData();
  54682. vertexData.indices = [];
  54683. vertexData.positions = [];
  54684. vertexData.normals = [];
  54685. vertexData.uvs = [];
  54686. var currentVertexDataIndex = 0;
  54687. var extractDecalVector3 = function (indexId) {
  54688. var result = new BABYLON.PositionNormalVertex();
  54689. if (!indices || !positions || !normals) {
  54690. return result;
  54691. }
  54692. var vertexId = indices[indexId];
  54693. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54694. // Send vector to decal local world
  54695. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54696. // Get normal
  54697. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54698. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54699. return result;
  54700. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54701. var clip = function (vertices, axis) {
  54702. if (vertices.length === 0) {
  54703. return vertices;
  54704. }
  54705. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54706. var clipVertices = function (v0, v1) {
  54707. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54708. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54709. };
  54710. var result = new Array();
  54711. for (var index = 0; index < vertices.length; index += 3) {
  54712. var v1Out;
  54713. var v2Out;
  54714. var v3Out;
  54715. var total = 0;
  54716. var nV1 = null;
  54717. var nV2 = null;
  54718. var nV3 = null;
  54719. var nV4 = null;
  54720. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54721. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54722. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54723. v1Out = d1 > 0;
  54724. v2Out = d2 > 0;
  54725. v3Out = d3 > 0;
  54726. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54727. switch (total) {
  54728. case 0:
  54729. result.push(vertices[index]);
  54730. result.push(vertices[index + 1]);
  54731. result.push(vertices[index + 2]);
  54732. break;
  54733. case 1:
  54734. if (v1Out) {
  54735. nV1 = vertices[index + 1];
  54736. nV2 = vertices[index + 2];
  54737. nV3 = clipVertices(vertices[index], nV1);
  54738. nV4 = clipVertices(vertices[index], nV2);
  54739. }
  54740. if (v2Out) {
  54741. nV1 = vertices[index];
  54742. nV2 = vertices[index + 2];
  54743. nV3 = clipVertices(vertices[index + 1], nV1);
  54744. nV4 = clipVertices(vertices[index + 1], nV2);
  54745. result.push(nV3);
  54746. result.push(nV2.clone());
  54747. result.push(nV1.clone());
  54748. result.push(nV2.clone());
  54749. result.push(nV3.clone());
  54750. result.push(nV4);
  54751. break;
  54752. }
  54753. if (v3Out) {
  54754. nV1 = vertices[index];
  54755. nV2 = vertices[index + 1];
  54756. nV3 = clipVertices(vertices[index + 2], nV1);
  54757. nV4 = clipVertices(vertices[index + 2], nV2);
  54758. }
  54759. if (nV1 && nV2 && nV3 && nV4) {
  54760. result.push(nV1.clone());
  54761. result.push(nV2.clone());
  54762. result.push(nV3);
  54763. result.push(nV4);
  54764. result.push(nV3.clone());
  54765. result.push(nV2.clone());
  54766. }
  54767. break;
  54768. case 2:
  54769. if (!v1Out) {
  54770. nV1 = vertices[index].clone();
  54771. nV2 = clipVertices(nV1, vertices[index + 1]);
  54772. nV3 = clipVertices(nV1, vertices[index + 2]);
  54773. result.push(nV1);
  54774. result.push(nV2);
  54775. result.push(nV3);
  54776. }
  54777. if (!v2Out) {
  54778. nV1 = vertices[index + 1].clone();
  54779. nV2 = clipVertices(nV1, vertices[index + 2]);
  54780. nV3 = clipVertices(nV1, vertices[index]);
  54781. result.push(nV1);
  54782. result.push(nV2);
  54783. result.push(nV3);
  54784. }
  54785. if (!v3Out) {
  54786. nV1 = vertices[index + 2].clone();
  54787. nV2 = clipVertices(nV1, vertices[index]);
  54788. nV3 = clipVertices(nV1, vertices[index + 1]);
  54789. result.push(nV1);
  54790. result.push(nV2);
  54791. result.push(nV3);
  54792. }
  54793. break;
  54794. case 3:
  54795. break;
  54796. }
  54797. }
  54798. return result;
  54799. };
  54800. for (var index = 0; index < indices.length; index += 3) {
  54801. var faceVertices = new Array();
  54802. faceVertices.push(extractDecalVector3(index));
  54803. faceVertices.push(extractDecalVector3(index + 1));
  54804. faceVertices.push(extractDecalVector3(index + 2));
  54805. // Clip
  54806. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54807. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54808. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54809. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54810. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54811. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54812. if (faceVertices.length === 0) {
  54813. continue;
  54814. }
  54815. // Add UVs and get back to world
  54816. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54817. var vertex = faceVertices[vIndex];
  54818. //TODO check for Int32Array | Uint32Array | Uint16Array
  54819. vertexData.indices.push(currentVertexDataIndex);
  54820. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54821. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54822. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54823. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54824. currentVertexDataIndex++;
  54825. }
  54826. }
  54827. // Return mesh
  54828. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54829. vertexData.applyToMesh(decal);
  54830. decal.position = position.clone();
  54831. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54832. return decal;
  54833. };
  54834. // Privates
  54835. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54836. // extrusion geometry
  54837. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54838. var tangents = path3D.getTangents();
  54839. var normals = path3D.getNormals();
  54840. var binormals = path3D.getBinormals();
  54841. var distances = path3D.getDistances();
  54842. var angle = 0;
  54843. var returnScale = function () { return scale !== null ? scale : 1; };
  54844. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54845. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54846. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54847. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54848. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54849. for (var i = 0; i < curve.length; i++) {
  54850. var shapePath = new Array();
  54851. var angleStep = rotate(i, distances[i]);
  54852. var scaleRatio = scl(i, distances[i]);
  54853. for (var p = 0; p < shape.length; p++) {
  54854. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54855. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54856. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54857. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54858. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54859. shapePath[p] = rotated;
  54860. }
  54861. shapePaths[index] = shapePath;
  54862. angle += angleStep;
  54863. index++;
  54864. }
  54865. // cap
  54866. var capPath = function (shapePath) {
  54867. var pointCap = Array();
  54868. var barycenter = BABYLON.Vector3.Zero();
  54869. var i;
  54870. for (i = 0; i < shapePath.length; i++) {
  54871. barycenter.addInPlace(shapePath[i]);
  54872. }
  54873. barycenter.scaleInPlace(1.0 / shapePath.length);
  54874. for (i = 0; i < shapePath.length; i++) {
  54875. pointCap.push(barycenter);
  54876. }
  54877. return pointCap;
  54878. };
  54879. switch (cap) {
  54880. case BABYLON.Mesh.NO_CAP:
  54881. break;
  54882. case BABYLON.Mesh.CAP_START:
  54883. shapePaths[0] = capPath(shapePaths[2]);
  54884. shapePaths[1] = shapePaths[2];
  54885. break;
  54886. case BABYLON.Mesh.CAP_END:
  54887. shapePaths[index] = shapePaths[index - 1];
  54888. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54889. break;
  54890. case BABYLON.Mesh.CAP_ALL:
  54891. shapePaths[0] = capPath(shapePaths[2]);
  54892. shapePaths[1] = shapePaths[2];
  54893. shapePaths[index] = shapePaths[index - 1];
  54894. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54895. break;
  54896. default:
  54897. break;
  54898. }
  54899. return shapePaths;
  54900. };
  54901. var path3D;
  54902. var pathArray;
  54903. if (instance) {
  54904. path3D = (instance.path3D).update(curve);
  54905. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54906. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54907. return instance;
  54908. }
  54909. // extruded shape creation
  54910. path3D = new BABYLON.Path3D(curve);
  54911. var newShapePaths = new Array();
  54912. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54913. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54914. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54915. extrudedGeneric.pathArray = pathArray;
  54916. extrudedGeneric.path3D = path3D;
  54917. extrudedGeneric.cap = cap;
  54918. return extrudedGeneric;
  54919. };
  54920. return MeshBuilder;
  54921. }());
  54922. BABYLON.MeshBuilder = MeshBuilder;
  54923. })(BABYLON || (BABYLON = {}));
  54924. //# sourceMappingURL=babylon.meshBuilder.js.map
  54925. var BABYLON;
  54926. (function (BABYLON) {
  54927. var AudioEngine = /** @class */ (function () {
  54928. function AudioEngine() {
  54929. this._audioContext = null;
  54930. this._audioContextInitialized = false;
  54931. this.canUseWebAudio = false;
  54932. this.WarnedWebAudioUnsupported = false;
  54933. this.unlocked = false;
  54934. this.isMP3supported = false;
  54935. this.isOGGsupported = false;
  54936. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  54937. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  54938. this.canUseWebAudio = true;
  54939. }
  54940. var audioElem = document.createElement('audio');
  54941. try {
  54942. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  54943. this.isMP3supported = true;
  54944. }
  54945. }
  54946. catch (e) {
  54947. // protect error during capability check.
  54948. }
  54949. try {
  54950. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  54951. this.isOGGsupported = true;
  54952. }
  54953. }
  54954. catch (e) {
  54955. // protect error during capability check.
  54956. }
  54957. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  54958. this._unlockiOSaudio();
  54959. }
  54960. else {
  54961. this.unlocked = true;
  54962. }
  54963. }
  54964. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  54965. get: function () {
  54966. if (!this._audioContextInitialized) {
  54967. this._initializeAudioContext();
  54968. }
  54969. return this._audioContext;
  54970. },
  54971. enumerable: true,
  54972. configurable: true
  54973. });
  54974. AudioEngine.prototype._unlockiOSaudio = function () {
  54975. var _this = this;
  54976. var unlockaudio = function () {
  54977. if (!_this.audioContext) {
  54978. return;
  54979. }
  54980. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  54981. var source = _this.audioContext.createBufferSource();
  54982. source.buffer = buffer;
  54983. source.connect(_this.audioContext.destination);
  54984. source.start(0);
  54985. setTimeout(function () {
  54986. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  54987. _this.unlocked = true;
  54988. window.removeEventListener('touchend', unlockaudio, false);
  54989. if (_this.onAudioUnlocked) {
  54990. _this.onAudioUnlocked();
  54991. }
  54992. }
  54993. }, 0);
  54994. };
  54995. window.addEventListener('touchend', unlockaudio, false);
  54996. };
  54997. AudioEngine.prototype._initializeAudioContext = function () {
  54998. try {
  54999. if (this.canUseWebAudio) {
  55000. this._audioContext = new AudioContext();
  55001. // create a global volume gain node
  55002. this.masterGain = this._audioContext.createGain();
  55003. this.masterGain.gain.value = 1;
  55004. this.masterGain.connect(this._audioContext.destination);
  55005. this._audioContextInitialized = true;
  55006. }
  55007. }
  55008. catch (e) {
  55009. this.canUseWebAudio = false;
  55010. BABYLON.Tools.Error("Web Audio: " + e.message);
  55011. }
  55012. };
  55013. AudioEngine.prototype.dispose = function () {
  55014. if (this.canUseWebAudio && this._audioContextInitialized) {
  55015. if (this._connectedAnalyser && this._audioContext) {
  55016. this._connectedAnalyser.stopDebugCanvas();
  55017. this._connectedAnalyser.dispose();
  55018. this.masterGain.disconnect();
  55019. this.masterGain.connect(this._audioContext.destination);
  55020. this._connectedAnalyser = null;
  55021. }
  55022. this.masterGain.gain.value = 1;
  55023. }
  55024. this.WarnedWebAudioUnsupported = false;
  55025. };
  55026. AudioEngine.prototype.getGlobalVolume = function () {
  55027. if (this.canUseWebAudio && this._audioContextInitialized) {
  55028. return this.masterGain.gain.value;
  55029. }
  55030. else {
  55031. return -1;
  55032. }
  55033. };
  55034. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55035. if (this.canUseWebAudio && this._audioContextInitialized) {
  55036. this.masterGain.gain.value = newVolume;
  55037. }
  55038. };
  55039. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55040. if (this._connectedAnalyser) {
  55041. this._connectedAnalyser.stopDebugCanvas();
  55042. }
  55043. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55044. this._connectedAnalyser = analyser;
  55045. this.masterGain.disconnect();
  55046. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55047. }
  55048. };
  55049. return AudioEngine;
  55050. }());
  55051. BABYLON.AudioEngine = AudioEngine;
  55052. })(BABYLON || (BABYLON = {}));
  55053. //# sourceMappingURL=babylon.audioEngine.js.map
  55054. var BABYLON;
  55055. (function (BABYLON) {
  55056. var Sound = /** @class */ (function () {
  55057. /**
  55058. * Create a sound and attach it to a scene
  55059. * @param name Name of your sound
  55060. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55061. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55062. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55063. */
  55064. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55065. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55066. var _this = this;
  55067. this.autoplay = false;
  55068. this.loop = false;
  55069. this.useCustomAttenuation = false;
  55070. this.spatialSound = false;
  55071. this.refDistance = 1;
  55072. this.rolloffFactor = 1;
  55073. this.maxDistance = 100;
  55074. this.distanceModel = "linear";
  55075. this._panningModel = "equalpower";
  55076. this._playbackRate = 1;
  55077. this._streaming = false;
  55078. this._startTime = 0;
  55079. this._startOffset = 0;
  55080. this._position = BABYLON.Vector3.Zero();
  55081. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55082. this._volume = 1;
  55083. this._isReadyToPlay = false;
  55084. this.isPlaying = false;
  55085. this.isPaused = false;
  55086. this._isDirectional = false;
  55087. // Used if you'd like to create a directional sound.
  55088. // If not set, the sound will be omnidirectional
  55089. this._coneInnerAngle = 360;
  55090. this._coneOuterAngle = 360;
  55091. this._coneOuterGain = 0;
  55092. this._isOutputConnected = false;
  55093. this._urlType = "Unknown";
  55094. this.name = name;
  55095. this._scene = scene;
  55096. this._readyToPlayCallback = readyToPlayCallback;
  55097. // Default custom attenuation function is a linear attenuation
  55098. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55099. if (currentDistance < maxDistance) {
  55100. return currentVolume * (1 - currentDistance / maxDistance);
  55101. }
  55102. else {
  55103. return 0;
  55104. }
  55105. };
  55106. if (options) {
  55107. this.autoplay = options.autoplay || false;
  55108. this.loop = options.loop || false;
  55109. // if volume === 0, we need another way to check this option
  55110. if (options.volume !== undefined) {
  55111. this._volume = options.volume;
  55112. }
  55113. this.spatialSound = options.spatialSound || false;
  55114. this.maxDistance = options.maxDistance || 100;
  55115. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55116. this.rolloffFactor = options.rolloffFactor || 1;
  55117. this.refDistance = options.refDistance || 1;
  55118. this.distanceModel = options.distanceModel || "linear";
  55119. this._playbackRate = options.playbackRate || 1;
  55120. this._streaming = options.streaming || false;
  55121. }
  55122. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55123. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55124. this._soundGain.gain.value = this._volume;
  55125. this._inputAudioNode = this._soundGain;
  55126. this._ouputAudioNode = this._soundGain;
  55127. if (this.spatialSound) {
  55128. this._createSpatialParameters();
  55129. }
  55130. this._scene.mainSoundTrack.AddSound(this);
  55131. var validParameter = true;
  55132. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55133. if (urlOrArrayBuffer) {
  55134. if (typeof (urlOrArrayBuffer) === "string")
  55135. this._urlType = "String";
  55136. if (Array.isArray(urlOrArrayBuffer))
  55137. this._urlType = "Array";
  55138. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55139. this._urlType = "ArrayBuffer";
  55140. var urls = [];
  55141. var codecSupportedFound = false;
  55142. switch (this._urlType) {
  55143. case "ArrayBuffer":
  55144. if (urlOrArrayBuffer.byteLength > 0) {
  55145. codecSupportedFound = true;
  55146. this._soundLoaded(urlOrArrayBuffer);
  55147. }
  55148. break;
  55149. case "String":
  55150. urls.push(urlOrArrayBuffer);
  55151. case "Array":
  55152. if (urls.length === 0)
  55153. urls = urlOrArrayBuffer;
  55154. // If we found a supported format, we load it immediately and stop the loop
  55155. for (var i = 0; i < urls.length; i++) {
  55156. var url = urls[i];
  55157. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55158. codecSupportedFound = true;
  55159. }
  55160. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55161. codecSupportedFound = true;
  55162. }
  55163. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55164. codecSupportedFound = true;
  55165. }
  55166. if (url.indexOf("blob:") !== -1) {
  55167. codecSupportedFound = true;
  55168. }
  55169. if (codecSupportedFound) {
  55170. // Loading sound using XHR2
  55171. if (!this._streaming) {
  55172. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55173. }
  55174. else {
  55175. this._htmlAudioElement = new Audio(url);
  55176. this._htmlAudioElement.controls = false;
  55177. this._htmlAudioElement.loop = this.loop;
  55178. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55179. this._htmlAudioElement.preload = "auto";
  55180. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55181. _this._isReadyToPlay = true;
  55182. if (_this.autoplay) {
  55183. _this.play();
  55184. }
  55185. if (_this._readyToPlayCallback) {
  55186. _this._readyToPlayCallback();
  55187. }
  55188. });
  55189. document.body.appendChild(this._htmlAudioElement);
  55190. }
  55191. break;
  55192. }
  55193. }
  55194. break;
  55195. default:
  55196. validParameter = false;
  55197. break;
  55198. }
  55199. if (!validParameter) {
  55200. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55201. }
  55202. else {
  55203. if (!codecSupportedFound) {
  55204. this._isReadyToPlay = true;
  55205. // Simulating a ready to play event to avoid breaking code path
  55206. if (this._readyToPlayCallback) {
  55207. window.setTimeout(function () {
  55208. if (_this._readyToPlayCallback) {
  55209. _this._readyToPlayCallback();
  55210. }
  55211. }, 1000);
  55212. }
  55213. }
  55214. }
  55215. }
  55216. }
  55217. else {
  55218. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55219. this._scene.mainSoundTrack.AddSound(this);
  55220. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55221. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55222. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55223. }
  55224. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55225. if (this._readyToPlayCallback) {
  55226. window.setTimeout(function () {
  55227. if (_this._readyToPlayCallback) {
  55228. _this._readyToPlayCallback();
  55229. }
  55230. }, 1000);
  55231. }
  55232. }
  55233. }
  55234. Sound.prototype.dispose = function () {
  55235. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55236. if (this.isPlaying) {
  55237. this.stop();
  55238. }
  55239. this._isReadyToPlay = false;
  55240. if (this.soundTrackId === -1) {
  55241. this._scene.mainSoundTrack.RemoveSound(this);
  55242. }
  55243. else {
  55244. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55245. }
  55246. if (this._soundGain) {
  55247. this._soundGain.disconnect();
  55248. this._soundGain = null;
  55249. }
  55250. if (this._soundPanner) {
  55251. this._soundPanner.disconnect();
  55252. this._soundPanner = null;
  55253. }
  55254. if (this._soundSource) {
  55255. this._soundSource.disconnect();
  55256. this._soundSource = null;
  55257. }
  55258. this._audioBuffer = null;
  55259. if (this._htmlAudioElement) {
  55260. this._htmlAudioElement.pause();
  55261. this._htmlAudioElement.src = "";
  55262. document.body.removeChild(this._htmlAudioElement);
  55263. }
  55264. if (this._connectedMesh && this._registerFunc) {
  55265. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55266. this._connectedMesh = null;
  55267. }
  55268. }
  55269. };
  55270. Sound.prototype.isReady = function () {
  55271. return this._isReadyToPlay;
  55272. };
  55273. Sound.prototype._soundLoaded = function (audioData) {
  55274. var _this = this;
  55275. if (!BABYLON.Engine.audioEngine.audioContext) {
  55276. return;
  55277. }
  55278. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55279. _this._audioBuffer = buffer;
  55280. _this._isReadyToPlay = true;
  55281. if (_this.autoplay) {
  55282. _this.play();
  55283. }
  55284. if (_this._readyToPlayCallback) {
  55285. _this._readyToPlayCallback();
  55286. }
  55287. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55288. };
  55289. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55290. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55291. this._audioBuffer = audioBuffer;
  55292. this._isReadyToPlay = true;
  55293. }
  55294. };
  55295. Sound.prototype.updateOptions = function (options) {
  55296. if (options) {
  55297. this.loop = options.loop || this.loop;
  55298. this.maxDistance = options.maxDistance || this.maxDistance;
  55299. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55300. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55301. this.refDistance = options.refDistance || this.refDistance;
  55302. this.distanceModel = options.distanceModel || this.distanceModel;
  55303. this._playbackRate = options.playbackRate || this._playbackRate;
  55304. this._updateSpatialParameters();
  55305. if (this.isPlaying) {
  55306. if (this._streaming) {
  55307. this._htmlAudioElement.playbackRate = this._playbackRate;
  55308. }
  55309. else {
  55310. if (this._soundSource) {
  55311. this._soundSource.playbackRate.value = this._playbackRate;
  55312. }
  55313. }
  55314. }
  55315. }
  55316. };
  55317. Sound.prototype._createSpatialParameters = function () {
  55318. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55319. if (this._scene.headphone) {
  55320. this._panningModel = "HRTF";
  55321. }
  55322. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55323. this._updateSpatialParameters();
  55324. this._soundPanner.connect(this._ouputAudioNode);
  55325. this._inputAudioNode = this._soundPanner;
  55326. }
  55327. };
  55328. Sound.prototype._updateSpatialParameters = function () {
  55329. if (this.spatialSound && this._soundPanner) {
  55330. if (this.useCustomAttenuation) {
  55331. // Tricks to disable in a way embedded Web Audio attenuation
  55332. this._soundPanner.distanceModel = "linear";
  55333. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55334. this._soundPanner.refDistance = 1;
  55335. this._soundPanner.rolloffFactor = 1;
  55336. this._soundPanner.panningModel = this._panningModel;
  55337. }
  55338. else {
  55339. this._soundPanner.distanceModel = this.distanceModel;
  55340. this._soundPanner.maxDistance = this.maxDistance;
  55341. this._soundPanner.refDistance = this.refDistance;
  55342. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55343. this._soundPanner.panningModel = this._panningModel;
  55344. }
  55345. }
  55346. };
  55347. Sound.prototype.switchPanningModelToHRTF = function () {
  55348. this._panningModel = "HRTF";
  55349. this._switchPanningModel();
  55350. };
  55351. Sound.prototype.switchPanningModelToEqualPower = function () {
  55352. this._panningModel = "equalpower";
  55353. this._switchPanningModel();
  55354. };
  55355. Sound.prototype._switchPanningModel = function () {
  55356. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55357. this._soundPanner.panningModel = this._panningModel;
  55358. }
  55359. };
  55360. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55361. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55362. if (this._isOutputConnected) {
  55363. this._ouputAudioNode.disconnect();
  55364. }
  55365. this._ouputAudioNode.connect(soundTrackAudioNode);
  55366. this._isOutputConnected = true;
  55367. }
  55368. };
  55369. /**
  55370. * Transform this sound into a directional source
  55371. * @param coneInnerAngle Size of the inner cone in degree
  55372. * @param coneOuterAngle Size of the outer cone in degree
  55373. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55374. */
  55375. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55376. if (coneOuterAngle < coneInnerAngle) {
  55377. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55378. return;
  55379. }
  55380. this._coneInnerAngle = coneInnerAngle;
  55381. this._coneOuterAngle = coneOuterAngle;
  55382. this._coneOuterGain = coneOuterGain;
  55383. this._isDirectional = true;
  55384. if (this.isPlaying && this.loop) {
  55385. this.stop();
  55386. this.play();
  55387. }
  55388. };
  55389. Sound.prototype.setPosition = function (newPosition) {
  55390. this._position = newPosition;
  55391. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55392. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55393. }
  55394. };
  55395. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55396. this._localDirection = newLocalDirection;
  55397. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55398. this._updateDirection();
  55399. }
  55400. };
  55401. Sound.prototype._updateDirection = function () {
  55402. if (!this._connectedMesh || !this._soundPanner) {
  55403. return;
  55404. }
  55405. var mat = this._connectedMesh.getWorldMatrix();
  55406. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55407. direction.normalize();
  55408. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55409. };
  55410. Sound.prototype.updateDistanceFromListener = function () {
  55411. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55412. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55413. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55414. }
  55415. };
  55416. Sound.prototype.setAttenuationFunction = function (callback) {
  55417. this._customAttenuationFunction = callback;
  55418. };
  55419. /**
  55420. * Play the sound
  55421. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55422. * @param offset (optional) Start the sound setting it at a specific time
  55423. */
  55424. Sound.prototype.play = function (time, offset) {
  55425. var _this = this;
  55426. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55427. try {
  55428. if (this._startOffset < 0) {
  55429. time = -this._startOffset;
  55430. this._startOffset = 0;
  55431. }
  55432. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55433. if (!this._soundSource || !this._streamingSource) {
  55434. if (this.spatialSound && this._soundPanner) {
  55435. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55436. if (this._isDirectional) {
  55437. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55438. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55439. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55440. if (this._connectedMesh) {
  55441. this._updateDirection();
  55442. }
  55443. else {
  55444. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55445. }
  55446. }
  55447. }
  55448. }
  55449. if (this._streaming) {
  55450. if (!this._streamingSource) {
  55451. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55452. this._htmlAudioElement.onended = function () { _this._onended(); };
  55453. this._htmlAudioElement.playbackRate = this._playbackRate;
  55454. }
  55455. this._streamingSource.disconnect();
  55456. this._streamingSource.connect(this._inputAudioNode);
  55457. this._htmlAudioElement.play();
  55458. }
  55459. else {
  55460. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55461. this._soundSource.buffer = this._audioBuffer;
  55462. this._soundSource.connect(this._inputAudioNode);
  55463. this._soundSource.loop = this.loop;
  55464. this._soundSource.playbackRate.value = this._playbackRate;
  55465. this._soundSource.onended = function () { _this._onended(); };
  55466. if (this._soundSource.buffer) {
  55467. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55468. }
  55469. }
  55470. this._startTime = startTime;
  55471. this.isPlaying = true;
  55472. this.isPaused = false;
  55473. }
  55474. catch (ex) {
  55475. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55476. }
  55477. }
  55478. };
  55479. Sound.prototype._onended = function () {
  55480. this.isPlaying = false;
  55481. if (this.onended) {
  55482. this.onended();
  55483. }
  55484. };
  55485. /**
  55486. * Stop the sound
  55487. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55488. */
  55489. Sound.prototype.stop = function (time) {
  55490. if (this.isPlaying) {
  55491. if (this._streaming) {
  55492. this._htmlAudioElement.pause();
  55493. // Test needed for Firefox or it will generate an Invalid State Error
  55494. if (this._htmlAudioElement.currentTime > 0) {
  55495. this._htmlAudioElement.currentTime = 0;
  55496. }
  55497. }
  55498. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55499. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55500. this._soundSource.stop(stopTime);
  55501. this._soundSource.onended = function () { };
  55502. if (!this.isPaused) {
  55503. this._startOffset = 0;
  55504. }
  55505. }
  55506. this.isPlaying = false;
  55507. }
  55508. };
  55509. Sound.prototype.pause = function () {
  55510. if (this.isPlaying) {
  55511. this.isPaused = true;
  55512. if (this._streaming) {
  55513. this._htmlAudioElement.pause();
  55514. }
  55515. else if (BABYLON.Engine.audioEngine.audioContext) {
  55516. this.stop(0);
  55517. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55518. }
  55519. }
  55520. };
  55521. Sound.prototype.setVolume = function (newVolume, time) {
  55522. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55523. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55524. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55525. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55526. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55527. }
  55528. else {
  55529. this._soundGain.gain.value = newVolume;
  55530. }
  55531. }
  55532. this._volume = newVolume;
  55533. };
  55534. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55535. this._playbackRate = newPlaybackRate;
  55536. if (this.isPlaying) {
  55537. if (this._streaming) {
  55538. this._htmlAudioElement.playbackRate = this._playbackRate;
  55539. }
  55540. else if (this._soundSource) {
  55541. this._soundSource.playbackRate.value = this._playbackRate;
  55542. }
  55543. }
  55544. };
  55545. Sound.prototype.getVolume = function () {
  55546. return this._volume;
  55547. };
  55548. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55549. var _this = this;
  55550. if (this._connectedMesh && this._registerFunc) {
  55551. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55552. this._registerFunc = null;
  55553. }
  55554. this._connectedMesh = meshToConnectTo;
  55555. if (!this.spatialSound) {
  55556. this.spatialSound = true;
  55557. this._createSpatialParameters();
  55558. if (this.isPlaying && this.loop) {
  55559. this.stop();
  55560. this.play();
  55561. }
  55562. }
  55563. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55564. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55565. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55566. };
  55567. Sound.prototype.detachFromMesh = function () {
  55568. if (this._connectedMesh && this._registerFunc) {
  55569. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55570. this._registerFunc = null;
  55571. this._connectedMesh = null;
  55572. }
  55573. };
  55574. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55575. if (!node.getBoundingInfo) {
  55576. return;
  55577. }
  55578. var mesh = node;
  55579. var boundingInfo = mesh.getBoundingInfo();
  55580. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55581. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55582. this._updateDirection();
  55583. }
  55584. };
  55585. Sound.prototype.clone = function () {
  55586. var _this = this;
  55587. if (!this._streaming) {
  55588. var setBufferAndRun = function () {
  55589. if (_this._isReadyToPlay) {
  55590. clonedSound._audioBuffer = _this.getAudioBuffer();
  55591. clonedSound._isReadyToPlay = true;
  55592. if (clonedSound.autoplay) {
  55593. clonedSound.play();
  55594. }
  55595. }
  55596. else {
  55597. window.setTimeout(setBufferAndRun, 300);
  55598. }
  55599. };
  55600. var currentOptions = {
  55601. autoplay: this.autoplay, loop: this.loop,
  55602. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55603. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55604. refDistance: this.refDistance, distanceModel: this.distanceModel
  55605. };
  55606. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55607. if (this.useCustomAttenuation) {
  55608. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55609. }
  55610. clonedSound.setPosition(this._position);
  55611. clonedSound.setPlaybackRate(this._playbackRate);
  55612. setBufferAndRun();
  55613. return clonedSound;
  55614. }
  55615. else {
  55616. return null;
  55617. }
  55618. };
  55619. Sound.prototype.getAudioBuffer = function () {
  55620. return this._audioBuffer;
  55621. };
  55622. Sound.prototype.serialize = function () {
  55623. var serializationObject = {
  55624. name: this.name,
  55625. url: this.name,
  55626. autoplay: this.autoplay,
  55627. loop: this.loop,
  55628. volume: this._volume,
  55629. spatialSound: this.spatialSound,
  55630. maxDistance: this.maxDistance,
  55631. rolloffFactor: this.rolloffFactor,
  55632. refDistance: this.refDistance,
  55633. distanceModel: this.distanceModel,
  55634. playbackRate: this._playbackRate,
  55635. panningModel: this._panningModel,
  55636. soundTrackId: this.soundTrackId
  55637. };
  55638. if (this.spatialSound) {
  55639. if (this._connectedMesh)
  55640. serializationObject.connectedMeshId = this._connectedMesh.id;
  55641. serializationObject.position = this._position.asArray();
  55642. serializationObject.refDistance = this.refDistance;
  55643. serializationObject.distanceModel = this.distanceModel;
  55644. serializationObject.isDirectional = this._isDirectional;
  55645. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55646. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55647. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55648. serializationObject.coneOuterGain = this._coneOuterGain;
  55649. }
  55650. return serializationObject;
  55651. };
  55652. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55653. var soundName = parsedSound.name;
  55654. var soundUrl;
  55655. if (parsedSound.url) {
  55656. soundUrl = rootUrl + parsedSound.url;
  55657. }
  55658. else {
  55659. soundUrl = rootUrl + soundName;
  55660. }
  55661. var options = {
  55662. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55663. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55664. rolloffFactor: parsedSound.rolloffFactor,
  55665. refDistance: parsedSound.refDistance,
  55666. distanceModel: parsedSound.distanceModel,
  55667. playbackRate: parsedSound.playbackRate
  55668. };
  55669. var newSound;
  55670. if (!sourceSound) {
  55671. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55672. scene._addPendingData(newSound);
  55673. }
  55674. else {
  55675. var setBufferAndRun = function () {
  55676. if (sourceSound._isReadyToPlay) {
  55677. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55678. newSound._isReadyToPlay = true;
  55679. if (newSound.autoplay) {
  55680. newSound.play();
  55681. }
  55682. }
  55683. else {
  55684. window.setTimeout(setBufferAndRun, 300);
  55685. }
  55686. };
  55687. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55688. setBufferAndRun();
  55689. }
  55690. if (parsedSound.position) {
  55691. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55692. newSound.setPosition(soundPosition);
  55693. }
  55694. if (parsedSound.isDirectional) {
  55695. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55696. if (parsedSound.localDirectionToMesh) {
  55697. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55698. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55699. }
  55700. }
  55701. if (parsedSound.connectedMeshId) {
  55702. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55703. if (connectedMesh) {
  55704. newSound.attachToMesh(connectedMesh);
  55705. }
  55706. }
  55707. return newSound;
  55708. };
  55709. return Sound;
  55710. }());
  55711. BABYLON.Sound = Sound;
  55712. })(BABYLON || (BABYLON = {}));
  55713. //# sourceMappingURL=babylon.sound.js.map
  55714. var BABYLON;
  55715. (function (BABYLON) {
  55716. var SoundTrack = /** @class */ (function () {
  55717. function SoundTrack(scene, options) {
  55718. this.id = -1;
  55719. this._isMainTrack = false;
  55720. this._isInitialized = false;
  55721. this._scene = scene;
  55722. this.soundCollection = new Array();
  55723. this._options = options;
  55724. if (!this._isMainTrack) {
  55725. this._scene.soundTracks.push(this);
  55726. this.id = this._scene.soundTracks.length - 1;
  55727. }
  55728. }
  55729. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55730. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55731. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55732. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55733. if (this._options) {
  55734. if (this._options.volume) {
  55735. this._outputAudioNode.gain.value = this._options.volume;
  55736. }
  55737. if (this._options.mainTrack) {
  55738. this._isMainTrack = this._options.mainTrack;
  55739. }
  55740. }
  55741. this._isInitialized = true;
  55742. }
  55743. };
  55744. SoundTrack.prototype.dispose = function () {
  55745. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  55746. if (this._connectedAnalyser) {
  55747. this._connectedAnalyser.stopDebugCanvas();
  55748. }
  55749. while (this.soundCollection.length) {
  55750. this.soundCollection[0].dispose();
  55751. }
  55752. if (this._outputAudioNode) {
  55753. this._outputAudioNode.disconnect();
  55754. }
  55755. this._outputAudioNode = null;
  55756. }
  55757. };
  55758. SoundTrack.prototype.AddSound = function (sound) {
  55759. if (!this._isInitialized) {
  55760. this._initializeSoundTrackAudioGraph();
  55761. }
  55762. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55763. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55764. }
  55765. if (sound.soundTrackId) {
  55766. if (sound.soundTrackId === -1) {
  55767. this._scene.mainSoundTrack.RemoveSound(sound);
  55768. }
  55769. else {
  55770. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55771. }
  55772. }
  55773. this.soundCollection.push(sound);
  55774. sound.soundTrackId = this.id;
  55775. };
  55776. SoundTrack.prototype.RemoveSound = function (sound) {
  55777. var index = this.soundCollection.indexOf(sound);
  55778. if (index !== -1) {
  55779. this.soundCollection.splice(index, 1);
  55780. }
  55781. };
  55782. SoundTrack.prototype.setVolume = function (newVolume) {
  55783. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55784. this._outputAudioNode.gain.value = newVolume;
  55785. }
  55786. };
  55787. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55788. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55789. for (var i = 0; i < this.soundCollection.length; i++) {
  55790. this.soundCollection[i].switchPanningModelToHRTF();
  55791. }
  55792. }
  55793. };
  55794. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55795. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55796. for (var i = 0; i < this.soundCollection.length; i++) {
  55797. this.soundCollection[i].switchPanningModelToEqualPower();
  55798. }
  55799. }
  55800. };
  55801. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55802. if (this._connectedAnalyser) {
  55803. this._connectedAnalyser.stopDebugCanvas();
  55804. }
  55805. this._connectedAnalyser = analyser;
  55806. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55807. this._outputAudioNode.disconnect();
  55808. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55809. }
  55810. };
  55811. return SoundTrack;
  55812. }());
  55813. BABYLON.SoundTrack = SoundTrack;
  55814. })(BABYLON || (BABYLON = {}));
  55815. //# sourceMappingURL=babylon.soundtrack.js.map
  55816. var BABYLON;
  55817. (function (BABYLON) {
  55818. var Analyser = /** @class */ (function () {
  55819. function Analyser(scene) {
  55820. this.SMOOTHING = 0.75;
  55821. this.FFT_SIZE = 512;
  55822. this.BARGRAPHAMPLITUDE = 256;
  55823. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55824. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55825. this._scene = scene;
  55826. this._audioEngine = BABYLON.Engine.audioEngine;
  55827. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55828. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55829. this._webAudioAnalyser.minDecibels = -140;
  55830. this._webAudioAnalyser.maxDecibels = 0;
  55831. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55832. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55833. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55834. }
  55835. }
  55836. Analyser.prototype.getFrequencyBinCount = function () {
  55837. if (this._audioEngine.canUseWebAudio) {
  55838. return this._webAudioAnalyser.frequencyBinCount;
  55839. }
  55840. else {
  55841. return 0;
  55842. }
  55843. };
  55844. Analyser.prototype.getByteFrequencyData = function () {
  55845. if (this._audioEngine.canUseWebAudio) {
  55846. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55847. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55848. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55849. }
  55850. return this._byteFreqs;
  55851. };
  55852. Analyser.prototype.getByteTimeDomainData = function () {
  55853. if (this._audioEngine.canUseWebAudio) {
  55854. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55855. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55856. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55857. }
  55858. return this._byteTime;
  55859. };
  55860. Analyser.prototype.getFloatFrequencyData = function () {
  55861. if (this._audioEngine.canUseWebAudio) {
  55862. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55863. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55864. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55865. }
  55866. return this._floatFreqs;
  55867. };
  55868. Analyser.prototype.drawDebugCanvas = function () {
  55869. var _this = this;
  55870. if (this._audioEngine.canUseWebAudio) {
  55871. if (!this._debugCanvas) {
  55872. this._debugCanvas = document.createElement("canvas");
  55873. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55874. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55875. this._debugCanvas.style.position = "absolute";
  55876. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55877. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55878. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55879. document.body.appendChild(this._debugCanvas);
  55880. this._registerFunc = function () {
  55881. _this.drawDebugCanvas();
  55882. };
  55883. this._scene.registerBeforeRender(this._registerFunc);
  55884. }
  55885. if (this._registerFunc && this._debugCanvasContext) {
  55886. var workingArray = this.getByteFrequencyData();
  55887. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55888. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55889. // Draw the frequency domain chart.
  55890. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55891. var value = workingArray[i];
  55892. var percent = value / this.BARGRAPHAMPLITUDE;
  55893. var height = this.DEBUGCANVASSIZE.height * percent;
  55894. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55895. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55896. var hue = i / this.getFrequencyBinCount() * 360;
  55897. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55898. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55899. }
  55900. }
  55901. }
  55902. };
  55903. Analyser.prototype.stopDebugCanvas = function () {
  55904. if (this._debugCanvas) {
  55905. if (this._registerFunc) {
  55906. this._scene.unregisterBeforeRender(this._registerFunc);
  55907. this._registerFunc = null;
  55908. }
  55909. document.body.removeChild(this._debugCanvas);
  55910. this._debugCanvas = null;
  55911. this._debugCanvasContext = null;
  55912. }
  55913. };
  55914. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55915. if (this._audioEngine.canUseWebAudio) {
  55916. inputAudioNode.connect(this._webAudioAnalyser);
  55917. this._webAudioAnalyser.connect(outputAudioNode);
  55918. }
  55919. };
  55920. Analyser.prototype.dispose = function () {
  55921. if (this._audioEngine.canUseWebAudio) {
  55922. this._webAudioAnalyser.disconnect();
  55923. }
  55924. };
  55925. return Analyser;
  55926. }());
  55927. BABYLON.Analyser = Analyser;
  55928. })(BABYLON || (BABYLON = {}));
  55929. //# sourceMappingURL=babylon.analyser.js.map
  55930. var BABYLON;
  55931. (function (BABYLON) {
  55932. var CubeTexture = /** @class */ (function (_super) {
  55933. __extends(CubeTexture, _super);
  55934. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55935. if (extensions === void 0) { extensions = null; }
  55936. if (noMipmap === void 0) { noMipmap = false; }
  55937. if (files === void 0) { files = null; }
  55938. if (onLoad === void 0) { onLoad = null; }
  55939. if (onError === void 0) { onError = null; }
  55940. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55941. if (prefiltered === void 0) { prefiltered = false; }
  55942. if (forcedExtension === void 0) { forcedExtension = null; }
  55943. var _this = _super.call(this, scene) || this;
  55944. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55945. /**
  55946. * Gets or sets the center of the bounding box associated with the cube texture
  55947. * It must define where the camera used to render the texture was set
  55948. */
  55949. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  55950. _this.name = rootUrl;
  55951. _this.url = rootUrl;
  55952. _this._noMipmap = noMipmap;
  55953. _this.hasAlpha = false;
  55954. _this._format = format;
  55955. _this._prefiltered = prefiltered;
  55956. _this.isCube = true;
  55957. _this._textureMatrix = BABYLON.Matrix.Identity();
  55958. if (prefiltered) {
  55959. _this.gammaSpace = false;
  55960. }
  55961. if (!rootUrl && !files) {
  55962. return _this;
  55963. }
  55964. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  55965. var lastDot = rootUrl.lastIndexOf(".");
  55966. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  55967. var isDDS = (extension === ".dds");
  55968. if (!files) {
  55969. if (!isDDS && !extensions) {
  55970. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  55971. }
  55972. files = [];
  55973. if (extensions) {
  55974. for (var index = 0; index < extensions.length; index++) {
  55975. files.push(rootUrl + extensions[index]);
  55976. }
  55977. }
  55978. }
  55979. _this._files = files;
  55980. if (!_this._texture) {
  55981. if (!scene.useDelayedTextureLoading) {
  55982. if (prefiltered) {
  55983. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  55984. }
  55985. else {
  55986. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  55987. }
  55988. }
  55989. else {
  55990. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55991. }
  55992. }
  55993. else if (onLoad) {
  55994. if (_this._texture.isReady) {
  55995. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  55996. }
  55997. else {
  55998. _this._texture.onLoadedObservable.add(onLoad);
  55999. }
  56000. }
  56001. return _this;
  56002. }
  56003. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56004. get: function () {
  56005. return this._boundingBoxSize;
  56006. },
  56007. /**
  56008. * Gets or sets the size of the bounding box associated with the cube texture
  56009. * When defined, the cubemap will switch to local mode
  56010. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56011. * @example https://www.babylonjs-playground.com/#RNASML
  56012. */
  56013. set: function (value) {
  56014. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56015. return;
  56016. }
  56017. this._boundingBoxSize = value;
  56018. var scene = this.getScene();
  56019. if (scene) {
  56020. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56021. }
  56022. },
  56023. enumerable: true,
  56024. configurable: true
  56025. });
  56026. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56027. return new CubeTexture("", scene, null, noMipmap, files);
  56028. };
  56029. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56030. if (forcedExtension === void 0) { forcedExtension = null; }
  56031. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56032. };
  56033. // Methods
  56034. CubeTexture.prototype.delayLoad = function () {
  56035. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56036. return;
  56037. }
  56038. var scene = this.getScene();
  56039. if (!scene) {
  56040. return;
  56041. }
  56042. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56043. this._texture = this._getFromCache(this.url, this._noMipmap);
  56044. if (!this._texture) {
  56045. if (this._prefiltered) {
  56046. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56047. }
  56048. else {
  56049. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56050. }
  56051. }
  56052. };
  56053. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56054. return this._textureMatrix;
  56055. };
  56056. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56057. this._textureMatrix = value;
  56058. };
  56059. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56060. var texture = BABYLON.SerializationHelper.Parse(function () {
  56061. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56062. }, parsedTexture, scene);
  56063. // Animations
  56064. if (parsedTexture.animations) {
  56065. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56066. var parsedAnimation = parsedTexture.animations[animationIndex];
  56067. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56068. }
  56069. }
  56070. return texture;
  56071. };
  56072. CubeTexture.prototype.clone = function () {
  56073. var _this = this;
  56074. return BABYLON.SerializationHelper.Clone(function () {
  56075. var scene = _this.getScene();
  56076. if (!scene) {
  56077. return _this;
  56078. }
  56079. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56080. }, this);
  56081. };
  56082. return CubeTexture;
  56083. }(BABYLON.BaseTexture));
  56084. BABYLON.CubeTexture = CubeTexture;
  56085. })(BABYLON || (BABYLON = {}));
  56086. //# sourceMappingURL=babylon.cubeTexture.js.map
  56087. var BABYLON;
  56088. (function (BABYLON) {
  56089. var RenderTargetTexture = /** @class */ (function (_super) {
  56090. __extends(RenderTargetTexture, _super);
  56091. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56092. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56093. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56094. if (isCube === void 0) { isCube = false; }
  56095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56096. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56097. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56098. if (isMulti === void 0) { isMulti = false; }
  56099. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56100. _this.isCube = isCube;
  56101. /**
  56102. * Use this list to define the list of mesh you want to render.
  56103. */
  56104. _this.renderList = new Array();
  56105. _this.renderParticles = true;
  56106. _this.renderSprites = false;
  56107. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56108. _this.ignoreCameraViewport = false;
  56109. // Events
  56110. /**
  56111. * An event triggered when the texture is unbind.
  56112. * @type {BABYLON.Observable}
  56113. */
  56114. _this.onBeforeBindObservable = new BABYLON.Observable();
  56115. /**
  56116. * An event triggered when the texture is unbind.
  56117. * @type {BABYLON.Observable}
  56118. */
  56119. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56120. /**
  56121. * An event triggered before rendering the texture
  56122. * @type {BABYLON.Observable}
  56123. */
  56124. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56125. /**
  56126. * An event triggered after rendering the texture
  56127. * @type {BABYLON.Observable}
  56128. */
  56129. _this.onAfterRenderObservable = new BABYLON.Observable();
  56130. /**
  56131. * An event triggered after the texture clear
  56132. * @type {BABYLON.Observable}
  56133. */
  56134. _this.onClearObservable = new BABYLON.Observable();
  56135. _this._currentRefreshId = -1;
  56136. _this._refreshRate = 1;
  56137. _this._samples = 1;
  56138. /**
  56139. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56140. * It must define where the camera used to render the texture is set
  56141. */
  56142. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56143. scene = _this.getScene();
  56144. if (!scene) {
  56145. return _this;
  56146. }
  56147. _this._engine = scene.getEngine();
  56148. _this.name = name;
  56149. _this.isRenderTarget = true;
  56150. _this._initialSizeParameter = size;
  56151. _this._processSizeParameter(size);
  56152. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56153. });
  56154. _this._generateMipMaps = generateMipMaps ? true : false;
  56155. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56156. // Rendering groups
  56157. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56158. if (isMulti) {
  56159. return _this;
  56160. }
  56161. _this._renderTargetOptions = {
  56162. generateMipMaps: generateMipMaps,
  56163. type: type,
  56164. samplingMode: samplingMode,
  56165. generateDepthBuffer: generateDepthBuffer,
  56166. generateStencilBuffer: generateStencilBuffer
  56167. };
  56168. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56169. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56170. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56171. }
  56172. if (isCube) {
  56173. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56174. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56175. _this._textureMatrix = BABYLON.Matrix.Identity();
  56176. }
  56177. else {
  56178. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56179. }
  56180. return _this;
  56181. }
  56182. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56183. get: function () {
  56184. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56185. },
  56186. enumerable: true,
  56187. configurable: true
  56188. });
  56189. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56190. get: function () {
  56191. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56192. },
  56193. enumerable: true,
  56194. configurable: true
  56195. });
  56196. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56197. get: function () {
  56198. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56199. },
  56200. enumerable: true,
  56201. configurable: true
  56202. });
  56203. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56204. set: function (callback) {
  56205. if (this._onAfterUnbindObserver) {
  56206. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56207. }
  56208. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56209. },
  56210. enumerable: true,
  56211. configurable: true
  56212. });
  56213. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56214. set: function (callback) {
  56215. if (this._onBeforeRenderObserver) {
  56216. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56217. }
  56218. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56219. },
  56220. enumerable: true,
  56221. configurable: true
  56222. });
  56223. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56224. set: function (callback) {
  56225. if (this._onAfterRenderObserver) {
  56226. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56227. }
  56228. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56229. },
  56230. enumerable: true,
  56231. configurable: true
  56232. });
  56233. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56234. set: function (callback) {
  56235. if (this._onClearObserver) {
  56236. this.onClearObservable.remove(this._onClearObserver);
  56237. }
  56238. this._onClearObserver = this.onClearObservable.add(callback);
  56239. },
  56240. enumerable: true,
  56241. configurable: true
  56242. });
  56243. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56244. get: function () {
  56245. return this._renderTargetOptions;
  56246. },
  56247. enumerable: true,
  56248. configurable: true
  56249. });
  56250. RenderTargetTexture.prototype._onRatioRescale = function () {
  56251. if (this._sizeRatio) {
  56252. this.resize(this._initialSizeParameter);
  56253. }
  56254. };
  56255. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56256. get: function () {
  56257. return this._boundingBoxSize;
  56258. },
  56259. /**
  56260. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56261. * When defined, the cubemap will switch to local mode
  56262. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56263. * @example https://www.babylonjs-playground.com/#RNASML
  56264. */
  56265. set: function (value) {
  56266. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56267. return;
  56268. }
  56269. this._boundingBoxSize = value;
  56270. var scene = this.getScene();
  56271. if (scene) {
  56272. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56273. }
  56274. },
  56275. enumerable: true,
  56276. configurable: true
  56277. });
  56278. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56279. if (size.ratio) {
  56280. this._sizeRatio = size.ratio;
  56281. this._size = {
  56282. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56283. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56284. };
  56285. }
  56286. else {
  56287. this._size = size;
  56288. }
  56289. };
  56290. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56291. get: function () {
  56292. return this._samples;
  56293. },
  56294. set: function (value) {
  56295. if (this._samples === value) {
  56296. return;
  56297. }
  56298. var scene = this.getScene();
  56299. if (!scene) {
  56300. return;
  56301. }
  56302. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56303. },
  56304. enumerable: true,
  56305. configurable: true
  56306. });
  56307. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56308. this._currentRefreshId = -1;
  56309. };
  56310. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56311. get: function () {
  56312. return this._refreshRate;
  56313. },
  56314. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56315. set: function (value) {
  56316. this._refreshRate = value;
  56317. this.resetRefreshCounter();
  56318. },
  56319. enumerable: true,
  56320. configurable: true
  56321. });
  56322. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56323. if (!this._postProcessManager) {
  56324. var scene = this.getScene();
  56325. if (!scene) {
  56326. return;
  56327. }
  56328. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56329. this._postProcesses = new Array();
  56330. }
  56331. this._postProcesses.push(postProcess);
  56332. this._postProcesses[0].autoClear = false;
  56333. };
  56334. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56335. if (!this._postProcesses) {
  56336. return;
  56337. }
  56338. if (dispose) {
  56339. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56340. var postProcess = _a[_i];
  56341. postProcess.dispose();
  56342. }
  56343. }
  56344. this._postProcesses = [];
  56345. };
  56346. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56347. if (!this._postProcesses) {
  56348. return;
  56349. }
  56350. var index = this._postProcesses.indexOf(postProcess);
  56351. if (index === -1) {
  56352. return;
  56353. }
  56354. this._postProcesses.splice(index, 1);
  56355. if (this._postProcesses.length > 0) {
  56356. this._postProcesses[0].autoClear = false;
  56357. }
  56358. };
  56359. RenderTargetTexture.prototype._shouldRender = function () {
  56360. if (this._currentRefreshId === -1) {
  56361. this._currentRefreshId = 1;
  56362. return true;
  56363. }
  56364. if (this.refreshRate === this._currentRefreshId) {
  56365. this._currentRefreshId = 1;
  56366. return true;
  56367. }
  56368. this._currentRefreshId++;
  56369. return false;
  56370. };
  56371. RenderTargetTexture.prototype.getRenderSize = function () {
  56372. if (this._size.width) {
  56373. return this._size.width;
  56374. }
  56375. return this._size;
  56376. };
  56377. RenderTargetTexture.prototype.getRenderWidth = function () {
  56378. if (this._size.width) {
  56379. return this._size.width;
  56380. }
  56381. return this._size;
  56382. };
  56383. RenderTargetTexture.prototype.getRenderHeight = function () {
  56384. if (this._size.width) {
  56385. return this._size.height;
  56386. }
  56387. return this._size;
  56388. };
  56389. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56390. get: function () {
  56391. return true;
  56392. },
  56393. enumerable: true,
  56394. configurable: true
  56395. });
  56396. RenderTargetTexture.prototype.scale = function (ratio) {
  56397. var newSize = this.getRenderSize() * ratio;
  56398. this.resize(newSize);
  56399. };
  56400. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56401. if (this.isCube) {
  56402. return this._textureMatrix;
  56403. }
  56404. return _super.prototype.getReflectionTextureMatrix.call(this);
  56405. };
  56406. RenderTargetTexture.prototype.resize = function (size) {
  56407. this.releaseInternalTexture();
  56408. var scene = this.getScene();
  56409. if (!scene) {
  56410. return;
  56411. }
  56412. this._processSizeParameter(size);
  56413. if (this.isCube) {
  56414. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56415. }
  56416. else {
  56417. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56418. }
  56419. };
  56420. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56421. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56422. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56423. var scene = this.getScene();
  56424. if (!scene) {
  56425. return;
  56426. }
  56427. var engine = scene.getEngine();
  56428. if (this.useCameraPostProcesses !== undefined) {
  56429. useCameraPostProcess = this.useCameraPostProcesses;
  56430. }
  56431. if (this._waitingRenderList) {
  56432. this.renderList = [];
  56433. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56434. var id = this._waitingRenderList[index];
  56435. var mesh_1 = scene.getMeshByID(id);
  56436. if (mesh_1) {
  56437. this.renderList.push(mesh_1);
  56438. }
  56439. }
  56440. delete this._waitingRenderList;
  56441. }
  56442. // Is predicate defined?
  56443. if (this.renderListPredicate) {
  56444. if (this.renderList) {
  56445. this.renderList.splice(0); // Clear previous renderList
  56446. }
  56447. else {
  56448. this.renderList = [];
  56449. }
  56450. var scene = this.getScene();
  56451. if (!scene) {
  56452. return;
  56453. }
  56454. var sceneMeshes = scene.meshes;
  56455. for (var index = 0; index < sceneMeshes.length; index++) {
  56456. var mesh = sceneMeshes[index];
  56457. if (this.renderListPredicate(mesh)) {
  56458. this.renderList.push(mesh);
  56459. }
  56460. }
  56461. }
  56462. this.onBeforeBindObservable.notifyObservers(this);
  56463. // Set custom projection.
  56464. // Needs to be before binding to prevent changing the aspect ratio.
  56465. var camera;
  56466. if (this.activeCamera) {
  56467. camera = this.activeCamera;
  56468. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56469. if (this.activeCamera !== scene.activeCamera) {
  56470. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56471. }
  56472. }
  56473. else {
  56474. camera = scene.activeCamera;
  56475. if (camera) {
  56476. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56477. }
  56478. }
  56479. // Prepare renderingManager
  56480. this._renderingManager.reset();
  56481. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56482. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56483. var sceneRenderId = scene.getRenderId();
  56484. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56485. var mesh = currentRenderList[meshIndex];
  56486. if (mesh) {
  56487. if (!mesh.isReady()) {
  56488. // Reset _currentRefreshId
  56489. this.resetRefreshCounter();
  56490. continue;
  56491. }
  56492. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56493. var isMasked = void 0;
  56494. if (!this.renderList && camera) {
  56495. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56496. }
  56497. else {
  56498. isMasked = false;
  56499. }
  56500. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56501. mesh._activate(sceneRenderId);
  56502. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56503. var subMesh = mesh.subMeshes[subIndex];
  56504. scene._activeIndices.addCount(subMesh.indexCount, false);
  56505. this._renderingManager.dispatch(subMesh, mesh);
  56506. }
  56507. }
  56508. }
  56509. }
  56510. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56511. var particleSystem = scene.particleSystems[particleIndex];
  56512. var emitter = particleSystem.emitter;
  56513. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56514. continue;
  56515. }
  56516. if (currentRenderList.indexOf(emitter) >= 0) {
  56517. this._renderingManager.dispatchParticles(particleSystem);
  56518. }
  56519. }
  56520. if (this.isCube) {
  56521. for (var face = 0; face < 6; face++) {
  56522. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56523. scene.incrementRenderId();
  56524. scene.resetCachedMaterial();
  56525. }
  56526. }
  56527. else {
  56528. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56529. }
  56530. this.onAfterUnbindObservable.notifyObservers(this);
  56531. if (scene.activeCamera) {
  56532. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56533. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56534. }
  56535. engine.setViewport(scene.activeCamera.viewport);
  56536. }
  56537. scene.resetCachedMaterial();
  56538. };
  56539. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56540. var minimum = 128;
  56541. var x = renderDimension * scale;
  56542. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56543. // Ensure we don't exceed the render dimension (while staying POT)
  56544. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56545. };
  56546. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56547. var _this = this;
  56548. if (!this._texture) {
  56549. return;
  56550. }
  56551. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56552. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56553. });
  56554. };
  56555. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56556. var scene = this.getScene();
  56557. if (!scene) {
  56558. return;
  56559. }
  56560. var engine = scene.getEngine();
  56561. if (!this._texture) {
  56562. return;
  56563. }
  56564. // Bind
  56565. if (this._postProcessManager) {
  56566. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56567. }
  56568. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56569. if (this._texture) {
  56570. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56571. }
  56572. }
  56573. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56574. // Clear
  56575. if (this.onClearObservable.hasObservers()) {
  56576. this.onClearObservable.notifyObservers(engine);
  56577. }
  56578. else {
  56579. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56580. }
  56581. if (!this._doNotChangeAspectRatio) {
  56582. scene.updateTransformMatrix(true);
  56583. }
  56584. // Render
  56585. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56586. if (this._postProcessManager) {
  56587. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56588. }
  56589. else if (useCameraPostProcess) {
  56590. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56591. }
  56592. if (!this._doNotChangeAspectRatio) {
  56593. scene.updateTransformMatrix(true);
  56594. }
  56595. // Dump ?
  56596. if (dumpForDebug) {
  56597. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56598. }
  56599. // Unbind
  56600. if (!this.isCube || faceIndex === 5) {
  56601. if (this.isCube) {
  56602. if (faceIndex === 5) {
  56603. engine.generateMipMapsForCubemap(this._texture);
  56604. }
  56605. }
  56606. this.unbindFrameBuffer(engine, faceIndex);
  56607. }
  56608. else {
  56609. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56610. }
  56611. };
  56612. /**
  56613. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56614. * This allowed control for front to back rendering or reversly depending of the special needs.
  56615. *
  56616. * @param renderingGroupId The rendering group id corresponding to its index
  56617. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56618. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56619. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56620. */
  56621. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56622. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56623. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56624. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56625. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56626. };
  56627. /**
  56628. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56629. *
  56630. * @param renderingGroupId The rendering group id corresponding to its index
  56631. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56632. */
  56633. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56634. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56635. };
  56636. RenderTargetTexture.prototype.clone = function () {
  56637. var textureSize = this.getSize();
  56638. 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);
  56639. // Base texture
  56640. newTexture.hasAlpha = this.hasAlpha;
  56641. newTexture.level = this.level;
  56642. // RenderTarget Texture
  56643. newTexture.coordinatesMode = this.coordinatesMode;
  56644. if (this.renderList) {
  56645. newTexture.renderList = this.renderList.slice(0);
  56646. }
  56647. return newTexture;
  56648. };
  56649. RenderTargetTexture.prototype.serialize = function () {
  56650. if (!this.name) {
  56651. return null;
  56652. }
  56653. var serializationObject = _super.prototype.serialize.call(this);
  56654. serializationObject.renderTargetSize = this.getRenderSize();
  56655. serializationObject.renderList = [];
  56656. if (this.renderList) {
  56657. for (var index = 0; index < this.renderList.length; index++) {
  56658. serializationObject.renderList.push(this.renderList[index].id);
  56659. }
  56660. }
  56661. return serializationObject;
  56662. };
  56663. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56664. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56665. var objBuffer = this.getInternalTexture();
  56666. var scene = this.getScene();
  56667. if (objBuffer && scene) {
  56668. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56669. }
  56670. };
  56671. RenderTargetTexture.prototype.dispose = function () {
  56672. if (this._postProcessManager) {
  56673. this._postProcessManager.dispose();
  56674. this._postProcessManager = null;
  56675. }
  56676. this.clearPostProcesses(true);
  56677. if (this._resizeObserver) {
  56678. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56679. this._resizeObserver = null;
  56680. }
  56681. this.renderList = null;
  56682. // Remove from custom render targets
  56683. var scene = this.getScene();
  56684. if (!scene) {
  56685. return;
  56686. }
  56687. var index = scene.customRenderTargets.indexOf(this);
  56688. if (index >= 0) {
  56689. scene.customRenderTargets.splice(index, 1);
  56690. }
  56691. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56692. var camera = _a[_i];
  56693. index = camera.customRenderTargets.indexOf(this);
  56694. if (index >= 0) {
  56695. camera.customRenderTargets.splice(index, 1);
  56696. }
  56697. }
  56698. _super.prototype.dispose.call(this);
  56699. };
  56700. RenderTargetTexture.prototype._rebuild = function () {
  56701. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56702. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56703. }
  56704. if (this._postProcessManager) {
  56705. this._postProcessManager._rebuild();
  56706. }
  56707. };
  56708. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56709. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56710. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56711. return RenderTargetTexture;
  56712. }(BABYLON.Texture));
  56713. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56714. })(BABYLON || (BABYLON = {}));
  56715. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56716. var BABYLON;
  56717. (function (BABYLON) {
  56718. ;
  56719. var MultiRenderTarget = /** @class */ (function (_super) {
  56720. __extends(MultiRenderTarget, _super);
  56721. function MultiRenderTarget(name, size, count, scene, options) {
  56722. var _this = this;
  56723. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56724. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56725. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56726. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56727. _this._engine = scene.getEngine();
  56728. if (!_this.isSupported) {
  56729. _this.dispose();
  56730. return;
  56731. }
  56732. var types = [];
  56733. var samplingModes = [];
  56734. for (var i = 0; i < count; i++) {
  56735. if (options && options.types && options.types[i] !== undefined) {
  56736. types.push(options.types[i]);
  56737. }
  56738. else {
  56739. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56740. }
  56741. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56742. samplingModes.push(options.samplingModes[i]);
  56743. }
  56744. else {
  56745. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56746. }
  56747. }
  56748. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56749. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56750. _this._size = size;
  56751. _this._multiRenderTargetOptions = {
  56752. samplingModes: samplingModes,
  56753. generateMipMaps: generateMipMaps,
  56754. generateDepthBuffer: generateDepthBuffer,
  56755. generateStencilBuffer: generateStencilBuffer,
  56756. generateDepthTexture: generateDepthTexture,
  56757. types: types,
  56758. textureCount: count
  56759. };
  56760. _this._createInternalTextures();
  56761. _this._createTextures();
  56762. return _this;
  56763. }
  56764. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56765. get: function () {
  56766. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56767. },
  56768. enumerable: true,
  56769. configurable: true
  56770. });
  56771. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56772. get: function () {
  56773. return this._textures;
  56774. },
  56775. enumerable: true,
  56776. configurable: true
  56777. });
  56778. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56779. get: function () {
  56780. return this._textures[this._textures.length - 1];
  56781. },
  56782. enumerable: true,
  56783. configurable: true
  56784. });
  56785. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56786. set: function (wrap) {
  56787. if (this._textures) {
  56788. for (var i = 0; i < this._textures.length; i++) {
  56789. this._textures[i].wrapU = wrap;
  56790. }
  56791. }
  56792. },
  56793. enumerable: true,
  56794. configurable: true
  56795. });
  56796. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56797. set: function (wrap) {
  56798. if (this._textures) {
  56799. for (var i = 0; i < this._textures.length; i++) {
  56800. this._textures[i].wrapV = wrap;
  56801. }
  56802. }
  56803. },
  56804. enumerable: true,
  56805. configurable: true
  56806. });
  56807. MultiRenderTarget.prototype._rebuild = function () {
  56808. this.releaseInternalTextures();
  56809. this._createInternalTextures();
  56810. for (var i = 0; i < this._internalTextures.length; i++) {
  56811. var texture = this._textures[i];
  56812. texture._texture = this._internalTextures[i];
  56813. }
  56814. // Keeps references to frame buffer and stencil/depth buffer
  56815. this._texture = this._internalTextures[0];
  56816. };
  56817. MultiRenderTarget.prototype._createInternalTextures = function () {
  56818. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56819. };
  56820. MultiRenderTarget.prototype._createTextures = function () {
  56821. this._textures = [];
  56822. for (var i = 0; i < this._internalTextures.length; i++) {
  56823. var texture = new BABYLON.Texture(null, this.getScene());
  56824. texture._texture = this._internalTextures[i];
  56825. this._textures.push(texture);
  56826. }
  56827. // Keeps references to frame buffer and stencil/depth buffer
  56828. this._texture = this._internalTextures[0];
  56829. };
  56830. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56831. get: function () {
  56832. return this._samples;
  56833. },
  56834. set: function (value) {
  56835. if (this._samples === value) {
  56836. return;
  56837. }
  56838. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56839. },
  56840. enumerable: true,
  56841. configurable: true
  56842. });
  56843. MultiRenderTarget.prototype.resize = function (size) {
  56844. this.releaseInternalTextures();
  56845. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56846. this._createInternalTextures();
  56847. };
  56848. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56849. var _this = this;
  56850. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56851. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56852. });
  56853. };
  56854. MultiRenderTarget.prototype.dispose = function () {
  56855. this.releaseInternalTextures();
  56856. _super.prototype.dispose.call(this);
  56857. };
  56858. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56859. if (!this._internalTextures) {
  56860. return;
  56861. }
  56862. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56863. if (this._internalTextures[i] !== undefined) {
  56864. this._internalTextures[i].dispose();
  56865. this._internalTextures.splice(i, 1);
  56866. }
  56867. }
  56868. };
  56869. return MultiRenderTarget;
  56870. }(BABYLON.RenderTargetTexture));
  56871. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56872. })(BABYLON || (BABYLON = {}));
  56873. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56874. var BABYLON;
  56875. (function (BABYLON) {
  56876. var MirrorTexture = /** @class */ (function (_super) {
  56877. __extends(MirrorTexture, _super);
  56878. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56879. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56880. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56881. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56882. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56883. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56884. _this._transformMatrix = BABYLON.Matrix.Zero();
  56885. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56886. _this._adaptiveBlurKernel = 0;
  56887. _this._blurKernelX = 0;
  56888. _this._blurKernelY = 0;
  56889. _this._blurRatio = 1.0;
  56890. _this.ignoreCameraViewport = true;
  56891. _this.onBeforeRenderObservable.add(function () {
  56892. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56893. _this._savedViewMatrix = scene.getViewMatrix();
  56894. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56895. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56896. scene.clipPlane = _this.mirrorPlane;
  56897. scene.getEngine().cullBackFaces = false;
  56898. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56899. });
  56900. _this.onAfterRenderObservable.add(function () {
  56901. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56902. scene.getEngine().cullBackFaces = true;
  56903. scene._mirroredCameraPosition = null;
  56904. delete scene.clipPlane;
  56905. });
  56906. return _this;
  56907. }
  56908. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56909. get: function () {
  56910. return this._blurRatio;
  56911. },
  56912. set: function (value) {
  56913. if (this._blurRatio === value) {
  56914. return;
  56915. }
  56916. this._blurRatio = value;
  56917. this._preparePostProcesses();
  56918. },
  56919. enumerable: true,
  56920. configurable: true
  56921. });
  56922. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56923. set: function (value) {
  56924. this._adaptiveBlurKernel = value;
  56925. this._autoComputeBlurKernel();
  56926. },
  56927. enumerable: true,
  56928. configurable: true
  56929. });
  56930. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56931. set: function (value) {
  56932. this.blurKernelX = value;
  56933. this.blurKernelY = value;
  56934. },
  56935. enumerable: true,
  56936. configurable: true
  56937. });
  56938. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  56939. get: function () {
  56940. return this._blurKernelX;
  56941. },
  56942. set: function (value) {
  56943. if (this._blurKernelX === value) {
  56944. return;
  56945. }
  56946. this._blurKernelX = value;
  56947. this._preparePostProcesses();
  56948. },
  56949. enumerable: true,
  56950. configurable: true
  56951. });
  56952. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  56953. get: function () {
  56954. return this._blurKernelY;
  56955. },
  56956. set: function (value) {
  56957. if (this._blurKernelY === value) {
  56958. return;
  56959. }
  56960. this._blurKernelY = value;
  56961. this._preparePostProcesses();
  56962. },
  56963. enumerable: true,
  56964. configurable: true
  56965. });
  56966. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  56967. var engine = this.getScene().getEngine();
  56968. var dw = this.getRenderWidth() / engine.getRenderWidth();
  56969. var dh = this.getRenderHeight() / engine.getRenderHeight();
  56970. this.blurKernelX = this._adaptiveBlurKernel * dw;
  56971. this.blurKernelY = this._adaptiveBlurKernel * dh;
  56972. };
  56973. MirrorTexture.prototype._onRatioRescale = function () {
  56974. if (this._sizeRatio) {
  56975. this.resize(this._initialSizeParameter);
  56976. if (!this._adaptiveBlurKernel) {
  56977. this._preparePostProcesses();
  56978. }
  56979. }
  56980. if (this._adaptiveBlurKernel) {
  56981. this._autoComputeBlurKernel();
  56982. }
  56983. };
  56984. MirrorTexture.prototype._preparePostProcesses = function () {
  56985. this.clearPostProcesses(true);
  56986. if (this._blurKernelX && this._blurKernelY) {
  56987. var engine = this.getScene().getEngine();
  56988. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56989. 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);
  56990. this._blurX.autoClear = false;
  56991. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  56992. this._blurX.inputTexture = this._texture;
  56993. }
  56994. else {
  56995. this._blurX.alwaysForcePOT = true;
  56996. }
  56997. 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);
  56998. this._blurY.autoClear = false;
  56999. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57000. this.addPostProcess(this._blurX);
  57001. this.addPostProcess(this._blurY);
  57002. }
  57003. else {
  57004. if (this._blurY) {
  57005. this.removePostProcess(this._blurY);
  57006. this._blurY.dispose();
  57007. this._blurY = null;
  57008. }
  57009. if (this._blurX) {
  57010. this.removePostProcess(this._blurX);
  57011. this._blurX.dispose();
  57012. this._blurX = null;
  57013. }
  57014. }
  57015. };
  57016. MirrorTexture.prototype.clone = function () {
  57017. var scene = this.getScene();
  57018. if (!scene) {
  57019. return this;
  57020. }
  57021. var textureSize = this.getSize();
  57022. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57023. // Base texture
  57024. newTexture.hasAlpha = this.hasAlpha;
  57025. newTexture.level = this.level;
  57026. // Mirror Texture
  57027. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57028. if (this.renderList) {
  57029. newTexture.renderList = this.renderList.slice(0);
  57030. }
  57031. return newTexture;
  57032. };
  57033. MirrorTexture.prototype.serialize = function () {
  57034. if (!this.name) {
  57035. return null;
  57036. }
  57037. var serializationObject = _super.prototype.serialize.call(this);
  57038. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57039. return serializationObject;
  57040. };
  57041. return MirrorTexture;
  57042. }(BABYLON.RenderTargetTexture));
  57043. BABYLON.MirrorTexture = MirrorTexture;
  57044. })(BABYLON || (BABYLON = {}));
  57045. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57046. var BABYLON;
  57047. (function (BABYLON) {
  57048. /**
  57049. * Creates a refraction texture used by refraction channel of the standard material.
  57050. * @param name the texture name
  57051. * @param size size of the underlying texture
  57052. * @param scene root scene
  57053. */
  57054. var RefractionTexture = /** @class */ (function (_super) {
  57055. __extends(RefractionTexture, _super);
  57056. function RefractionTexture(name, size, scene, generateMipMaps) {
  57057. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57058. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57059. _this.depth = 2.0;
  57060. _this.onBeforeRenderObservable.add(function () {
  57061. scene.clipPlane = _this.refractionPlane;
  57062. });
  57063. _this.onAfterRenderObservable.add(function () {
  57064. delete scene.clipPlane;
  57065. });
  57066. return _this;
  57067. }
  57068. RefractionTexture.prototype.clone = function () {
  57069. var scene = this.getScene();
  57070. if (!scene) {
  57071. return this;
  57072. }
  57073. var textureSize = this.getSize();
  57074. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57075. // Base texture
  57076. newTexture.hasAlpha = this.hasAlpha;
  57077. newTexture.level = this.level;
  57078. // Refraction Texture
  57079. newTexture.refractionPlane = this.refractionPlane.clone();
  57080. if (this.renderList) {
  57081. newTexture.renderList = this.renderList.slice(0);
  57082. }
  57083. newTexture.depth = this.depth;
  57084. return newTexture;
  57085. };
  57086. RefractionTexture.prototype.serialize = function () {
  57087. if (!this.name) {
  57088. return null;
  57089. }
  57090. var serializationObject = _super.prototype.serialize.call(this);
  57091. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57092. serializationObject.depth = this.depth;
  57093. return serializationObject;
  57094. };
  57095. return RefractionTexture;
  57096. }(BABYLON.RenderTargetTexture));
  57097. BABYLON.RefractionTexture = RefractionTexture;
  57098. })(BABYLON || (BABYLON = {}));
  57099. //# sourceMappingURL=babylon.refractionTexture.js.map
  57100. var BABYLON;
  57101. (function (BABYLON) {
  57102. var DynamicTexture = /** @class */ (function (_super) {
  57103. __extends(DynamicTexture, _super);
  57104. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57105. if (scene === void 0) { scene = null; }
  57106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57107. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57108. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57109. _this.name = name;
  57110. _this._engine = _this.getScene().getEngine();
  57111. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57112. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57113. _this._generateMipMaps = generateMipMaps;
  57114. if (options.getContext) {
  57115. _this._canvas = options;
  57116. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57117. }
  57118. else {
  57119. _this._canvas = document.createElement("canvas");
  57120. if (options.width) {
  57121. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57122. }
  57123. else {
  57124. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57125. }
  57126. }
  57127. var textureSize = _this.getSize();
  57128. _this._canvas.width = textureSize.width;
  57129. _this._canvas.height = textureSize.height;
  57130. _this._context = _this._canvas.getContext("2d");
  57131. return _this;
  57132. }
  57133. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57134. get: function () {
  57135. return true;
  57136. },
  57137. enumerable: true,
  57138. configurable: true
  57139. });
  57140. DynamicTexture.prototype._recreate = function (textureSize) {
  57141. this._canvas.width = textureSize.width;
  57142. this._canvas.height = textureSize.height;
  57143. this.releaseInternalTexture();
  57144. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57145. };
  57146. DynamicTexture.prototype.scale = function (ratio) {
  57147. var textureSize = this.getSize();
  57148. textureSize.width *= ratio;
  57149. textureSize.height *= ratio;
  57150. this._recreate(textureSize);
  57151. };
  57152. DynamicTexture.prototype.scaleTo = function (width, height) {
  57153. var textureSize = this.getSize();
  57154. textureSize.width = width;
  57155. textureSize.height = height;
  57156. this._recreate(textureSize);
  57157. };
  57158. DynamicTexture.prototype.getContext = function () {
  57159. return this._context;
  57160. };
  57161. DynamicTexture.prototype.clear = function () {
  57162. var size = this.getSize();
  57163. this._context.fillRect(0, 0, size.width, size.height);
  57164. };
  57165. DynamicTexture.prototype.update = function (invertY) {
  57166. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57167. };
  57168. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57169. if (update === void 0) { update = true; }
  57170. var size = this.getSize();
  57171. if (clearColor) {
  57172. this._context.fillStyle = clearColor;
  57173. this._context.fillRect(0, 0, size.width, size.height);
  57174. }
  57175. this._context.font = font;
  57176. if (x === null || x === undefined) {
  57177. var textSize = this._context.measureText(text);
  57178. x = (size.width - textSize.width) / 2;
  57179. }
  57180. if (y === null || y === undefined) {
  57181. var fontSize = parseInt((font.replace(/\D/g, '')));
  57182. ;
  57183. y = (size.height / 2) + (fontSize / 3.65);
  57184. }
  57185. this._context.fillStyle = color;
  57186. this._context.fillText(text, x, y);
  57187. if (update) {
  57188. this.update(invertY);
  57189. }
  57190. };
  57191. DynamicTexture.prototype.clone = function () {
  57192. var scene = this.getScene();
  57193. if (!scene) {
  57194. return this;
  57195. }
  57196. var textureSize = this.getSize();
  57197. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57198. // Base texture
  57199. newTexture.hasAlpha = this.hasAlpha;
  57200. newTexture.level = this.level;
  57201. // Dynamic Texture
  57202. newTexture.wrapU = this.wrapU;
  57203. newTexture.wrapV = this.wrapV;
  57204. return newTexture;
  57205. };
  57206. DynamicTexture.prototype._rebuild = function () {
  57207. this.update();
  57208. };
  57209. return DynamicTexture;
  57210. }(BABYLON.Texture));
  57211. BABYLON.DynamicTexture = DynamicTexture;
  57212. })(BABYLON || (BABYLON = {}));
  57213. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57214. var BABYLON;
  57215. (function (BABYLON) {
  57216. var VideoTexture = /** @class */ (function (_super) {
  57217. __extends(VideoTexture, _super);
  57218. /**
  57219. * Creates a video texture.
  57220. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57221. * @param {string | null} name optional name, will detect from video source, if not defined
  57222. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57223. * @param {BABYLON.Scene} scene is obviously the current scene.
  57224. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57225. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57226. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57227. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57228. */
  57229. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57230. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57231. if (invertY === void 0) { invertY = false; }
  57232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57233. if (settings === void 0) { settings = {
  57234. autoPlay: true,
  57235. loop: true,
  57236. autoUpdateTexture: true,
  57237. }; }
  57238. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57239. _this._createInternalTexture = function () {
  57240. if (_this._texture != null) {
  57241. return;
  57242. }
  57243. if (!_this._engine.needPOTTextures ||
  57244. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57245. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57246. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57247. }
  57248. else {
  57249. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57250. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57251. _this._generateMipMaps = false;
  57252. }
  57253. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57254. _this._texture.isReady = true;
  57255. _this._updateInternalTexture();
  57256. };
  57257. _this.reset = function () {
  57258. if (_this._texture == null) {
  57259. return;
  57260. }
  57261. _this._texture.dispose();
  57262. _this._texture = null;
  57263. };
  57264. _this._updateInternalTexture = function (e) {
  57265. if (_this._texture == null || !_this._texture.isReady) {
  57266. return;
  57267. }
  57268. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57269. return;
  57270. }
  57271. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57272. };
  57273. _this._engine = _this.getScene().getEngine();
  57274. _this._generateMipMaps = generateMipMaps;
  57275. _this._samplingMode = samplingMode;
  57276. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57277. _this.name = name || _this._getName(src);
  57278. _this.video = _this._getVideo(src);
  57279. if (settings.autoPlay !== undefined) {
  57280. _this.video.autoplay = settings.autoPlay;
  57281. }
  57282. if (settings.loop !== undefined) {
  57283. _this.video.loop = settings.loop;
  57284. }
  57285. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57286. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57287. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57288. _this.video.addEventListener("emptied", _this.reset);
  57289. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57290. _this._createInternalTexture();
  57291. }
  57292. return _this;
  57293. }
  57294. VideoTexture.prototype._getName = function (src) {
  57295. if (src instanceof HTMLVideoElement) {
  57296. return src.currentSrc;
  57297. }
  57298. if (typeof src === "object") {
  57299. return src.toString();
  57300. }
  57301. return src;
  57302. };
  57303. ;
  57304. VideoTexture.prototype._getVideo = function (src) {
  57305. if (src instanceof HTMLVideoElement) {
  57306. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57307. return src;
  57308. }
  57309. var video = document.createElement("video");
  57310. if (typeof src === "string") {
  57311. BABYLON.Tools.SetCorsBehavior(src, video);
  57312. video.src = src;
  57313. }
  57314. else {
  57315. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57316. src.forEach(function (url) {
  57317. var source = document.createElement("source");
  57318. source.src = url;
  57319. video.appendChild(source);
  57320. });
  57321. }
  57322. return video;
  57323. };
  57324. ;
  57325. /**
  57326. * Internal method to initiate `update`.
  57327. */
  57328. VideoTexture.prototype._rebuild = function () {
  57329. this.update();
  57330. };
  57331. /**
  57332. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57333. */
  57334. VideoTexture.prototype.update = function () {
  57335. if (!this.autoUpdateTexture) {
  57336. // Expecting user to call `updateTexture` manually
  57337. return;
  57338. }
  57339. this.updateTexture(true);
  57340. };
  57341. /**
  57342. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57343. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57344. */
  57345. VideoTexture.prototype.updateTexture = function (isVisible) {
  57346. if (!isVisible) {
  57347. return;
  57348. }
  57349. if (this.video.paused) {
  57350. return;
  57351. }
  57352. this._updateInternalTexture();
  57353. };
  57354. /**
  57355. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57356. * @param url New url.
  57357. */
  57358. VideoTexture.prototype.updateURL = function (url) {
  57359. this.video.src = url;
  57360. };
  57361. VideoTexture.prototype.dispose = function () {
  57362. _super.prototype.dispose.call(this);
  57363. this.video.removeEventListener("canplay", this._createInternalTexture);
  57364. this.video.removeEventListener("paused", this._updateInternalTexture);
  57365. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57366. this.video.removeEventListener("emptied", this.reset);
  57367. };
  57368. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57369. var video = document.createElement("video");
  57370. var constraintsDeviceId;
  57371. if (constraints && constraints.deviceId) {
  57372. constraintsDeviceId = {
  57373. exact: constraints.deviceId,
  57374. };
  57375. }
  57376. navigator.getUserMedia =
  57377. navigator.getUserMedia ||
  57378. navigator.webkitGetUserMedia ||
  57379. navigator.mozGetUserMedia ||
  57380. navigator.msGetUserMedia;
  57381. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57382. if (navigator.getUserMedia) {
  57383. navigator.getUserMedia({
  57384. video: {
  57385. deviceId: constraintsDeviceId,
  57386. width: {
  57387. min: (constraints && constraints.minWidth) || 256,
  57388. max: (constraints && constraints.maxWidth) || 640,
  57389. },
  57390. height: {
  57391. min: (constraints && constraints.minHeight) || 256,
  57392. max: (constraints && constraints.maxHeight) || 480,
  57393. },
  57394. },
  57395. }, function (stream) {
  57396. if (video.mozSrcObject !== undefined) {
  57397. // hack for Firefox < 19
  57398. video.mozSrcObject = stream;
  57399. }
  57400. else {
  57401. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57402. }
  57403. video.play();
  57404. if (onReady) {
  57405. onReady(new VideoTexture("video", video, scene, true, true));
  57406. }
  57407. }, function (e) {
  57408. BABYLON.Tools.Error(e.name);
  57409. });
  57410. }
  57411. };
  57412. return VideoTexture;
  57413. }(BABYLON.Texture));
  57414. BABYLON.VideoTexture = VideoTexture;
  57415. })(BABYLON || (BABYLON = {}));
  57416. //# sourceMappingURL=babylon.videoTexture.js.map
  57417. var BABYLON;
  57418. (function (BABYLON) {
  57419. var RawTexture = /** @class */ (function (_super) {
  57420. __extends(RawTexture, _super);
  57421. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57422. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57423. if (invertY === void 0) { invertY = false; }
  57424. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57425. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57426. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57427. _this.format = format;
  57428. _this._engine = scene.getEngine();
  57429. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57430. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57431. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57432. return _this;
  57433. }
  57434. RawTexture.prototype.update = function (data) {
  57435. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57436. };
  57437. // Statics
  57438. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57439. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57440. if (invertY === void 0) { invertY = false; }
  57441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57442. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57443. };
  57444. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57445. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57446. if (invertY === void 0) { invertY = false; }
  57447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57448. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57449. };
  57450. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57451. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57452. if (invertY === void 0) { invertY = false; }
  57453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57454. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57455. };
  57456. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57457. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57458. if (invertY === void 0) { invertY = false; }
  57459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57460. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57461. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57462. };
  57463. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57464. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57465. if (invertY === void 0) { invertY = false; }
  57466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57467. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57468. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57469. };
  57470. return RawTexture;
  57471. }(BABYLON.Texture));
  57472. BABYLON.RawTexture = RawTexture;
  57473. })(BABYLON || (BABYLON = {}));
  57474. //# sourceMappingURL=babylon.rawTexture.js.map
  57475. var BABYLON;
  57476. (function (BABYLON) {
  57477. /**
  57478. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57479. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57480. */
  57481. var PostProcess = /** @class */ (function () {
  57482. /**
  57483. * Creates a new instance of @see PostProcess
  57484. * @param name The name of the PostProcess.
  57485. * @param fragmentUrl The url of the fragment shader to be used.
  57486. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57487. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57488. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57489. * @param camera The camera to apply the render pass to.
  57490. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57491. * @param engine The engine which the post process will be applied. (default: current engine)
  57492. * @param reusable If the post process can be reused on the same frame. (default: false)
  57493. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57494. * @param textureType Type of textures used when performing the post process. (default: 0)
  57495. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57496. * @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
  57497. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57498. */
  57499. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57501. if (defines === void 0) { defines = null; }
  57502. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57503. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57504. if (blockCompilation === void 0) { blockCompilation = false; }
  57505. this.name = name;
  57506. /**
  57507. * Width of the texture to apply the post process on
  57508. */
  57509. this.width = -1;
  57510. /**
  57511. * Height of the texture to apply the post process on
  57512. */
  57513. this.height = -1;
  57514. /**
  57515. * If the buffer needs to be cleared before applying the post process. (default: true)
  57516. * Should be set to false if shader will overwrite all previous pixels.
  57517. */
  57518. this.autoClear = true;
  57519. /**
  57520. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57521. */
  57522. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57523. /**
  57524. * Animations to be used for the post processing
  57525. */
  57526. this.animations = new Array();
  57527. /**
  57528. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57529. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57530. */
  57531. this.enablePixelPerfectMode = false;
  57532. /**
  57533. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57534. */
  57535. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57536. /**
  57537. * Force textures to be a power of two (default: false)
  57538. */
  57539. this.alwaysForcePOT = false;
  57540. /**
  57541. * Number of sample textures (default: 1)
  57542. */
  57543. this.samples = 1;
  57544. /**
  57545. * Modify the scale of the post process to be the same as the viewport (default: false)
  57546. */
  57547. this.adaptScaleToCurrentViewport = false;
  57548. this._reusable = false;
  57549. /**
  57550. * Smart array of input and output textures for the post process.
  57551. */
  57552. this._textures = new BABYLON.SmartArray(2);
  57553. /**
  57554. * The index in _textures that corresponds to the output texture.
  57555. */
  57556. this._currentRenderTextureInd = 0;
  57557. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57558. this._texelSize = BABYLON.Vector2.Zero();
  57559. // Events
  57560. /**
  57561. * An event triggered when the postprocess is activated.
  57562. * @type {BABYLON.Observable}
  57563. */
  57564. this.onActivateObservable = new BABYLON.Observable();
  57565. /**
  57566. * An event triggered when the postprocess changes its size.
  57567. * @type {BABYLON.Observable}
  57568. */
  57569. this.onSizeChangedObservable = new BABYLON.Observable();
  57570. /**
  57571. * An event triggered when the postprocess applies its effect.
  57572. * @type {BABYLON.Observable}
  57573. */
  57574. this.onApplyObservable = new BABYLON.Observable();
  57575. /**
  57576. * An event triggered before rendering the postprocess
  57577. * @type {BABYLON.Observable}
  57578. */
  57579. this.onBeforeRenderObservable = new BABYLON.Observable();
  57580. /**
  57581. * An event triggered after rendering the postprocess
  57582. * @type {BABYLON.Observable}
  57583. */
  57584. this.onAfterRenderObservable = new BABYLON.Observable();
  57585. if (camera != null) {
  57586. this._camera = camera;
  57587. this._scene = camera.getScene();
  57588. camera.attachPostProcess(this);
  57589. this._engine = this._scene.getEngine();
  57590. this._scene.postProcesses.push(this);
  57591. }
  57592. else if (engine) {
  57593. this._engine = engine;
  57594. this._engine.postProcesses.push(this);
  57595. }
  57596. this._options = options;
  57597. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57598. this._reusable = reusable || false;
  57599. this._textureType = textureType;
  57600. this._samplers = samplers || [];
  57601. this._samplers.push("textureSampler");
  57602. this._fragmentUrl = fragmentUrl;
  57603. this._vertexUrl = vertexUrl;
  57604. this._parameters = parameters || [];
  57605. this._parameters.push("scale");
  57606. this._indexParameters = indexParameters;
  57607. if (!blockCompilation) {
  57608. this.updateEffect(defines);
  57609. }
  57610. }
  57611. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57612. /**
  57613. * A function that is added to the onActivateObservable
  57614. */
  57615. set: function (callback) {
  57616. if (this._onActivateObserver) {
  57617. this.onActivateObservable.remove(this._onActivateObserver);
  57618. }
  57619. if (callback) {
  57620. this._onActivateObserver = this.onActivateObservable.add(callback);
  57621. }
  57622. },
  57623. enumerable: true,
  57624. configurable: true
  57625. });
  57626. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57627. /**
  57628. * A function that is added to the onSizeChangedObservable
  57629. */
  57630. set: function (callback) {
  57631. if (this._onSizeChangedObserver) {
  57632. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57633. }
  57634. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57635. },
  57636. enumerable: true,
  57637. configurable: true
  57638. });
  57639. Object.defineProperty(PostProcess.prototype, "onApply", {
  57640. /**
  57641. * A function that is added to the onApplyObservable
  57642. */
  57643. set: function (callback) {
  57644. if (this._onApplyObserver) {
  57645. this.onApplyObservable.remove(this._onApplyObserver);
  57646. }
  57647. this._onApplyObserver = this.onApplyObservable.add(callback);
  57648. },
  57649. enumerable: true,
  57650. configurable: true
  57651. });
  57652. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57653. /**
  57654. * A function that is added to the onBeforeRenderObservable
  57655. */
  57656. set: function (callback) {
  57657. if (this._onBeforeRenderObserver) {
  57658. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57659. }
  57660. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57661. },
  57662. enumerable: true,
  57663. configurable: true
  57664. });
  57665. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57666. /**
  57667. * A function that is added to the onAfterRenderObservable
  57668. */
  57669. set: function (callback) {
  57670. if (this._onAfterRenderObserver) {
  57671. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57672. }
  57673. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57674. },
  57675. enumerable: true,
  57676. configurable: true
  57677. });
  57678. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57679. /**
  57680. * 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
  57681. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57682. */
  57683. get: function () {
  57684. return this._textures.data[this._currentRenderTextureInd];
  57685. },
  57686. set: function (value) {
  57687. this._forcedOutputTexture = value;
  57688. },
  57689. enumerable: true,
  57690. configurable: true
  57691. });
  57692. /**
  57693. * Gets the camera which post process is applied to.
  57694. * @returns The camera the post process is applied to.
  57695. */
  57696. PostProcess.prototype.getCamera = function () {
  57697. return this._camera;
  57698. };
  57699. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57700. /**
  57701. * Gets the texel size of the postprocess.
  57702. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57703. */
  57704. get: function () {
  57705. if (this._shareOutputWithPostProcess) {
  57706. return this._shareOutputWithPostProcess.texelSize;
  57707. }
  57708. if (this._forcedOutputTexture) {
  57709. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57710. }
  57711. return this._texelSize;
  57712. },
  57713. enumerable: true,
  57714. configurable: true
  57715. });
  57716. /**
  57717. * Gets the engine which this post process belongs to.
  57718. * @returns The engine the post process was enabled with.
  57719. */
  57720. PostProcess.prototype.getEngine = function () {
  57721. return this._engine;
  57722. };
  57723. /**
  57724. * The effect that is created when initializing the post process.
  57725. * @returns The created effect corrisponding the the postprocess.
  57726. */
  57727. PostProcess.prototype.getEffect = function () {
  57728. return this._effect;
  57729. };
  57730. /**
  57731. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57732. * @param postProcess The post process to share the output with.
  57733. * @returns This post process.
  57734. */
  57735. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57736. this._disposeTextures();
  57737. this._shareOutputWithPostProcess = postProcess;
  57738. return this;
  57739. };
  57740. /**
  57741. * Updates the effect with the current post process compile time values and recompiles the shader.
  57742. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57743. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57744. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57745. * @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
  57746. * @param onCompiled Called when the shader has been compiled.
  57747. * @param onError Called if there is an error when compiling a shader.
  57748. */
  57749. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57750. if (defines === void 0) { defines = null; }
  57751. if (uniforms === void 0) { uniforms = null; }
  57752. if (samplers === void 0) { samplers = null; }
  57753. 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);
  57754. };
  57755. /**
  57756. * The post process is reusable if it can be used multiple times within one frame.
  57757. * @returns If the post process is reusable
  57758. */
  57759. PostProcess.prototype.isReusable = function () {
  57760. return this._reusable;
  57761. };
  57762. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57763. PostProcess.prototype.markTextureDirty = function () {
  57764. this.width = -1;
  57765. };
  57766. /**
  57767. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57768. * 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.
  57769. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57770. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57771. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57772. */
  57773. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57774. var _this = this;
  57775. if (sourceTexture === void 0) { sourceTexture = null; }
  57776. camera = camera || this._camera;
  57777. var scene = camera.getScene();
  57778. var engine = scene.getEngine();
  57779. var maxSize = engine.getCaps().maxTextureSize;
  57780. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57781. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57782. var desiredWidth = (this._options.width || requiredWidth);
  57783. var desiredHeight = this._options.height || requiredHeight;
  57784. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57785. if (this.adaptScaleToCurrentViewport) {
  57786. var currentViewport = engine.currentViewport;
  57787. if (currentViewport) {
  57788. desiredWidth *= currentViewport.width;
  57789. desiredHeight *= currentViewport.height;
  57790. }
  57791. }
  57792. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57793. if (!this._options.width) {
  57794. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57795. }
  57796. if (!this._options.height) {
  57797. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57798. }
  57799. }
  57800. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57801. if (this._textures.length > 0) {
  57802. for (var i = 0; i < this._textures.length; i++) {
  57803. this._engine._releaseTexture(this._textures.data[i]);
  57804. }
  57805. this._textures.reset();
  57806. }
  57807. this.width = desiredWidth;
  57808. this.height = desiredHeight;
  57809. var textureSize = { width: this.width, height: this.height };
  57810. var textureOptions = {
  57811. generateMipMaps: false,
  57812. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57813. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57814. samplingMode: this.renderTargetSamplingMode,
  57815. type: this._textureType
  57816. };
  57817. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57818. if (this._reusable) {
  57819. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57820. }
  57821. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57822. this.onSizeChangedObservable.notifyObservers(this);
  57823. }
  57824. this._textures.forEach(function (texture) {
  57825. if (texture.samples !== _this.samples) {
  57826. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57827. }
  57828. });
  57829. }
  57830. var target;
  57831. if (this._shareOutputWithPostProcess) {
  57832. target = this._shareOutputWithPostProcess.inputTexture;
  57833. }
  57834. else if (this._forcedOutputTexture) {
  57835. target = this._forcedOutputTexture;
  57836. this.width = this._forcedOutputTexture.width;
  57837. this.height = this._forcedOutputTexture.height;
  57838. }
  57839. else {
  57840. target = this.inputTexture;
  57841. }
  57842. // Bind the input of this post process to be used as the output of the previous post process.
  57843. if (this.enablePixelPerfectMode) {
  57844. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57845. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57846. }
  57847. else {
  57848. this._scaleRatio.copyFromFloats(1, 1);
  57849. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57850. }
  57851. this.onActivateObservable.notifyObservers(camera);
  57852. // Clear
  57853. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57854. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57855. }
  57856. if (this._reusable) {
  57857. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57858. }
  57859. };
  57860. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57861. /**
  57862. * If the post process is supported.
  57863. */
  57864. get: function () {
  57865. return this._effect.isSupported;
  57866. },
  57867. enumerable: true,
  57868. configurable: true
  57869. });
  57870. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57871. /**
  57872. * The aspect ratio of the output texture.
  57873. */
  57874. get: function () {
  57875. if (this._shareOutputWithPostProcess) {
  57876. return this._shareOutputWithPostProcess.aspectRatio;
  57877. }
  57878. if (this._forcedOutputTexture) {
  57879. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57880. }
  57881. return this.width / this.height;
  57882. },
  57883. enumerable: true,
  57884. configurable: true
  57885. });
  57886. /**
  57887. * Get a value indicating if the post-process is ready to be used
  57888. * @returns true if the post-process is ready (shader is compiled)
  57889. */
  57890. PostProcess.prototype.isReady = function () {
  57891. return this._effect && this._effect.isReady();
  57892. };
  57893. /**
  57894. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57895. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57896. */
  57897. PostProcess.prototype.apply = function () {
  57898. // Check
  57899. if (!this._effect || !this._effect.isReady())
  57900. return null;
  57901. // States
  57902. this._engine.enableEffect(this._effect);
  57903. this._engine.setState(false);
  57904. this._engine.setDepthBuffer(false);
  57905. this._engine.setDepthWrite(false);
  57906. // Alpha
  57907. this._engine.setAlphaMode(this.alphaMode);
  57908. if (this.alphaConstants) {
  57909. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57910. }
  57911. // Bind the output texture of the preivous post process as the input to this post process.
  57912. var source;
  57913. if (this._shareOutputWithPostProcess) {
  57914. source = this._shareOutputWithPostProcess.inputTexture;
  57915. }
  57916. else if (this._forcedOutputTexture) {
  57917. source = this._forcedOutputTexture;
  57918. }
  57919. else {
  57920. source = this.inputTexture;
  57921. }
  57922. this._effect._bindTexture("textureSampler", source);
  57923. // Parameters
  57924. this._effect.setVector2("scale", this._scaleRatio);
  57925. this.onApplyObservable.notifyObservers(this._effect);
  57926. return this._effect;
  57927. };
  57928. PostProcess.prototype._disposeTextures = function () {
  57929. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57930. return;
  57931. }
  57932. if (this._textures.length > 0) {
  57933. for (var i = 0; i < this._textures.length; i++) {
  57934. this._engine._releaseTexture(this._textures.data[i]);
  57935. }
  57936. }
  57937. this._textures.dispose();
  57938. };
  57939. /**
  57940. * Disposes the post process.
  57941. * @param camera The camera to dispose the post process on.
  57942. */
  57943. PostProcess.prototype.dispose = function (camera) {
  57944. camera = camera || this._camera;
  57945. this._disposeTextures();
  57946. if (this._scene) {
  57947. var index_1 = this._scene.postProcesses.indexOf(this);
  57948. if (index_1 !== -1) {
  57949. this._scene.postProcesses.splice(index_1, 1);
  57950. }
  57951. }
  57952. else {
  57953. var index_2 = this._engine.postProcesses.indexOf(this);
  57954. if (index_2 !== -1) {
  57955. this._engine.postProcesses.splice(index_2, 1);
  57956. }
  57957. }
  57958. if (!camera) {
  57959. return;
  57960. }
  57961. camera.detachPostProcess(this);
  57962. var index = camera._postProcesses.indexOf(this);
  57963. if (index === 0 && camera._postProcesses.length > 0) {
  57964. this._camera._postProcesses[0].markTextureDirty();
  57965. }
  57966. this.onActivateObservable.clear();
  57967. this.onAfterRenderObservable.clear();
  57968. this.onApplyObservable.clear();
  57969. this.onBeforeRenderObservable.clear();
  57970. this.onSizeChangedObservable.clear();
  57971. };
  57972. return PostProcess;
  57973. }());
  57974. BABYLON.PostProcess = PostProcess;
  57975. })(BABYLON || (BABYLON = {}));
  57976. //# sourceMappingURL=babylon.postProcess.js.map
  57977. var BABYLON;
  57978. (function (BABYLON) {
  57979. var PassPostProcess = /** @class */ (function (_super) {
  57980. __extends(PassPostProcess, _super);
  57981. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57982. if (camera === void 0) { camera = null; }
  57983. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57984. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  57985. }
  57986. return PassPostProcess;
  57987. }(BABYLON.PostProcess));
  57988. BABYLON.PassPostProcess = PassPostProcess;
  57989. })(BABYLON || (BABYLON = {}));
  57990. //# sourceMappingURL=babylon.passPostProcess.js.map
  57991. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57992. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57993. s = arguments[i];
  57994. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57995. t[p] = s[p];
  57996. }
  57997. return t;
  57998. };
  57999. var BABYLON;
  58000. (function (BABYLON) {
  58001. /**
  58002. * Default implementation of @see IShadowGenerator.
  58003. * This is the main object responsible of generating shadows in the framework.
  58004. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58005. */
  58006. var ShadowGenerator = /** @class */ (function () {
  58007. /**
  58008. * Creates a ShadowGenerator object.
  58009. * A ShadowGenerator is the required tool to use the shadows.
  58010. * Each light casting shadows needs to use its own ShadowGenerator.
  58011. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58012. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58013. * @param light The light object generating the shadows.
  58014. * @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.
  58015. */
  58016. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58017. this._bias = 0.00005;
  58018. this._blurBoxOffset = 1;
  58019. this._blurScale = 2;
  58020. this._blurKernel = 1;
  58021. this._useKernelBlur = false;
  58022. this._filter = ShadowGenerator.FILTER_NONE;
  58023. this._darkness = 0;
  58024. this._transparencyShadow = false;
  58025. /**
  58026. * Controls the extent to which the shadows fade out at the edge of the frustum
  58027. * Used only by directionals and spots
  58028. */
  58029. this.frustumEdgeFalloff = 0;
  58030. /**
  58031. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58032. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58033. * It might on the other hand introduce peter panning.
  58034. */
  58035. this.forceBackFacesOnly = false;
  58036. this._lightDirection = BABYLON.Vector3.Zero();
  58037. this._viewMatrix = BABYLON.Matrix.Zero();
  58038. this._projectionMatrix = BABYLON.Matrix.Zero();
  58039. this._transformMatrix = BABYLON.Matrix.Zero();
  58040. this._currentFaceIndex = 0;
  58041. this._currentFaceIndexCache = 0;
  58042. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58043. this._mapSize = mapSize;
  58044. this._light = light;
  58045. this._scene = light.getScene();
  58046. light._shadowGenerator = this;
  58047. // Texture type fallback from float to int if not supported.
  58048. var caps = this._scene.getEngine().getCaps();
  58049. if (!useFullFloatFirst) {
  58050. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58051. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58052. }
  58053. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58054. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58055. }
  58056. else {
  58057. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58058. }
  58059. }
  58060. else {
  58061. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58062. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58063. }
  58064. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58065. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58066. }
  58067. else {
  58068. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58069. }
  58070. }
  58071. this._initializeGenerator();
  58072. }
  58073. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58074. /**
  58075. * Shadow generator mode None: no filtering applied.
  58076. */
  58077. get: function () {
  58078. return ShadowGenerator._FILTER_NONE;
  58079. },
  58080. enumerable: true,
  58081. configurable: true
  58082. });
  58083. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58084. /**
  58085. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58086. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58087. */
  58088. get: function () {
  58089. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58090. },
  58091. enumerable: true,
  58092. configurable: true
  58093. });
  58094. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58095. /**
  58096. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58097. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58098. */
  58099. get: function () {
  58100. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58101. },
  58102. enumerable: true,
  58103. configurable: true
  58104. });
  58105. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58106. /**
  58107. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58108. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58109. */
  58110. get: function () {
  58111. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58112. },
  58113. enumerable: true,
  58114. configurable: true
  58115. });
  58116. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58117. /**
  58118. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58119. * edge artifacts on steep falloff.
  58120. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58121. */
  58122. get: function () {
  58123. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58124. },
  58125. enumerable: true,
  58126. configurable: true
  58127. });
  58128. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58129. /**
  58130. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58131. * edge artifacts on steep falloff.
  58132. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58133. */
  58134. get: function () {
  58135. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58136. },
  58137. enumerable: true,
  58138. configurable: true
  58139. });
  58140. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58141. /**
  58142. * Gets the bias: offset applied on the depth preventing acnea.
  58143. */
  58144. get: function () {
  58145. return this._bias;
  58146. },
  58147. /**
  58148. * Sets the bias: offset applied on the depth preventing acnea.
  58149. */
  58150. set: function (bias) {
  58151. this._bias = bias;
  58152. },
  58153. enumerable: true,
  58154. configurable: true
  58155. });
  58156. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58157. /**
  58158. * Gets the blur box offset: offset applied during the blur pass.
  58159. * Only usefull if useKernelBlur = false
  58160. */
  58161. get: function () {
  58162. return this._blurBoxOffset;
  58163. },
  58164. /**
  58165. * Sets the blur box offset: offset applied during the blur pass.
  58166. * Only usefull if useKernelBlur = false
  58167. */
  58168. set: function (value) {
  58169. if (this._blurBoxOffset === value) {
  58170. return;
  58171. }
  58172. this._blurBoxOffset = value;
  58173. this._disposeBlurPostProcesses();
  58174. },
  58175. enumerable: true,
  58176. configurable: true
  58177. });
  58178. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58179. /**
  58180. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58181. * 2 means half of the size.
  58182. */
  58183. get: function () {
  58184. return this._blurScale;
  58185. },
  58186. /**
  58187. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58188. * 2 means half of the size.
  58189. */
  58190. set: function (value) {
  58191. if (this._blurScale === value) {
  58192. return;
  58193. }
  58194. this._blurScale = value;
  58195. this._disposeBlurPostProcesses();
  58196. },
  58197. enumerable: true,
  58198. configurable: true
  58199. });
  58200. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58201. /**
  58202. * Gets the blur kernel: kernel size of the blur pass.
  58203. * Only usefull if useKernelBlur = true
  58204. */
  58205. get: function () {
  58206. return this._blurKernel;
  58207. },
  58208. /**
  58209. * Sets the blur kernel: kernel size of the blur pass.
  58210. * Only usefull if useKernelBlur = true
  58211. */
  58212. set: function (value) {
  58213. if (this._blurKernel === value) {
  58214. return;
  58215. }
  58216. this._blurKernel = value;
  58217. this._disposeBlurPostProcesses();
  58218. },
  58219. enumerable: true,
  58220. configurable: true
  58221. });
  58222. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58223. /**
  58224. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58225. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58226. */
  58227. get: function () {
  58228. return this._useKernelBlur;
  58229. },
  58230. /**
  58231. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58232. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58233. */
  58234. set: function (value) {
  58235. if (this._useKernelBlur === value) {
  58236. return;
  58237. }
  58238. this._useKernelBlur = value;
  58239. this._disposeBlurPostProcesses();
  58240. },
  58241. enumerable: true,
  58242. configurable: true
  58243. });
  58244. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58245. /**
  58246. * Gets the depth scale used in ESM mode.
  58247. */
  58248. get: function () {
  58249. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58250. },
  58251. /**
  58252. * Sets the depth scale used in ESM mode.
  58253. * This can override the scale stored on the light.
  58254. */
  58255. set: function (value) {
  58256. this._depthScale = value;
  58257. },
  58258. enumerable: true,
  58259. configurable: true
  58260. });
  58261. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58262. /**
  58263. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58264. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58265. */
  58266. get: function () {
  58267. return this._filter;
  58268. },
  58269. /**
  58270. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58271. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58272. */
  58273. set: function (value) {
  58274. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58275. if (this._light.needCube()) {
  58276. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58277. this.useExponentialShadowMap = true;
  58278. return;
  58279. }
  58280. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58281. this.useCloseExponentialShadowMap = true;
  58282. return;
  58283. }
  58284. }
  58285. if (this._filter === value) {
  58286. return;
  58287. }
  58288. this._filter = value;
  58289. this._disposeBlurPostProcesses();
  58290. this._applyFilterValues();
  58291. this._light._markMeshesAsLightDirty();
  58292. },
  58293. enumerable: true,
  58294. configurable: true
  58295. });
  58296. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58297. /**
  58298. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58299. */
  58300. get: function () {
  58301. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58302. },
  58303. /**
  58304. * Sets the current filter to Poisson Sampling aka PCF.
  58305. */
  58306. set: function (value) {
  58307. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58308. return;
  58309. }
  58310. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58311. },
  58312. enumerable: true,
  58313. configurable: true
  58314. });
  58315. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58316. /**
  58317. * Gets if the current filter is set to VSM.
  58318. * DEPRECATED. Should use useExponentialShadowMap instead.
  58319. */
  58320. get: function () {
  58321. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58322. return this.useExponentialShadowMap;
  58323. },
  58324. /**
  58325. * Sets the current filter is to VSM.
  58326. * DEPRECATED. Should use useExponentialShadowMap instead.
  58327. */
  58328. set: function (value) {
  58329. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58330. this.useExponentialShadowMap = value;
  58331. },
  58332. enumerable: true,
  58333. configurable: true
  58334. });
  58335. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58336. /**
  58337. * Gets if the current filter is set to blurred VSM.
  58338. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58339. */
  58340. get: function () {
  58341. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58342. return this.useBlurExponentialShadowMap;
  58343. },
  58344. /**
  58345. * Sets the current filter is to blurred VSM.
  58346. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58347. */
  58348. set: function (value) {
  58349. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58350. this.useBlurExponentialShadowMap = value;
  58351. },
  58352. enumerable: true,
  58353. configurable: true
  58354. });
  58355. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58356. /**
  58357. * Gets if the current filter is set to ESM.
  58358. */
  58359. get: function () {
  58360. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58361. },
  58362. /**
  58363. * Sets the current filter is to ESM.
  58364. */
  58365. set: function (value) {
  58366. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58367. return;
  58368. }
  58369. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58370. },
  58371. enumerable: true,
  58372. configurable: true
  58373. });
  58374. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58375. /**
  58376. * Gets if the current filter is set to filtered ESM.
  58377. */
  58378. get: function () {
  58379. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58380. },
  58381. /**
  58382. * Gets if the current filter is set to filtered ESM.
  58383. */
  58384. set: function (value) {
  58385. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58386. return;
  58387. }
  58388. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58389. },
  58390. enumerable: true,
  58391. configurable: true
  58392. });
  58393. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58394. /**
  58395. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58396. * exponential to prevent steep falloff artifacts).
  58397. */
  58398. get: function () {
  58399. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58400. },
  58401. /**
  58402. * Sets the current filter to "close ESM" (using the inverse of the
  58403. * exponential to prevent steep falloff artifacts).
  58404. */
  58405. set: function (value) {
  58406. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58407. return;
  58408. }
  58409. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58410. },
  58411. enumerable: true,
  58412. configurable: true
  58413. });
  58414. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58415. /**
  58416. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58417. * exponential to prevent steep falloff artifacts).
  58418. */
  58419. get: function () {
  58420. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58421. },
  58422. /**
  58423. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58424. * exponential to prevent steep falloff artifacts).
  58425. */
  58426. set: function (value) {
  58427. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58428. return;
  58429. }
  58430. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58431. },
  58432. enumerable: true,
  58433. configurable: true
  58434. });
  58435. /**
  58436. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58437. * 0 means strongest and 1 would means no shadow.
  58438. * @returns the darkness.
  58439. */
  58440. ShadowGenerator.prototype.getDarkness = function () {
  58441. return this._darkness;
  58442. };
  58443. /**
  58444. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58445. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58446. * @returns the shadow generator allowing fluent coding.
  58447. */
  58448. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58449. if (darkness >= 1.0)
  58450. this._darkness = 1.0;
  58451. else if (darkness <= 0.0)
  58452. this._darkness = 0.0;
  58453. else
  58454. this._darkness = darkness;
  58455. return this;
  58456. };
  58457. /**
  58458. * Sets the ability to have transparent shadow (boolean).
  58459. * @param transparent True if transparent else False
  58460. * @returns the shadow generator allowing fluent coding
  58461. */
  58462. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58463. this._transparencyShadow = transparent;
  58464. return this;
  58465. };
  58466. /**
  58467. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58468. * @returns The render target texture if present otherwise, null
  58469. */
  58470. ShadowGenerator.prototype.getShadowMap = function () {
  58471. return this._shadowMap;
  58472. };
  58473. /**
  58474. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58475. * @returns The render target texture if the shadow map is present otherwise, null
  58476. */
  58477. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58478. if (this._shadowMap2) {
  58479. return this._shadowMap2;
  58480. }
  58481. return this._shadowMap;
  58482. };
  58483. /**
  58484. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58485. * @param mesh Mesh to add
  58486. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58487. * @returns the Shadow Generator itself
  58488. */
  58489. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58490. if (includeDescendants === void 0) { includeDescendants = true; }
  58491. if (!this._shadowMap) {
  58492. return this;
  58493. }
  58494. if (!this._shadowMap.renderList) {
  58495. this._shadowMap.renderList = [];
  58496. }
  58497. this._shadowMap.renderList.push(mesh);
  58498. if (includeDescendants) {
  58499. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58500. }
  58501. return this;
  58502. var _a;
  58503. };
  58504. /**
  58505. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58506. * @param mesh Mesh to remove
  58507. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58508. * @returns the Shadow Generator itself
  58509. */
  58510. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58511. if (includeDescendants === void 0) { includeDescendants = true; }
  58512. if (!this._shadowMap || !this._shadowMap.renderList) {
  58513. return this;
  58514. }
  58515. var index = this._shadowMap.renderList.indexOf(mesh);
  58516. if (index !== -1) {
  58517. this._shadowMap.renderList.splice(index, 1);
  58518. }
  58519. if (includeDescendants) {
  58520. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58521. var child = _a[_i];
  58522. this.removeShadowCaster(child);
  58523. }
  58524. }
  58525. return this;
  58526. };
  58527. /**
  58528. * Returns the associated light object.
  58529. * @returns the light generating the shadow
  58530. */
  58531. ShadowGenerator.prototype.getLight = function () {
  58532. return this._light;
  58533. };
  58534. ShadowGenerator.prototype._initializeGenerator = function () {
  58535. this._light._markMeshesAsLightDirty();
  58536. this._initializeShadowMap();
  58537. };
  58538. ShadowGenerator.prototype._initializeShadowMap = function () {
  58539. var _this = this;
  58540. // Render target
  58541. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58542. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58543. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58544. this._shadowMap.anisotropicFilteringLevel = 1;
  58545. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58546. this._shadowMap.renderParticles = false;
  58547. this._shadowMap.ignoreCameraViewport = true;
  58548. // Record Face Index before render.
  58549. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58550. _this._currentFaceIndex = faceIndex;
  58551. });
  58552. // Custom render function.
  58553. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58554. // Blur if required afer render.
  58555. this._shadowMap.onAfterUnbindObservable.add(function () {
  58556. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58557. return;
  58558. }
  58559. var shadowMap = _this.getShadowMapForRendering();
  58560. if (shadowMap) {
  58561. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58562. }
  58563. });
  58564. // Clear according to the chosen filter.
  58565. this._shadowMap.onClearObservable.add(function (engine) {
  58566. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58567. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58568. }
  58569. else {
  58570. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58571. }
  58572. });
  58573. };
  58574. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58575. var _this = this;
  58576. var engine = this._scene.getEngine();
  58577. var targetSize = this._mapSize / this.blurScale;
  58578. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58579. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58580. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58581. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58582. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58583. }
  58584. if (this.useKernelBlur) {
  58585. 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);
  58586. this._kernelBlurXPostprocess.width = targetSize;
  58587. this._kernelBlurXPostprocess.height = targetSize;
  58588. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58589. effect.setTexture("textureSampler", _this._shadowMap);
  58590. });
  58591. 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);
  58592. this._kernelBlurXPostprocess.autoClear = false;
  58593. this._kernelBlurYPostprocess.autoClear = false;
  58594. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58595. this._kernelBlurXPostprocess.packedFloat = true;
  58596. this._kernelBlurYPostprocess.packedFloat = true;
  58597. }
  58598. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58599. }
  58600. else {
  58601. 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);
  58602. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58603. effect.setFloat2("screenSize", targetSize, targetSize);
  58604. effect.setTexture("textureSampler", _this._shadowMap);
  58605. });
  58606. this._boxBlurPostprocess.autoClear = false;
  58607. this._blurPostProcesses = [this._boxBlurPostprocess];
  58608. }
  58609. };
  58610. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58611. var index;
  58612. var engine = this._scene.getEngine();
  58613. if (depthOnlySubMeshes.length) {
  58614. engine.setColorWrite(false);
  58615. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58616. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58617. }
  58618. engine.setColorWrite(true);
  58619. }
  58620. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58621. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58622. }
  58623. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58624. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58625. }
  58626. if (this._transparencyShadow) {
  58627. for (index = 0; index < transparentSubMeshes.length; index++) {
  58628. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58629. }
  58630. }
  58631. };
  58632. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58633. var _this = this;
  58634. var mesh = subMesh.getRenderingMesh();
  58635. var scene = this._scene;
  58636. var engine = scene.getEngine();
  58637. var material = subMesh.getMaterial();
  58638. if (!material) {
  58639. return;
  58640. }
  58641. // Culling
  58642. engine.setState(material.backFaceCulling);
  58643. // Managing instances
  58644. var batch = mesh._getInstancesRenderList(subMesh._id);
  58645. if (batch.mustReturn) {
  58646. return;
  58647. }
  58648. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58649. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58650. engine.enableEffect(this._effect);
  58651. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58652. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58653. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58654. this._effect.setVector3("lightPosition", this.getLight().position);
  58655. if (scene.activeCamera) {
  58656. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58657. }
  58658. // Alpha test
  58659. if (material && material.needAlphaTesting()) {
  58660. var alphaTexture = material.getAlphaTestTexture();
  58661. if (alphaTexture) {
  58662. this._effect.setTexture("diffuseSampler", alphaTexture);
  58663. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58664. }
  58665. }
  58666. // Bones
  58667. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58668. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58669. }
  58670. if (this.forceBackFacesOnly) {
  58671. engine.setState(true, 0, false, true);
  58672. }
  58673. // Draw
  58674. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58675. if (this.forceBackFacesOnly) {
  58676. engine.setState(true, 0, false, false);
  58677. }
  58678. }
  58679. else {
  58680. // Need to reset refresh rate of the shadowMap
  58681. if (this._shadowMap) {
  58682. this._shadowMap.resetRefreshCounter();
  58683. }
  58684. }
  58685. };
  58686. ShadowGenerator.prototype._applyFilterValues = function () {
  58687. if (!this._shadowMap) {
  58688. return;
  58689. }
  58690. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58691. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58692. }
  58693. else {
  58694. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58695. }
  58696. };
  58697. /**
  58698. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58699. * @param onCompiled Callback triggered at the and of the effects compilation
  58700. * @param options Sets of optional options forcing the compilation with different modes
  58701. */
  58702. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58703. var _this = this;
  58704. var localOptions = __assign({ useInstances: false }, options);
  58705. var shadowMap = this.getShadowMap();
  58706. if (!shadowMap) {
  58707. if (onCompiled) {
  58708. onCompiled(this);
  58709. }
  58710. return;
  58711. }
  58712. var renderList = shadowMap.renderList;
  58713. if (!renderList) {
  58714. if (onCompiled) {
  58715. onCompiled(this);
  58716. }
  58717. return;
  58718. }
  58719. var subMeshes = new Array();
  58720. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58721. var mesh = renderList_1[_i];
  58722. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58723. }
  58724. if (subMeshes.length === 0) {
  58725. if (onCompiled) {
  58726. onCompiled(this);
  58727. }
  58728. return;
  58729. }
  58730. var currentIndex = 0;
  58731. var checkReady = function () {
  58732. if (!_this._scene || !_this._scene.getEngine()) {
  58733. return;
  58734. }
  58735. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58736. currentIndex++;
  58737. if (currentIndex >= subMeshes.length) {
  58738. if (onCompiled) {
  58739. onCompiled(_this);
  58740. }
  58741. return;
  58742. }
  58743. }
  58744. setTimeout(checkReady, 16);
  58745. };
  58746. checkReady();
  58747. };
  58748. /**
  58749. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58750. * @param options Sets of optional options forcing the compilation with different modes
  58751. * @returns A promise that resolves when the compilation completes
  58752. */
  58753. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58754. var _this = this;
  58755. return new Promise(function (resolve) {
  58756. _this.forceCompilation(function () {
  58757. resolve();
  58758. }, options);
  58759. });
  58760. };
  58761. /**
  58762. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58763. * @param subMesh The submesh we want to render in the shadow map
  58764. * @param useInstances Defines wether will draw in the map using instances
  58765. * @returns true if ready otherwise, false
  58766. */
  58767. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58768. var defines = [];
  58769. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58770. defines.push("#define FLOAT");
  58771. }
  58772. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58773. defines.push("#define ESM");
  58774. }
  58775. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58776. var mesh = subMesh.getMesh();
  58777. var material = subMesh.getMaterial();
  58778. // Alpha test
  58779. if (material && material.needAlphaTesting()) {
  58780. var alphaTexture = material.getAlphaTestTexture();
  58781. if (alphaTexture) {
  58782. defines.push("#define ALPHATEST");
  58783. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58784. attribs.push(BABYLON.VertexBuffer.UVKind);
  58785. defines.push("#define UV1");
  58786. }
  58787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58788. if (alphaTexture.coordinatesIndex === 1) {
  58789. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58790. defines.push("#define UV2");
  58791. }
  58792. }
  58793. }
  58794. }
  58795. // Bones
  58796. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58797. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58798. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58799. if (mesh.numBoneInfluencers > 4) {
  58800. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58801. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58802. }
  58803. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58804. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58805. }
  58806. else {
  58807. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58808. }
  58809. // Instances
  58810. if (useInstances) {
  58811. defines.push("#define INSTANCES");
  58812. attribs.push("world0");
  58813. attribs.push("world1");
  58814. attribs.push("world2");
  58815. attribs.push("world3");
  58816. }
  58817. // Get correct effect
  58818. var join = defines.join("\n");
  58819. if (this._cachedDefines !== join) {
  58820. this._cachedDefines = join;
  58821. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58822. }
  58823. if (!this._effect.isReady()) {
  58824. return false;
  58825. }
  58826. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58827. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58828. this._initializeBlurRTTAndPostProcesses();
  58829. }
  58830. }
  58831. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58832. return false;
  58833. }
  58834. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58835. return false;
  58836. }
  58837. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58838. return false;
  58839. }
  58840. return true;
  58841. };
  58842. /**
  58843. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58844. * @param defines Defines of the material we want to update
  58845. * @param lightIndex Index of the light in the enabled light list of the material
  58846. */
  58847. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58848. var scene = this._scene;
  58849. var light = this._light;
  58850. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58851. return;
  58852. }
  58853. defines["SHADOW" + lightIndex] = true;
  58854. if (this.usePoissonSampling) {
  58855. defines["SHADOWPCF" + lightIndex] = true;
  58856. }
  58857. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58858. defines["SHADOWESM" + lightIndex] = true;
  58859. }
  58860. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58861. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58862. }
  58863. if (light.needCube()) {
  58864. defines["SHADOWCUBE" + lightIndex] = true;
  58865. }
  58866. };
  58867. /**
  58868. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58869. * defined in the generator but impacting the effect).
  58870. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58871. * @param effect The effect we are binfing the information for
  58872. */
  58873. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58874. var light = this._light;
  58875. var scene = this._scene;
  58876. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58877. return;
  58878. }
  58879. var camera = scene.activeCamera;
  58880. if (!camera) {
  58881. return;
  58882. }
  58883. var shadowMap = this.getShadowMap();
  58884. if (!shadowMap) {
  58885. return;
  58886. }
  58887. if (!light.needCube()) {
  58888. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58889. }
  58890. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58891. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58892. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58893. };
  58894. /**
  58895. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58896. * (eq to shadow prjection matrix * light transform matrix)
  58897. * @returns The transform matrix used to create the shadow map
  58898. */
  58899. ShadowGenerator.prototype.getTransformMatrix = function () {
  58900. var scene = this._scene;
  58901. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58902. return this._transformMatrix;
  58903. }
  58904. this._currentRenderID = scene.getRenderId();
  58905. this._currentFaceIndexCache = this._currentFaceIndex;
  58906. var lightPosition = this._light.position;
  58907. if (this._light.computeTransformedInformation()) {
  58908. lightPosition = this._light.transformedPosition;
  58909. }
  58910. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58911. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58912. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58913. }
  58914. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58915. this._cachedPosition = lightPosition.clone();
  58916. this._cachedDirection = this._lightDirection.clone();
  58917. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58918. var shadowMap = this.getShadowMap();
  58919. if (shadowMap) {
  58920. var renderList = shadowMap.renderList;
  58921. if (renderList) {
  58922. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58923. }
  58924. }
  58925. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58926. }
  58927. return this._transformMatrix;
  58928. };
  58929. /**
  58930. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58931. * Cube and 2D textures for instance.
  58932. */
  58933. ShadowGenerator.prototype.recreateShadowMap = function () {
  58934. var shadowMap = this._shadowMap;
  58935. if (!shadowMap) {
  58936. return;
  58937. }
  58938. // Track render list.
  58939. var renderList = shadowMap.renderList;
  58940. // Clean up existing data.
  58941. this._disposeRTTandPostProcesses();
  58942. // Reinitializes.
  58943. this._initializeGenerator();
  58944. // Reaffect the filter to ensure a correct fallback if necessary.
  58945. this.filter = this.filter;
  58946. // Reaffect the filter.
  58947. this._applyFilterValues();
  58948. // Reaffect Render List.
  58949. this._shadowMap.renderList = renderList;
  58950. };
  58951. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  58952. if (this._shadowMap2) {
  58953. this._shadowMap2.dispose();
  58954. this._shadowMap2 = null;
  58955. }
  58956. if (this._boxBlurPostprocess) {
  58957. this._boxBlurPostprocess.dispose();
  58958. this._boxBlurPostprocess = null;
  58959. }
  58960. if (this._kernelBlurXPostprocess) {
  58961. this._kernelBlurXPostprocess.dispose();
  58962. this._kernelBlurXPostprocess = null;
  58963. }
  58964. if (this._kernelBlurYPostprocess) {
  58965. this._kernelBlurYPostprocess.dispose();
  58966. this._kernelBlurYPostprocess = null;
  58967. }
  58968. this._blurPostProcesses = [];
  58969. };
  58970. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  58971. if (this._shadowMap) {
  58972. this._shadowMap.dispose();
  58973. this._shadowMap = null;
  58974. }
  58975. this._disposeBlurPostProcesses();
  58976. };
  58977. /**
  58978. * Disposes the ShadowGenerator.
  58979. * Returns nothing.
  58980. */
  58981. ShadowGenerator.prototype.dispose = function () {
  58982. this._disposeRTTandPostProcesses();
  58983. if (this._light) {
  58984. this._light._shadowGenerator = null;
  58985. this._light._markMeshesAsLightDirty();
  58986. }
  58987. };
  58988. /**
  58989. * Serializes the shadow generator setup to a json object.
  58990. * @returns The serialized JSON object
  58991. */
  58992. ShadowGenerator.prototype.serialize = function () {
  58993. var serializationObject = {};
  58994. var shadowMap = this.getShadowMap();
  58995. if (!shadowMap) {
  58996. return serializationObject;
  58997. }
  58998. serializationObject.lightId = this._light.id;
  58999. serializationObject.mapSize = shadowMap.getRenderSize();
  59000. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59001. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59002. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59003. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59004. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59005. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59006. serializationObject.depthScale = this.depthScale;
  59007. serializationObject.darkness = this.getDarkness();
  59008. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59009. serializationObject.blurKernel = this.blurKernel;
  59010. serializationObject.blurScale = this.blurScale;
  59011. serializationObject.useKernelBlur = this.useKernelBlur;
  59012. serializationObject.transparencyShadow = this._transparencyShadow;
  59013. serializationObject.renderList = [];
  59014. if (shadowMap.renderList) {
  59015. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59016. var mesh = shadowMap.renderList[meshIndex];
  59017. serializationObject.renderList.push(mesh.id);
  59018. }
  59019. }
  59020. return serializationObject;
  59021. };
  59022. /**
  59023. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59024. * @param parsedShadowGenerator The JSON object to parse
  59025. * @param scene The scene to create the shadow map for
  59026. * @returns The parsed shadow generator
  59027. */
  59028. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59029. //casting to point light, as light is missing the position attr and typescript complains.
  59030. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59031. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59032. var shadowMap = shadowGenerator.getShadowMap();
  59033. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59034. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59035. meshes.forEach(function (mesh) {
  59036. if (!shadowMap) {
  59037. return;
  59038. }
  59039. if (!shadowMap.renderList) {
  59040. shadowMap.renderList = [];
  59041. }
  59042. shadowMap.renderList.push(mesh);
  59043. });
  59044. }
  59045. if (parsedShadowGenerator.usePoissonSampling) {
  59046. shadowGenerator.usePoissonSampling = true;
  59047. }
  59048. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59049. shadowGenerator.useExponentialShadowMap = true;
  59050. }
  59051. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59052. shadowGenerator.useBlurExponentialShadowMap = true;
  59053. }
  59054. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59055. shadowGenerator.useCloseExponentialShadowMap = true;
  59056. }
  59057. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59058. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59059. }
  59060. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59061. shadowGenerator.useExponentialShadowMap = true;
  59062. }
  59063. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59064. shadowGenerator.useBlurExponentialShadowMap = true;
  59065. }
  59066. if (parsedShadowGenerator.depthScale) {
  59067. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59068. }
  59069. if (parsedShadowGenerator.blurScale) {
  59070. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59071. }
  59072. if (parsedShadowGenerator.blurBoxOffset) {
  59073. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59074. }
  59075. if (parsedShadowGenerator.useKernelBlur) {
  59076. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59077. }
  59078. if (parsedShadowGenerator.blurKernel) {
  59079. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59080. }
  59081. if (parsedShadowGenerator.bias !== undefined) {
  59082. shadowGenerator.bias = parsedShadowGenerator.bias;
  59083. }
  59084. if (parsedShadowGenerator.darkness) {
  59085. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59086. }
  59087. if (parsedShadowGenerator.transparencyShadow) {
  59088. shadowGenerator.setTransparencyShadow(true);
  59089. }
  59090. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59091. return shadowGenerator;
  59092. };
  59093. ShadowGenerator._FILTER_NONE = 0;
  59094. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59095. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59096. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59097. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59098. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59099. return ShadowGenerator;
  59100. }());
  59101. BABYLON.ShadowGenerator = ShadowGenerator;
  59102. })(BABYLON || (BABYLON = {}));
  59103. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59104. var BABYLON;
  59105. (function (BABYLON) {
  59106. var DefaultLoadingScreen = /** @class */ (function () {
  59107. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59108. if (_loadingText === void 0) { _loadingText = ""; }
  59109. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59110. var _this = this;
  59111. this._renderingCanvas = _renderingCanvas;
  59112. this._loadingText = _loadingText;
  59113. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59114. // Resize
  59115. this._resizeLoadingUI = function () {
  59116. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59117. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59118. if (!_this._loadingDiv) {
  59119. return;
  59120. }
  59121. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59122. _this._loadingDiv.style.left = canvasRect.left + "px";
  59123. _this._loadingDiv.style.top = canvasRect.top + "px";
  59124. _this._loadingDiv.style.width = canvasRect.width + "px";
  59125. _this._loadingDiv.style.height = canvasRect.height + "px";
  59126. };
  59127. }
  59128. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59129. if (this._loadingDiv) {
  59130. // Do not add a loading screen if there is already one
  59131. return;
  59132. }
  59133. this._loadingDiv = document.createElement("div");
  59134. this._loadingDiv.id = "babylonjsLoadingDiv";
  59135. this._loadingDiv.style.opacity = "0";
  59136. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59137. this._loadingDiv.style.pointerEvents = "none";
  59138. // Loading text
  59139. this._loadingTextDiv = document.createElement("div");
  59140. this._loadingTextDiv.style.position = "absolute";
  59141. this._loadingTextDiv.style.left = "0";
  59142. this._loadingTextDiv.style.top = "50%";
  59143. this._loadingTextDiv.style.marginTop = "80px";
  59144. this._loadingTextDiv.style.width = "100%";
  59145. this._loadingTextDiv.style.height = "20px";
  59146. this._loadingTextDiv.style.fontFamily = "Arial";
  59147. this._loadingTextDiv.style.fontSize = "14px";
  59148. this._loadingTextDiv.style.color = "white";
  59149. this._loadingTextDiv.style.textAlign = "center";
  59150. this._loadingTextDiv.innerHTML = "Loading";
  59151. this._loadingDiv.appendChild(this._loadingTextDiv);
  59152. //set the predefined text
  59153. this._loadingTextDiv.innerHTML = this._loadingText;
  59154. // Generating keyframes
  59155. var style = document.createElement('style');
  59156. style.type = 'text/css';
  59157. 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 }";
  59158. style.innerHTML = keyFrames;
  59159. document.getElementsByTagName('head')[0].appendChild(style);
  59160. // Loading img
  59161. var imgBack = new Image();
  59162. 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";
  59163. imgBack.style.position = "absolute";
  59164. imgBack.style.left = "50%";
  59165. imgBack.style.top = "50%";
  59166. imgBack.style.marginLeft = "-60px";
  59167. imgBack.style.marginTop = "-60px";
  59168. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59169. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59170. imgBack.style.transformOrigin = "50% 50%";
  59171. imgBack.style.webkitTransformOrigin = "50% 50%";
  59172. this._loadingDiv.appendChild(imgBack);
  59173. this._resizeLoadingUI();
  59174. window.addEventListener("resize", this._resizeLoadingUI);
  59175. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59176. document.body.appendChild(this._loadingDiv);
  59177. this._loadingDiv.style.opacity = "1";
  59178. };
  59179. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59180. var _this = this;
  59181. if (!this._loadingDiv) {
  59182. return;
  59183. }
  59184. var onTransitionEnd = function () {
  59185. if (!_this._loadingDiv) {
  59186. return;
  59187. }
  59188. document.body.removeChild(_this._loadingDiv);
  59189. window.removeEventListener("resize", _this._resizeLoadingUI);
  59190. _this._loadingDiv = null;
  59191. };
  59192. this._loadingDiv.style.opacity = "0";
  59193. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59194. };
  59195. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59196. set: function (text) {
  59197. this._loadingText = text;
  59198. if (this._loadingTextDiv) {
  59199. this._loadingTextDiv.innerHTML = this._loadingText;
  59200. }
  59201. },
  59202. enumerable: true,
  59203. configurable: true
  59204. });
  59205. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59206. get: function () {
  59207. return this._loadingDivBackgroundColor;
  59208. },
  59209. set: function (color) {
  59210. this._loadingDivBackgroundColor = color;
  59211. if (!this._loadingDiv) {
  59212. return;
  59213. }
  59214. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59215. },
  59216. enumerable: true,
  59217. configurable: true
  59218. });
  59219. return DefaultLoadingScreen;
  59220. }());
  59221. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59222. })(BABYLON || (BABYLON = {}));
  59223. //# sourceMappingURL=babylon.loadingScreen.js.map
  59224. var BABYLON;
  59225. (function (BABYLON) {
  59226. var SceneLoaderProgressEvent = /** @class */ (function () {
  59227. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59228. this.lengthComputable = lengthComputable;
  59229. this.loaded = loaded;
  59230. this.total = total;
  59231. }
  59232. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59233. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59234. };
  59235. return SceneLoaderProgressEvent;
  59236. }());
  59237. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59238. var SceneLoader = /** @class */ (function () {
  59239. function SceneLoader() {
  59240. }
  59241. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59242. get: function () {
  59243. return 0;
  59244. },
  59245. enumerable: true,
  59246. configurable: true
  59247. });
  59248. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59249. get: function () {
  59250. return 1;
  59251. },
  59252. enumerable: true,
  59253. configurable: true
  59254. });
  59255. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59256. get: function () {
  59257. return 2;
  59258. },
  59259. enumerable: true,
  59260. configurable: true
  59261. });
  59262. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59263. get: function () {
  59264. return 3;
  59265. },
  59266. enumerable: true,
  59267. configurable: true
  59268. });
  59269. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59270. get: function () {
  59271. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59272. },
  59273. set: function (value) {
  59274. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59275. },
  59276. enumerable: true,
  59277. configurable: true
  59278. });
  59279. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59280. get: function () {
  59281. return SceneLoader._ShowLoadingScreen;
  59282. },
  59283. set: function (value) {
  59284. SceneLoader._ShowLoadingScreen = value;
  59285. },
  59286. enumerable: true,
  59287. configurable: true
  59288. });
  59289. Object.defineProperty(SceneLoader, "loggingLevel", {
  59290. get: function () {
  59291. return SceneLoader._loggingLevel;
  59292. },
  59293. set: function (value) {
  59294. SceneLoader._loggingLevel = value;
  59295. },
  59296. enumerable: true,
  59297. configurable: true
  59298. });
  59299. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59300. get: function () {
  59301. return SceneLoader._CleanBoneMatrixWeights;
  59302. },
  59303. set: function (value) {
  59304. SceneLoader._CleanBoneMatrixWeights = value;
  59305. },
  59306. enumerable: true,
  59307. configurable: true
  59308. });
  59309. SceneLoader._getDefaultPlugin = function () {
  59310. return SceneLoader._registeredPlugins[".babylon"];
  59311. };
  59312. SceneLoader._getPluginForExtension = function (extension) {
  59313. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59314. if (registeredPlugin) {
  59315. return registeredPlugin;
  59316. }
  59317. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59318. return SceneLoader._getDefaultPlugin();
  59319. };
  59320. SceneLoader._getPluginForDirectLoad = function (data) {
  59321. for (var extension in SceneLoader._registeredPlugins) {
  59322. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59323. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59324. return SceneLoader._registeredPlugins[extension];
  59325. }
  59326. }
  59327. return SceneLoader._getDefaultPlugin();
  59328. };
  59329. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59330. if (sceneFilename.name) {
  59331. sceneFilename = sceneFilename.name;
  59332. }
  59333. var queryStringPosition = sceneFilename.indexOf("?");
  59334. if (queryStringPosition !== -1) {
  59335. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59336. }
  59337. var dotPosition = sceneFilename.lastIndexOf(".");
  59338. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59339. return SceneLoader._getPluginForExtension(extension);
  59340. };
  59341. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59342. SceneLoader._getDirectLoad = function (sceneFilename) {
  59343. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59344. return sceneFilename.substr(5);
  59345. }
  59346. return null;
  59347. };
  59348. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59349. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59350. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59351. var plugin;
  59352. if (registeredPlugin.plugin.createPlugin) {
  59353. plugin = registeredPlugin.plugin.createPlugin();
  59354. }
  59355. else {
  59356. plugin = registeredPlugin.plugin;
  59357. }
  59358. var useArrayBuffer = registeredPlugin.isBinary;
  59359. var database;
  59360. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59361. var dataCallback = function (data, responseURL) {
  59362. if (scene.isDisposed) {
  59363. onError("Scene has been disposed");
  59364. return;
  59365. }
  59366. scene.database = database;
  59367. onSuccess(plugin, data, responseURL);
  59368. };
  59369. var request = null;
  59370. var pluginDisposed = false;
  59371. var onDisposeObservable = plugin.onDisposeObservable;
  59372. if (onDisposeObservable) {
  59373. onDisposeObservable.add(function () {
  59374. pluginDisposed = true;
  59375. if (request) {
  59376. request.abort();
  59377. request = null;
  59378. }
  59379. onDispose();
  59380. });
  59381. }
  59382. var manifestChecked = function () {
  59383. if (pluginDisposed) {
  59384. return;
  59385. }
  59386. var url = rootUrl + sceneFilename;
  59387. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59388. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59389. } : undefined, database, useArrayBuffer, function (request, exception) {
  59390. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59391. });
  59392. };
  59393. if (directLoad) {
  59394. dataCallback(directLoad);
  59395. return plugin;
  59396. }
  59397. if (rootUrl.indexOf("file:") === -1) {
  59398. if (scene.getEngine().enableOfflineSupport) {
  59399. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59400. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59401. }
  59402. else {
  59403. manifestChecked();
  59404. }
  59405. }
  59406. else {
  59407. var fileOrString = sceneFilename;
  59408. if (fileOrString.name) {
  59409. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59410. }
  59411. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59412. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59413. }
  59414. else {
  59415. onError("Unable to find file named " + sceneFilename);
  59416. }
  59417. }
  59418. return plugin;
  59419. };
  59420. // Public functions
  59421. SceneLoader.GetPluginForExtension = function (extension) {
  59422. return SceneLoader._getPluginForExtension(extension).plugin;
  59423. };
  59424. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59425. return !!SceneLoader._registeredPlugins[extension];
  59426. };
  59427. SceneLoader.RegisterPlugin = function (plugin) {
  59428. if (typeof plugin.extensions === "string") {
  59429. var extension = plugin.extensions;
  59430. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59431. plugin: plugin,
  59432. isBinary: false
  59433. };
  59434. }
  59435. else {
  59436. var extensions = plugin.extensions;
  59437. Object.keys(extensions).forEach(function (extension) {
  59438. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59439. plugin: plugin,
  59440. isBinary: extensions[extension].isBinary
  59441. };
  59442. });
  59443. }
  59444. };
  59445. /**
  59446. * Import meshes into a scene
  59447. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59448. * @param rootUrl a string that defines the root url for scene and resources
  59449. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59450. * @param scene the instance of BABYLON.Scene to append to
  59451. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59452. * @param onProgress a callback with a progress event for each file being loaded
  59453. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59454. * @param pluginExtension the extension used to determine the plugin
  59455. * @returns The loaded plugin
  59456. */
  59457. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59458. if (onSuccess === void 0) { onSuccess = null; }
  59459. if (onProgress === void 0) { onProgress = null; }
  59460. if (onError === void 0) { onError = null; }
  59461. if (pluginExtension === void 0) { pluginExtension = null; }
  59462. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59463. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59464. return null;
  59465. }
  59466. var loadingToken = {};
  59467. scene._addPendingData(loadingToken);
  59468. var disposeHandler = function () {
  59469. scene._removePendingData(loadingToken);
  59470. };
  59471. var errorHandler = function (message, exception) {
  59472. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59473. if (onError) {
  59474. onError(scene, errorMessage, exception);
  59475. }
  59476. else {
  59477. BABYLON.Tools.Error(errorMessage);
  59478. // should the exception be thrown?
  59479. }
  59480. disposeHandler();
  59481. };
  59482. var progressHandler = onProgress ? function (event) {
  59483. try {
  59484. onProgress(event);
  59485. }
  59486. catch (e) {
  59487. errorHandler("Error in onProgress callback", e);
  59488. }
  59489. } : undefined;
  59490. var successHandler = function (meshes, particleSystems, skeletons) {
  59491. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59492. if (onSuccess) {
  59493. try {
  59494. onSuccess(meshes, particleSystems, skeletons);
  59495. }
  59496. catch (e) {
  59497. errorHandler("Error in onSuccess callback", e);
  59498. }
  59499. }
  59500. scene._removePendingData(loadingToken);
  59501. };
  59502. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59503. if (plugin.rewriteRootURL) {
  59504. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59505. }
  59506. if (sceneFilename === "") {
  59507. if (sceneFilename === "") {
  59508. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59509. }
  59510. }
  59511. if (plugin.importMesh) {
  59512. var syncedPlugin = plugin;
  59513. var meshes = new Array();
  59514. var particleSystems = new Array();
  59515. var skeletons = new Array();
  59516. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59517. return;
  59518. }
  59519. scene.loadingPluginName = plugin.name;
  59520. successHandler(meshes, particleSystems, skeletons);
  59521. }
  59522. else {
  59523. var asyncedPlugin = plugin;
  59524. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59525. scene.loadingPluginName = plugin.name;
  59526. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59527. }).catch(function (error) {
  59528. errorHandler(error.message, error);
  59529. });
  59530. }
  59531. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59532. };
  59533. /**
  59534. * Import meshes into a scene
  59535. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59536. * @param rootUrl a string that defines the root url for scene and resources
  59537. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59538. * @param scene the instance of BABYLON.Scene to append to
  59539. * @param onProgress a callback with a progress event for each file being loaded
  59540. * @param pluginExtension the extension used to determine the plugin
  59541. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59542. */
  59543. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59544. if (onProgress === void 0) { onProgress = null; }
  59545. if (pluginExtension === void 0) { pluginExtension = null; }
  59546. return new Promise(function (resolve, reject) {
  59547. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59548. resolve({
  59549. meshes: meshes,
  59550. particleSystems: particleSystems,
  59551. skeletons: skeletons
  59552. });
  59553. }, onProgress, function (scene, message, exception) {
  59554. reject(exception || new Error(message));
  59555. });
  59556. });
  59557. };
  59558. /**
  59559. * Load a scene
  59560. * @param rootUrl a string that defines the root url for scene and resources
  59561. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59562. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59563. * @param onSuccess a callback with the scene when import succeeds
  59564. * @param onProgress a callback with a progress event for each file being loaded
  59565. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59566. * @param pluginExtension the extension used to determine the plugin
  59567. * @returns The loaded plugin
  59568. */
  59569. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59570. if (onSuccess === void 0) { onSuccess = null; }
  59571. if (onProgress === void 0) { onProgress = null; }
  59572. if (onError === void 0) { onError = null; }
  59573. if (pluginExtension === void 0) { pluginExtension = null; }
  59574. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59575. };
  59576. /**
  59577. * Load a scene
  59578. * @param rootUrl a string that defines the root url for scene and resources
  59579. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59580. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59581. * @param onProgress a callback with a progress event for each file being loaded
  59582. * @param pluginExtension the extension used to determine the plugin
  59583. * @returns The loaded scene
  59584. */
  59585. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59586. if (onProgress === void 0) { onProgress = null; }
  59587. if (pluginExtension === void 0) { pluginExtension = null; }
  59588. return new Promise(function (resolve, reject) {
  59589. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59590. resolve(scene);
  59591. }, onProgress, function (scene, message, exception) {
  59592. reject(exception || new Error(message));
  59593. }, pluginExtension);
  59594. });
  59595. };
  59596. /**
  59597. * Append a scene
  59598. * @param rootUrl a string that defines the root url for scene and resources
  59599. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59600. * @param scene is the instance of BABYLON.Scene to append to
  59601. * @param onSuccess a callback with the scene when import succeeds
  59602. * @param onProgress a callback with a progress event for each file being loaded
  59603. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59604. * @param pluginExtension the extension used to determine the plugin
  59605. * @returns The loaded plugin
  59606. */
  59607. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59608. if (onSuccess === void 0) { onSuccess = null; }
  59609. if (onProgress === void 0) { onProgress = null; }
  59610. if (onError === void 0) { onError = null; }
  59611. if (pluginExtension === void 0) { pluginExtension = null; }
  59612. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59613. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59614. return null;
  59615. }
  59616. if (SceneLoader.ShowLoadingScreen) {
  59617. scene.getEngine().displayLoadingUI();
  59618. }
  59619. var loadingToken = {};
  59620. scene._addPendingData(loadingToken);
  59621. var disposeHandler = function () {
  59622. scene._removePendingData(loadingToken);
  59623. scene.getEngine().hideLoadingUI();
  59624. };
  59625. var errorHandler = function (message, exception) {
  59626. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59627. if (onError) {
  59628. onError(scene, errorMessage, exception);
  59629. }
  59630. else {
  59631. BABYLON.Tools.Error(errorMessage);
  59632. // should the exception be thrown?
  59633. }
  59634. disposeHandler();
  59635. };
  59636. var progressHandler = onProgress ? function (event) {
  59637. try {
  59638. onProgress(event);
  59639. }
  59640. catch (e) {
  59641. errorHandler("Error in onProgress callback", e);
  59642. }
  59643. } : undefined;
  59644. var successHandler = function () {
  59645. if (onSuccess) {
  59646. try {
  59647. onSuccess(scene);
  59648. }
  59649. catch (e) {
  59650. errorHandler("Error in onSuccess callback", e);
  59651. }
  59652. }
  59653. scene._removePendingData(loadingToken);
  59654. };
  59655. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59656. if (sceneFilename === "") {
  59657. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59658. }
  59659. if (plugin.load) {
  59660. var syncedPlugin = plugin;
  59661. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59662. return;
  59663. }
  59664. scene.loadingPluginName = plugin.name;
  59665. successHandler();
  59666. }
  59667. else {
  59668. var asyncedPlugin = plugin;
  59669. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59670. scene.loadingPluginName = plugin.name;
  59671. successHandler();
  59672. }).catch(function (error) {
  59673. errorHandler(error.message, error);
  59674. });
  59675. }
  59676. if (SceneLoader.ShowLoadingScreen) {
  59677. scene.executeWhenReady(function () {
  59678. scene.getEngine().hideLoadingUI();
  59679. });
  59680. }
  59681. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59682. };
  59683. /**
  59684. * Append a scene
  59685. * @param rootUrl a string that defines the root url for scene and resources
  59686. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59687. * @param scene is the instance of BABYLON.Scene to append to
  59688. * @param onProgress a callback with a progress event for each file being loaded
  59689. * @param pluginExtension the extension used to determine the plugin
  59690. * @returns The given scene
  59691. */
  59692. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59693. if (onProgress === void 0) { onProgress = null; }
  59694. if (pluginExtension === void 0) { pluginExtension = null; }
  59695. return new Promise(function (resolve, reject) {
  59696. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59697. resolve(scene);
  59698. }, onProgress, function (scene, message, exception) {
  59699. reject(exception || new Error(message));
  59700. }, pluginExtension);
  59701. });
  59702. };
  59703. /**
  59704. * Load a scene into an asset container
  59705. * @param rootUrl a string that defines the root url for scene and resources
  59706. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59707. * @param scene is the instance of BABYLON.Scene to append to
  59708. * @param onSuccess a callback with the scene when import succeeds
  59709. * @param onProgress a callback with a progress event for each file being loaded
  59710. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59711. * @param pluginExtension the extension used to determine the plugin
  59712. * @returns The loaded plugin
  59713. */
  59714. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59715. if (onSuccess === void 0) { onSuccess = null; }
  59716. if (onProgress === void 0) { onProgress = null; }
  59717. if (onError === void 0) { onError = null; }
  59718. if (pluginExtension === void 0) { pluginExtension = null; }
  59719. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59720. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59721. return null;
  59722. }
  59723. var loadingToken = {};
  59724. scene._addPendingData(loadingToken);
  59725. var disposeHandler = function () {
  59726. scene._removePendingData(loadingToken);
  59727. };
  59728. var errorHandler = function (message, exception) {
  59729. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59730. if (onError) {
  59731. onError(scene, errorMessage, exception);
  59732. }
  59733. else {
  59734. BABYLON.Tools.Error(errorMessage);
  59735. // should the exception be thrown?
  59736. }
  59737. disposeHandler();
  59738. };
  59739. var progressHandler = onProgress ? function (event) {
  59740. try {
  59741. onProgress(event);
  59742. }
  59743. catch (e) {
  59744. errorHandler("Error in onProgress callback", e);
  59745. }
  59746. } : undefined;
  59747. var successHandler = function (assets) {
  59748. if (onSuccess) {
  59749. try {
  59750. onSuccess(assets);
  59751. }
  59752. catch (e) {
  59753. errorHandler("Error in onSuccess callback", e);
  59754. }
  59755. }
  59756. scene._removePendingData(loadingToken);
  59757. };
  59758. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59759. if (plugin.loadAssetContainer) {
  59760. var syncedPlugin = plugin;
  59761. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59762. if (!assetContainer) {
  59763. return;
  59764. }
  59765. scene.loadingPluginName = plugin.name;
  59766. successHandler(assetContainer);
  59767. }
  59768. else if (plugin.loadAssetContainerAsync) {
  59769. var asyncedPlugin = plugin;
  59770. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59771. scene.loadingPluginName = plugin.name;
  59772. successHandler(assetContainer);
  59773. }).catch(function (error) {
  59774. errorHandler(error.message, error);
  59775. });
  59776. }
  59777. else {
  59778. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59779. }
  59780. if (SceneLoader.ShowLoadingScreen) {
  59781. scene.executeWhenReady(function () {
  59782. scene.getEngine().hideLoadingUI();
  59783. });
  59784. }
  59785. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59786. };
  59787. /**
  59788. * Load a scene into an asset container
  59789. * @param rootUrl a string that defines the root url for scene and resources
  59790. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59791. * @param scene is the instance of BABYLON.Scene to append to
  59792. * @param onProgress a callback with a progress event for each file being loaded
  59793. * @param pluginExtension the extension used to determine the plugin
  59794. * @returns The loaded asset container
  59795. */
  59796. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59797. if (onProgress === void 0) { onProgress = null; }
  59798. if (pluginExtension === void 0) { pluginExtension = null; }
  59799. return new Promise(function (resolve, reject) {
  59800. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  59801. resolve(assetContainer);
  59802. }, onProgress, function (scene, message, exception) {
  59803. reject(exception || new Error(message));
  59804. }, pluginExtension);
  59805. });
  59806. };
  59807. // Flags
  59808. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59809. SceneLoader._ShowLoadingScreen = true;
  59810. SceneLoader._CleanBoneMatrixWeights = false;
  59811. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59812. // Members
  59813. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59814. SceneLoader._registeredPlugins = {};
  59815. return SceneLoader;
  59816. }());
  59817. BABYLON.SceneLoader = SceneLoader;
  59818. ;
  59819. })(BABYLON || (BABYLON = {}));
  59820. //# sourceMappingURL=babylon.sceneLoader.js.map
  59821. var BABYLON;
  59822. (function (BABYLON) {
  59823. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59824. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59825. var parsedMaterial = parsedData.materials[index];
  59826. if (parsedMaterial.id === id) {
  59827. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59828. }
  59829. }
  59830. return null;
  59831. };
  59832. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59833. for (var i in names) {
  59834. if (mesh.name === names[i]) {
  59835. hierarchyIds.push(mesh.id);
  59836. return true;
  59837. }
  59838. }
  59839. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59840. hierarchyIds.push(mesh.id);
  59841. return true;
  59842. }
  59843. return false;
  59844. };
  59845. var logOperation = function (operation, producer) {
  59846. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59847. };
  59848. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  59849. if (addToScene === void 0) { addToScene = false; }
  59850. var container = new BABYLON.AssetContainer(scene);
  59851. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59852. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59853. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59854. // and avoid problems with multiple concurrent .babylon loads.
  59855. var log = "importScene has failed JSON parse";
  59856. try {
  59857. var parsedData = JSON.parse(data);
  59858. log = "";
  59859. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59860. var index;
  59861. var cache;
  59862. // Lights
  59863. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59864. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59865. var parsedLight = parsedData.lights[index];
  59866. var light = BABYLON.Light.Parse(parsedLight, scene);
  59867. if (light) {
  59868. container.lights.push(light);
  59869. log += (index === 0 ? "\n\tLights:" : "");
  59870. log += "\n\t\t" + light.toString(fullDetails);
  59871. }
  59872. }
  59873. }
  59874. // Animations
  59875. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59876. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59877. var parsedAnimation = parsedData.animations[index];
  59878. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59879. scene.animations.push(animation);
  59880. container.animations.push(animation);
  59881. log += (index === 0 ? "\n\tAnimations:" : "");
  59882. log += "\n\t\t" + animation.toString(fullDetails);
  59883. }
  59884. }
  59885. // Materials
  59886. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59887. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59888. var parsedMaterial = parsedData.materials[index];
  59889. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59890. container.materials.push(mat);
  59891. log += (index === 0 ? "\n\tMaterials:" : "");
  59892. log += "\n\t\t" + mat.toString(fullDetails);
  59893. }
  59894. }
  59895. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59896. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59897. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59898. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59899. container.multiMaterials.push(mmat);
  59900. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59901. log += "\n\t\t" + mmat.toString(fullDetails);
  59902. }
  59903. }
  59904. // Morph targets
  59905. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59906. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59907. var managerData = _a[_i];
  59908. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59909. }
  59910. }
  59911. // Skeletons
  59912. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59913. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59914. var parsedSkeleton = parsedData.skeletons[index];
  59915. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59916. container.skeletons.push(skeleton);
  59917. log += (index === 0 ? "\n\tSkeletons:" : "");
  59918. log += "\n\t\t" + skeleton.toString(fullDetails);
  59919. }
  59920. }
  59921. // Geometries
  59922. var geometries = parsedData.geometries;
  59923. if (geometries !== undefined && geometries !== null) {
  59924. var addedGeometry = new Array();
  59925. // Boxes
  59926. var boxes = geometries.boxes;
  59927. if (boxes !== undefined && boxes !== null) {
  59928. for (index = 0, cache = boxes.length; index < cache; index++) {
  59929. var parsedBox = boxes[index];
  59930. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59931. }
  59932. }
  59933. // Spheres
  59934. var spheres = geometries.spheres;
  59935. if (spheres !== undefined && spheres !== null) {
  59936. for (index = 0, cache = spheres.length; index < cache; index++) {
  59937. var parsedSphere = spheres[index];
  59938. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  59939. }
  59940. }
  59941. // Cylinders
  59942. var cylinders = geometries.cylinders;
  59943. if (cylinders !== undefined && cylinders !== null) {
  59944. for (index = 0, cache = cylinders.length; index < cache; index++) {
  59945. var parsedCylinder = cylinders[index];
  59946. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  59947. }
  59948. }
  59949. // Toruses
  59950. var toruses = geometries.toruses;
  59951. if (toruses !== undefined && toruses !== null) {
  59952. for (index = 0, cache = toruses.length; index < cache; index++) {
  59953. var parsedTorus = toruses[index];
  59954. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  59955. }
  59956. }
  59957. // Grounds
  59958. var grounds = geometries.grounds;
  59959. if (grounds !== undefined && grounds !== null) {
  59960. for (index = 0, cache = grounds.length; index < cache; index++) {
  59961. var parsedGround = grounds[index];
  59962. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  59963. }
  59964. }
  59965. // Planes
  59966. var planes = geometries.planes;
  59967. if (planes !== undefined && planes !== null) {
  59968. for (index = 0, cache = planes.length; index < cache; index++) {
  59969. var parsedPlane = planes[index];
  59970. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  59971. }
  59972. }
  59973. // TorusKnots
  59974. var torusKnots = geometries.torusKnots;
  59975. if (torusKnots !== undefined && torusKnots !== null) {
  59976. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  59977. var parsedTorusKnot = torusKnots[index];
  59978. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  59979. }
  59980. }
  59981. // VertexData
  59982. var vertexData = geometries.vertexData;
  59983. if (vertexData !== undefined && vertexData !== null) {
  59984. for (index = 0, cache = vertexData.length; index < cache; index++) {
  59985. var parsedVertexData = vertexData[index];
  59986. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  59987. }
  59988. }
  59989. addedGeometry.forEach(function (g) {
  59990. if (g) {
  59991. container.geometries.push(g);
  59992. }
  59993. });
  59994. }
  59995. // Transform nodes
  59996. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  59997. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  59998. var parsedTransformNode = parsedData.transformNodes[index];
  59999. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60000. container.transformNodes.push(node);
  60001. }
  60002. }
  60003. // Meshes
  60004. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60005. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60006. var parsedMesh = parsedData.meshes[index];
  60007. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60008. container.meshes.push(mesh);
  60009. log += (index === 0 ? "\n\tMeshes:" : "");
  60010. log += "\n\t\t" + mesh.toString(fullDetails);
  60011. }
  60012. }
  60013. // Cameras
  60014. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60015. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60016. var parsedCamera = parsedData.cameras[index];
  60017. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60018. container.cameras.push(camera);
  60019. log += (index === 0 ? "\n\tCameras:" : "");
  60020. log += "\n\t\t" + camera.toString(fullDetails);
  60021. }
  60022. }
  60023. // Browsing all the graph to connect the dots
  60024. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60025. var camera = scene.cameras[index];
  60026. if (camera._waitingParentId) {
  60027. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60028. camera._waitingParentId = null;
  60029. }
  60030. }
  60031. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60032. var light_1 = scene.lights[index];
  60033. if (light_1 && light_1._waitingParentId) {
  60034. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60035. light_1._waitingParentId = null;
  60036. }
  60037. }
  60038. // Sounds
  60039. // TODO: add sound
  60040. var loadedSounds = [];
  60041. var loadedSound;
  60042. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60043. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60044. var parsedSound = parsedData.sounds[index];
  60045. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60046. if (!parsedSound.url)
  60047. parsedSound.url = parsedSound.name;
  60048. if (!loadedSounds[parsedSound.url]) {
  60049. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60050. loadedSounds[parsedSound.url] = loadedSound;
  60051. container.sounds.push(loadedSound);
  60052. }
  60053. else {
  60054. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60055. }
  60056. }
  60057. else {
  60058. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60059. }
  60060. }
  60061. }
  60062. loadedSounds = [];
  60063. // Connect parents & children and parse actions
  60064. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  60065. var transformNode = scene.transformNodes[index];
  60066. if (transformNode._waitingParentId) {
  60067. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60068. transformNode._waitingParentId = null;
  60069. }
  60070. }
  60071. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60072. var mesh = scene.meshes[index];
  60073. if (mesh._waitingParentId) {
  60074. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60075. mesh._waitingParentId = null;
  60076. }
  60077. if (mesh._waitingActions) {
  60078. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60079. mesh._waitingActions = null;
  60080. }
  60081. }
  60082. // freeze world matrix application
  60083. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60084. var currentMesh = scene.meshes[index];
  60085. if (currentMesh._waitingFreezeWorldMatrix) {
  60086. currentMesh.freezeWorldMatrix();
  60087. currentMesh._waitingFreezeWorldMatrix = null;
  60088. }
  60089. else {
  60090. currentMesh.computeWorldMatrix(true);
  60091. }
  60092. }
  60093. // Particles Systems
  60094. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60095. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60096. var parsedParticleSystem = parsedData.particleSystems[index];
  60097. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60098. container.particleSystems.push(ps);
  60099. }
  60100. }
  60101. // Lens flares
  60102. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60103. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60104. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60105. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60106. container.lensFlareSystems.push(lf);
  60107. }
  60108. }
  60109. // Shadows
  60110. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60111. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60112. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60113. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60114. container.shadowGenerators.push(sg);
  60115. }
  60116. }
  60117. // Lights exclusions / inclusions
  60118. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60119. var light_2 = scene.lights[index];
  60120. // Excluded check
  60121. if (light_2._excludedMeshesIds.length > 0) {
  60122. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60123. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60124. if (excludedMesh) {
  60125. light_2.excludedMeshes.push(excludedMesh);
  60126. }
  60127. }
  60128. light_2._excludedMeshesIds = [];
  60129. }
  60130. // Included check
  60131. if (light_2._includedOnlyMeshesIds.length > 0) {
  60132. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60133. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60134. if (includedOnlyMesh) {
  60135. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60136. }
  60137. }
  60138. light_2._includedOnlyMeshesIds = [];
  60139. }
  60140. }
  60141. // Actions (scene)
  60142. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60143. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60144. }
  60145. if (!addToScene) {
  60146. container.removeAllFromScene();
  60147. }
  60148. }
  60149. catch (err) {
  60150. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60151. if (onError) {
  60152. onError(msg, err);
  60153. }
  60154. else {
  60155. BABYLON.Tools.Log(msg);
  60156. throw err;
  60157. }
  60158. }
  60159. finally {
  60160. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60161. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60162. }
  60163. }
  60164. return container;
  60165. };
  60166. BABYLON.SceneLoader.RegisterPlugin({
  60167. name: "babylon.js",
  60168. extensions: ".babylon",
  60169. canDirectLoad: function (data) {
  60170. if (data.indexOf("babylon") !== -1) {
  60171. return true;
  60172. }
  60173. return false;
  60174. },
  60175. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60176. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60177. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60178. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60179. // and avoid problems with multiple concurrent .babylon loads.
  60180. var log = "importMesh has failed JSON parse";
  60181. try {
  60182. var parsedData = JSON.parse(data);
  60183. log = "";
  60184. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60185. if (!meshesNames) {
  60186. meshesNames = null;
  60187. }
  60188. else if (!Array.isArray(meshesNames)) {
  60189. meshesNames = [meshesNames];
  60190. }
  60191. var hierarchyIds = new Array();
  60192. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60193. var loadedSkeletonsIds = [];
  60194. var loadedMaterialsIds = [];
  60195. var index;
  60196. var cache;
  60197. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60198. var parsedMesh = parsedData.meshes[index];
  60199. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60200. if (meshesNames !== null) {
  60201. // Remove found mesh name from list.
  60202. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60203. }
  60204. //Geometry?
  60205. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60206. //does the file contain geometries?
  60207. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60208. //find the correct geometry and add it to the scene
  60209. var found = false;
  60210. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60211. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60212. return;
  60213. }
  60214. else {
  60215. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60216. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60217. switch (geometryType) {
  60218. case "boxes":
  60219. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60220. break;
  60221. case "spheres":
  60222. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60223. break;
  60224. case "cylinders":
  60225. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60226. break;
  60227. case "toruses":
  60228. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60229. break;
  60230. case "grounds":
  60231. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60232. break;
  60233. case "planes":
  60234. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60235. break;
  60236. case "torusKnots":
  60237. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60238. break;
  60239. case "vertexData":
  60240. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60241. break;
  60242. }
  60243. found = true;
  60244. }
  60245. });
  60246. }
  60247. });
  60248. if (found === false) {
  60249. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60250. }
  60251. }
  60252. }
  60253. // Material ?
  60254. if (parsedMesh.materialId) {
  60255. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60256. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60257. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60258. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60259. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60260. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60261. var subMatId = parsedMultiMaterial.materials[matIndex];
  60262. loadedMaterialsIds.push(subMatId);
  60263. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60264. if (mat) {
  60265. log += "\n\tMaterial " + mat.toString(fullDetails);
  60266. }
  60267. }
  60268. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60269. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60270. if (mmat) {
  60271. materialFound = true;
  60272. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60273. }
  60274. break;
  60275. }
  60276. }
  60277. }
  60278. if (materialFound === false) {
  60279. loadedMaterialsIds.push(parsedMesh.materialId);
  60280. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60281. if (!mat) {
  60282. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60283. }
  60284. else {
  60285. log += "\n\tMaterial " + mat.toString(fullDetails);
  60286. }
  60287. }
  60288. }
  60289. // Skeleton ?
  60290. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60291. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60292. if (skeletonAlreadyLoaded === false) {
  60293. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60294. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60295. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60296. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60297. skeletons.push(skeleton);
  60298. loadedSkeletonsIds.push(parsedSkeleton.id);
  60299. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60300. }
  60301. }
  60302. }
  60303. }
  60304. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60305. meshes.push(mesh);
  60306. log += "\n\tMesh " + mesh.toString(fullDetails);
  60307. }
  60308. }
  60309. // Connecting parents
  60310. var currentMesh;
  60311. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60312. currentMesh = scene.meshes[index];
  60313. if (currentMesh._waitingParentId) {
  60314. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60315. currentMesh._waitingParentId = null;
  60316. }
  60317. }
  60318. // freeze and compute world matrix application
  60319. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60320. currentMesh = scene.meshes[index];
  60321. if (currentMesh._waitingFreezeWorldMatrix) {
  60322. currentMesh.freezeWorldMatrix();
  60323. currentMesh._waitingFreezeWorldMatrix = null;
  60324. }
  60325. else {
  60326. currentMesh.computeWorldMatrix(true);
  60327. }
  60328. }
  60329. }
  60330. // Particles
  60331. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60332. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60333. var parsedParticleSystem = parsedData.particleSystems[index];
  60334. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60335. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60336. }
  60337. }
  60338. }
  60339. return true;
  60340. }
  60341. catch (err) {
  60342. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60343. if (onError) {
  60344. onError(msg, err);
  60345. }
  60346. else {
  60347. BABYLON.Tools.Log(msg);
  60348. throw err;
  60349. }
  60350. }
  60351. finally {
  60352. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60353. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60354. }
  60355. }
  60356. return false;
  60357. },
  60358. load: function (scene, data, rootUrl, onError) {
  60359. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60360. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60361. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60362. // and avoid problems with multiple concurrent .babylon loads.
  60363. var log = "importScene has failed JSON parse";
  60364. try {
  60365. var parsedData = JSON.parse(data);
  60366. log = "";
  60367. // Scene
  60368. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60369. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60370. }
  60371. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60372. scene.autoClear = parsedData.autoClear;
  60373. }
  60374. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60375. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60376. }
  60377. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60378. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60379. }
  60380. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60381. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60382. }
  60383. // Fog
  60384. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60385. scene.fogMode = parsedData.fogMode;
  60386. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60387. scene.fogStart = parsedData.fogStart;
  60388. scene.fogEnd = parsedData.fogEnd;
  60389. scene.fogDensity = parsedData.fogDensity;
  60390. log += "\tFog mode for scene: ";
  60391. switch (scene.fogMode) {
  60392. // getters not compiling, so using hardcoded
  60393. case 1:
  60394. log += "exp\n";
  60395. break;
  60396. case 2:
  60397. log += "exp2\n";
  60398. break;
  60399. case 3:
  60400. log += "linear\n";
  60401. break;
  60402. }
  60403. }
  60404. //Physics
  60405. if (parsedData.physicsEnabled) {
  60406. var physicsPlugin;
  60407. if (parsedData.physicsEngine === "cannon") {
  60408. physicsPlugin = new BABYLON.CannonJSPlugin();
  60409. }
  60410. else if (parsedData.physicsEngine === "oimo") {
  60411. physicsPlugin = new BABYLON.OimoJSPlugin();
  60412. }
  60413. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60414. //else - default engine, which is currently oimo
  60415. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60416. scene.enablePhysics(physicsGravity, physicsPlugin);
  60417. }
  60418. // Metadata
  60419. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60420. scene.metadata = parsedData.metadata;
  60421. }
  60422. //collisions, if defined. otherwise, default is true
  60423. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60424. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60425. }
  60426. scene.workerCollisions = !!parsedData.workerCollisions;
  60427. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60428. if (!container) {
  60429. return false;
  60430. }
  60431. if (parsedData.autoAnimate) {
  60432. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60433. }
  60434. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60435. scene.setActiveCameraByID(parsedData.activeCameraID);
  60436. }
  60437. // Environment texture
  60438. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60439. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60440. if (parsedData.createDefaultSkybox === true) {
  60441. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60442. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60443. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60444. }
  60445. }
  60446. // Finish
  60447. return true;
  60448. }
  60449. catch (err) {
  60450. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60451. if (onError) {
  60452. onError(msg, err);
  60453. }
  60454. else {
  60455. BABYLON.Tools.Log(msg);
  60456. throw err;
  60457. }
  60458. }
  60459. finally {
  60460. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60461. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60462. }
  60463. }
  60464. return false;
  60465. },
  60466. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60467. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60468. return container;
  60469. }
  60470. });
  60471. })(BABYLON || (BABYLON = {}));
  60472. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60473. var BABYLON;
  60474. (function (BABYLON) {
  60475. var FilesInput = /** @class */ (function () {
  60476. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60477. this.onProcessFileCallback = function () { return true; };
  60478. this._engine = engine;
  60479. this._currentScene = scene;
  60480. this._sceneLoadedCallback = sceneLoadedCallback;
  60481. this._progressCallback = progressCallback;
  60482. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60483. this._textureLoadingCallback = textureLoadingCallback;
  60484. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60485. this._onReloadCallback = onReloadCallback;
  60486. this._errorCallback = errorCallback;
  60487. }
  60488. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60489. var _this = this;
  60490. if (elementToMonitor) {
  60491. this._elementToMonitor = elementToMonitor;
  60492. this._dragEnterHandler = function (e) { _this.drag(e); };
  60493. this._dragOverHandler = function (e) { _this.drag(e); };
  60494. this._dropHandler = function (e) { _this.drop(e); };
  60495. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60496. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60497. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60498. }
  60499. };
  60500. FilesInput.prototype.dispose = function () {
  60501. if (!this._elementToMonitor) {
  60502. return;
  60503. }
  60504. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60505. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60506. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60507. };
  60508. FilesInput.prototype.renderFunction = function () {
  60509. if (this._additionalRenderLoopLogicCallback) {
  60510. this._additionalRenderLoopLogicCallback();
  60511. }
  60512. if (this._currentScene) {
  60513. if (this._textureLoadingCallback) {
  60514. var remaining = this._currentScene.getWaitingItemsCount();
  60515. if (remaining > 0) {
  60516. this._textureLoadingCallback(remaining);
  60517. }
  60518. }
  60519. this._currentScene.render();
  60520. }
  60521. };
  60522. FilesInput.prototype.drag = function (e) {
  60523. e.stopPropagation();
  60524. e.preventDefault();
  60525. };
  60526. FilesInput.prototype.drop = function (eventDrop) {
  60527. eventDrop.stopPropagation();
  60528. eventDrop.preventDefault();
  60529. this.loadFiles(eventDrop);
  60530. };
  60531. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60532. var _this = this;
  60533. var reader = folder.createReader();
  60534. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60535. reader.readEntries(function (entries) {
  60536. remaining.count += entries.length;
  60537. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60538. var entry = entries_1[_i];
  60539. if (entry.isFile) {
  60540. entry.file(function (file) {
  60541. file.correctName = relativePath + file.name;
  60542. files.push(file);
  60543. if (--remaining.count === 0) {
  60544. callback();
  60545. }
  60546. });
  60547. }
  60548. else if (entry.isDirectory) {
  60549. _this._traverseFolder(entry, files, remaining, callback);
  60550. }
  60551. }
  60552. if (--remaining.count) {
  60553. callback();
  60554. }
  60555. });
  60556. };
  60557. FilesInput.prototype._processFiles = function (files) {
  60558. for (var i = 0; i < files.length; i++) {
  60559. var name = files[i].correctName.toLowerCase();
  60560. var extension = name.split('.').pop();
  60561. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60562. continue;
  60563. }
  60564. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60565. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60566. this._sceneFileToLoad = files[i];
  60567. }
  60568. else {
  60569. FilesInput.FilesToLoad[name] = files[i];
  60570. }
  60571. }
  60572. };
  60573. FilesInput.prototype.loadFiles = function (event) {
  60574. var _this = this;
  60575. if (this._startingProcessingFilesCallback)
  60576. this._startingProcessingFilesCallback();
  60577. // Handling data transfer via drag'n'drop
  60578. if (event && event.dataTransfer && event.dataTransfer.files) {
  60579. this._filesToLoad = event.dataTransfer.files;
  60580. }
  60581. // Handling files from input files
  60582. if (event && event.target && event.target.files) {
  60583. this._filesToLoad = event.target.files;
  60584. }
  60585. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60586. var files_1 = new Array();
  60587. var folders = [];
  60588. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60589. for (var i = 0; i < this._filesToLoad.length; i++) {
  60590. var fileToLoad = this._filesToLoad[i];
  60591. var name_1 = fileToLoad.name.toLowerCase();
  60592. var entry = void 0;
  60593. fileToLoad.correctName = name_1;
  60594. if (items) {
  60595. var item = items[i];
  60596. if (item.getAsEntry) {
  60597. entry = item.getAsEntry();
  60598. }
  60599. else if (item.webkitGetAsEntry) {
  60600. entry = item.webkitGetAsEntry();
  60601. }
  60602. }
  60603. if (!entry) {
  60604. files_1.push(fileToLoad);
  60605. }
  60606. else {
  60607. if (entry.isDirectory) {
  60608. folders.push(entry);
  60609. }
  60610. else {
  60611. files_1.push(fileToLoad);
  60612. }
  60613. }
  60614. }
  60615. if (folders.length === 0) {
  60616. this._processFiles(files_1);
  60617. this._processReload();
  60618. }
  60619. else {
  60620. var remaining = { count: folders.length };
  60621. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60622. var folder = folders_1[_i];
  60623. this._traverseFolder(folder, files_1, remaining, function () {
  60624. _this._processFiles(files_1);
  60625. if (remaining.count === 0) {
  60626. _this._processReload();
  60627. }
  60628. });
  60629. }
  60630. }
  60631. }
  60632. };
  60633. FilesInput.prototype._processReload = function () {
  60634. if (this._onReloadCallback) {
  60635. this._onReloadCallback(this._sceneFileToLoad);
  60636. }
  60637. else {
  60638. this.reload();
  60639. }
  60640. };
  60641. FilesInput.prototype.reload = function () {
  60642. var _this = this;
  60643. // If a scene file has been provided
  60644. if (this._sceneFileToLoad) {
  60645. if (this._currentScene) {
  60646. if (BABYLON.Tools.errorsCount > 0) {
  60647. BABYLON.Tools.ClearLogCache();
  60648. }
  60649. this._engine.stopRenderLoop();
  60650. this._currentScene.dispose();
  60651. }
  60652. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60653. if (_this._progressCallback) {
  60654. _this._progressCallback(progress);
  60655. }
  60656. }).then(function (scene) {
  60657. _this._currentScene = scene;
  60658. if (_this._sceneLoadedCallback) {
  60659. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60660. }
  60661. // Wait for textures and shaders to be ready
  60662. _this._currentScene.executeWhenReady(function () {
  60663. _this._engine.runRenderLoop(function () {
  60664. _this.renderFunction();
  60665. });
  60666. });
  60667. }).catch(function (error) {
  60668. if (_this._errorCallback) {
  60669. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60670. }
  60671. });
  60672. }
  60673. else {
  60674. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60675. }
  60676. };
  60677. FilesInput.FilesToLoad = {};
  60678. return FilesInput;
  60679. }());
  60680. BABYLON.FilesInput = FilesInput;
  60681. })(BABYLON || (BABYLON = {}));
  60682. //# sourceMappingURL=babylon.filesInput.js.map
  60683. var BABYLON;
  60684. (function (BABYLON) {
  60685. /**
  60686. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60687. * The underlying implementation relies on an associative array to ensure the best performances.
  60688. * The value can be anything including 'null' but except 'undefined'
  60689. */
  60690. var StringDictionary = /** @class */ (function () {
  60691. function StringDictionary() {
  60692. this._count = 0;
  60693. this._data = {};
  60694. }
  60695. /**
  60696. * This will clear this dictionary and copy the content from the 'source' one.
  60697. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60698. * @param source the dictionary to take the content from and copy to this dictionary
  60699. */
  60700. StringDictionary.prototype.copyFrom = function (source) {
  60701. var _this = this;
  60702. this.clear();
  60703. source.forEach(function (t, v) { return _this.add(t, v); });
  60704. };
  60705. /**
  60706. * Get a value based from its key
  60707. * @param key the given key to get the matching value from
  60708. * @return the value if found, otherwise undefined is returned
  60709. */
  60710. StringDictionary.prototype.get = function (key) {
  60711. var val = this._data[key];
  60712. if (val !== undefined) {
  60713. return val;
  60714. }
  60715. return undefined;
  60716. };
  60717. /**
  60718. * Get a value from its key or add it if it doesn't exist.
  60719. * This method will ensure you that a given key/data will be present in the dictionary.
  60720. * @param key the given key to get the matching value from
  60721. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60722. * The factory will only be invoked if there's no data for the given key.
  60723. * @return the value corresponding to the key.
  60724. */
  60725. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60726. var val = this.get(key);
  60727. if (val !== undefined) {
  60728. return val;
  60729. }
  60730. val = factory(key);
  60731. if (val) {
  60732. this.add(key, val);
  60733. }
  60734. return val;
  60735. };
  60736. /**
  60737. * Get a value from its key if present in the dictionary otherwise add it
  60738. * @param key the key to get the value from
  60739. * @param val if there's no such key/value pair in the dictionary add it with this value
  60740. * @return the value corresponding to the key
  60741. */
  60742. StringDictionary.prototype.getOrAdd = function (key, val) {
  60743. var curVal = this.get(key);
  60744. if (curVal !== undefined) {
  60745. return curVal;
  60746. }
  60747. this.add(key, val);
  60748. return val;
  60749. };
  60750. /**
  60751. * Check if there's a given key in the dictionary
  60752. * @param key the key to check for
  60753. * @return true if the key is present, false otherwise
  60754. */
  60755. StringDictionary.prototype.contains = function (key) {
  60756. return this._data[key] !== undefined;
  60757. };
  60758. /**
  60759. * Add a new key and its corresponding value
  60760. * @param key the key to add
  60761. * @param value the value corresponding to the key
  60762. * @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
  60763. */
  60764. StringDictionary.prototype.add = function (key, value) {
  60765. if (this._data[key] !== undefined) {
  60766. return false;
  60767. }
  60768. this._data[key] = value;
  60769. ++this._count;
  60770. return true;
  60771. };
  60772. StringDictionary.prototype.set = function (key, value) {
  60773. if (this._data[key] === undefined) {
  60774. return false;
  60775. }
  60776. this._data[key] = value;
  60777. return true;
  60778. };
  60779. /**
  60780. * Get the element of the given key and remove it from the dictionary
  60781. * @param key
  60782. */
  60783. StringDictionary.prototype.getAndRemove = function (key) {
  60784. var val = this.get(key);
  60785. if (val !== undefined) {
  60786. delete this._data[key];
  60787. --this._count;
  60788. return val;
  60789. }
  60790. return null;
  60791. };
  60792. /**
  60793. * Remove a key/value from the dictionary.
  60794. * @param key the key to remove
  60795. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60796. */
  60797. StringDictionary.prototype.remove = function (key) {
  60798. if (this.contains(key)) {
  60799. delete this._data[key];
  60800. --this._count;
  60801. return true;
  60802. }
  60803. return false;
  60804. };
  60805. /**
  60806. * Clear the whole content of the dictionary
  60807. */
  60808. StringDictionary.prototype.clear = function () {
  60809. this._data = {};
  60810. this._count = 0;
  60811. };
  60812. Object.defineProperty(StringDictionary.prototype, "count", {
  60813. get: function () {
  60814. return this._count;
  60815. },
  60816. enumerable: true,
  60817. configurable: true
  60818. });
  60819. /**
  60820. * Execute a callback on each key/val of the dictionary.
  60821. * Note that you can remove any element in this dictionary in the callback implementation
  60822. * @param callback the callback to execute on a given key/value pair
  60823. */
  60824. StringDictionary.prototype.forEach = function (callback) {
  60825. for (var cur in this._data) {
  60826. var val = this._data[cur];
  60827. callback(cur, val);
  60828. }
  60829. };
  60830. /**
  60831. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60832. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60833. * Note that you can remove any element in this dictionary in the callback implementation
  60834. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60835. */
  60836. StringDictionary.prototype.first = function (callback) {
  60837. for (var cur in this._data) {
  60838. var val = this._data[cur];
  60839. var res = callback(cur, val);
  60840. if (res) {
  60841. return res;
  60842. }
  60843. }
  60844. return null;
  60845. };
  60846. return StringDictionary;
  60847. }());
  60848. BABYLON.StringDictionary = StringDictionary;
  60849. })(BABYLON || (BABYLON = {}));
  60850. //# sourceMappingURL=babylon.stringDictionary.js.map
  60851. var BABYLON;
  60852. (function (BABYLON) {
  60853. var Tags = /** @class */ (function () {
  60854. function Tags() {
  60855. }
  60856. Tags.EnableFor = function (obj) {
  60857. obj._tags = obj._tags || {};
  60858. obj.hasTags = function () {
  60859. return Tags.HasTags(obj);
  60860. };
  60861. obj.addTags = function (tagsString) {
  60862. return Tags.AddTagsTo(obj, tagsString);
  60863. };
  60864. obj.removeTags = function (tagsString) {
  60865. return Tags.RemoveTagsFrom(obj, tagsString);
  60866. };
  60867. obj.matchesTagsQuery = function (tagsQuery) {
  60868. return Tags.MatchesQuery(obj, tagsQuery);
  60869. };
  60870. };
  60871. Tags.DisableFor = function (obj) {
  60872. delete obj._tags;
  60873. delete obj.hasTags;
  60874. delete obj.addTags;
  60875. delete obj.removeTags;
  60876. delete obj.matchesTagsQuery;
  60877. };
  60878. Tags.HasTags = function (obj) {
  60879. if (!obj._tags) {
  60880. return false;
  60881. }
  60882. return !BABYLON.Tools.IsEmpty(obj._tags);
  60883. };
  60884. Tags.GetTags = function (obj, asString) {
  60885. if (asString === void 0) { asString = true; }
  60886. if (!obj._tags) {
  60887. return null;
  60888. }
  60889. if (asString) {
  60890. var tagsArray = [];
  60891. for (var tag in obj._tags) {
  60892. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60893. tagsArray.push(tag);
  60894. }
  60895. }
  60896. return tagsArray.join(" ");
  60897. }
  60898. else {
  60899. return obj._tags;
  60900. }
  60901. };
  60902. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60903. // a tag cannot start with '||', '&&', and '!'
  60904. // it cannot contain whitespaces
  60905. Tags.AddTagsTo = function (obj, tagsString) {
  60906. if (!tagsString) {
  60907. return;
  60908. }
  60909. if (typeof tagsString !== "string") {
  60910. return;
  60911. }
  60912. var tags = tagsString.split(" ");
  60913. tags.forEach(function (tag, index, array) {
  60914. Tags._AddTagTo(obj, tag);
  60915. });
  60916. };
  60917. Tags._AddTagTo = function (obj, tag) {
  60918. tag = tag.trim();
  60919. if (tag === "" || tag === "true" || tag === "false") {
  60920. return;
  60921. }
  60922. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60923. return;
  60924. }
  60925. Tags.EnableFor(obj);
  60926. obj._tags[tag] = true;
  60927. };
  60928. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60929. if (!Tags.HasTags(obj)) {
  60930. return;
  60931. }
  60932. var tags = tagsString.split(" ");
  60933. for (var t in tags) {
  60934. Tags._RemoveTagFrom(obj, tags[t]);
  60935. }
  60936. };
  60937. Tags._RemoveTagFrom = function (obj, tag) {
  60938. delete obj._tags[tag];
  60939. };
  60940. Tags.MatchesQuery = function (obj, tagsQuery) {
  60941. if (tagsQuery === undefined) {
  60942. return true;
  60943. }
  60944. if (tagsQuery === "") {
  60945. return Tags.HasTags(obj);
  60946. }
  60947. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  60948. };
  60949. return Tags;
  60950. }());
  60951. BABYLON.Tags = Tags;
  60952. })(BABYLON || (BABYLON = {}));
  60953. //# sourceMappingURL=babylon.tags.js.map
  60954. var BABYLON;
  60955. (function (BABYLON) {
  60956. var AndOrNotEvaluator = /** @class */ (function () {
  60957. function AndOrNotEvaluator() {
  60958. }
  60959. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  60960. if (!query.match(/\([^\(\)]*\)/g)) {
  60961. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  60962. }
  60963. else {
  60964. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  60965. // remove parenthesis
  60966. r = r.slice(1, r.length - 1);
  60967. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  60968. });
  60969. }
  60970. if (query === "true") {
  60971. return true;
  60972. }
  60973. if (query === "false") {
  60974. return false;
  60975. }
  60976. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  60977. };
  60978. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  60979. evaluateCallback = evaluateCallback || (function (r) {
  60980. return r === "true" ? true : false;
  60981. });
  60982. var result;
  60983. var or = parenthesisContent.split("||");
  60984. for (var i in or) {
  60985. if (or.hasOwnProperty(i)) {
  60986. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  60987. var and = ori.split("&&");
  60988. if (and.length > 1) {
  60989. for (var j = 0; j < and.length; ++j) {
  60990. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  60991. if (andj !== "true" && andj !== "false") {
  60992. if (andj[0] === "!") {
  60993. result = !evaluateCallback(andj.substring(1));
  60994. }
  60995. else {
  60996. result = evaluateCallback(andj);
  60997. }
  60998. }
  60999. else {
  61000. result = andj === "true" ? true : false;
  61001. }
  61002. if (!result) {
  61003. ori = "false";
  61004. break;
  61005. }
  61006. }
  61007. }
  61008. if (result || ori === "true") {
  61009. result = true;
  61010. break;
  61011. }
  61012. // result equals false (or undefined)
  61013. if (ori !== "true" && ori !== "false") {
  61014. if (ori[0] === "!") {
  61015. result = !evaluateCallback(ori.substring(1));
  61016. }
  61017. else {
  61018. result = evaluateCallback(ori);
  61019. }
  61020. }
  61021. else {
  61022. result = ori === "true" ? true : false;
  61023. }
  61024. }
  61025. }
  61026. // the whole parenthesis scope is replaced by 'true' or 'false'
  61027. return result ? "true" : "false";
  61028. };
  61029. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61030. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61031. // remove whitespaces
  61032. r = r.replace(/[\s]/g, function () { return ""; });
  61033. return r.length % 2 ? "!" : "";
  61034. });
  61035. booleanString = booleanString.trim();
  61036. if (booleanString === "!true") {
  61037. booleanString = "false";
  61038. }
  61039. else if (booleanString === "!false") {
  61040. booleanString = "true";
  61041. }
  61042. return booleanString;
  61043. };
  61044. return AndOrNotEvaluator;
  61045. }());
  61046. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61047. })(BABYLON || (BABYLON = {}));
  61048. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61049. var BABYLON;
  61050. (function (BABYLON) {
  61051. var Database = /** @class */ (function () {
  61052. function Database(urlToScene, callbackManifestChecked) {
  61053. // Handling various flavors of prefixed version of IndexedDB
  61054. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61055. this.callbackManifestChecked = callbackManifestChecked;
  61056. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61057. this.db = null;
  61058. this._enableSceneOffline = false;
  61059. this._enableTexturesOffline = false;
  61060. this.manifestVersionFound = 0;
  61061. this.mustUpdateRessources = false;
  61062. this.hasReachedQuota = false;
  61063. if (!Database.IDBStorageEnabled) {
  61064. this.callbackManifestChecked(true);
  61065. }
  61066. else {
  61067. this.checkManifestFile();
  61068. }
  61069. }
  61070. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61071. get: function () {
  61072. return this._enableSceneOffline;
  61073. },
  61074. enumerable: true,
  61075. configurable: true
  61076. });
  61077. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61078. get: function () {
  61079. return this._enableTexturesOffline;
  61080. },
  61081. enumerable: true,
  61082. configurable: true
  61083. });
  61084. Database.prototype.checkManifestFile = function () {
  61085. var _this = this;
  61086. var noManifestFile = function () {
  61087. _this._enableSceneOffline = false;
  61088. _this._enableTexturesOffline = false;
  61089. _this.callbackManifestChecked(false);
  61090. };
  61091. var timeStampUsed = false;
  61092. var manifestURL = this.currentSceneUrl + ".manifest";
  61093. var xhr = new XMLHttpRequest();
  61094. if (navigator.onLine) {
  61095. // Adding a timestamp to by-pass browsers' cache
  61096. timeStampUsed = true;
  61097. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61098. }
  61099. xhr.open("GET", manifestURL, true);
  61100. xhr.addEventListener("load", function () {
  61101. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61102. try {
  61103. var manifestFile = JSON.parse(xhr.response);
  61104. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61105. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61106. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61107. _this.manifestVersionFound = manifestFile.version;
  61108. }
  61109. if (_this.callbackManifestChecked) {
  61110. _this.callbackManifestChecked(true);
  61111. }
  61112. }
  61113. catch (ex) {
  61114. noManifestFile();
  61115. }
  61116. }
  61117. else {
  61118. noManifestFile();
  61119. }
  61120. }, false);
  61121. xhr.addEventListener("error", function (event) {
  61122. if (timeStampUsed) {
  61123. timeStampUsed = false;
  61124. // Let's retry without the timeStamp
  61125. // It could fail when coupled with HTML5 Offline API
  61126. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61127. xhr.open("GET", retryManifestURL, true);
  61128. xhr.send();
  61129. }
  61130. else {
  61131. noManifestFile();
  61132. }
  61133. }, false);
  61134. try {
  61135. xhr.send();
  61136. }
  61137. catch (ex) {
  61138. BABYLON.Tools.Error("Error on XHR send request.");
  61139. this.callbackManifestChecked(false);
  61140. }
  61141. };
  61142. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61143. var _this = this;
  61144. var handleError = function () {
  61145. _this.isSupported = false;
  61146. if (errorCallback)
  61147. errorCallback();
  61148. };
  61149. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61150. // Your browser doesn't support IndexedDB
  61151. this.isSupported = false;
  61152. if (errorCallback)
  61153. errorCallback();
  61154. }
  61155. else {
  61156. // If the DB hasn't been opened or created yet
  61157. if (!this.db) {
  61158. this.hasReachedQuota = false;
  61159. this.isSupported = true;
  61160. var request = this.idbFactory.open("babylonjs", 1);
  61161. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61162. request.onerror = function (event) {
  61163. handleError();
  61164. };
  61165. // executes when a version change transaction cannot complete due to other active transactions
  61166. request.onblocked = function (event) {
  61167. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61168. handleError();
  61169. };
  61170. // DB has been opened successfully
  61171. request.onsuccess = function (event) {
  61172. _this.db = request.result;
  61173. successCallback();
  61174. };
  61175. // Initialization of the DB. Creating Scenes & Textures stores
  61176. request.onupgradeneeded = function (event) {
  61177. _this.db = (event.target).result;
  61178. if (_this.db) {
  61179. try {
  61180. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61181. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61182. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61183. }
  61184. catch (ex) {
  61185. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61186. handleError();
  61187. }
  61188. }
  61189. };
  61190. }
  61191. else {
  61192. if (successCallback)
  61193. successCallback();
  61194. }
  61195. }
  61196. };
  61197. Database.prototype.loadImageFromDB = function (url, image) {
  61198. var _this = this;
  61199. var completeURL = Database.ReturnFullUrlLocation(url);
  61200. var saveAndLoadImage = function () {
  61201. if (!_this.hasReachedQuota && _this.db !== null) {
  61202. // the texture is not yet in the DB, let's try to save it
  61203. _this._saveImageIntoDBAsync(completeURL, image);
  61204. }
  61205. else {
  61206. image.src = url;
  61207. }
  61208. };
  61209. if (!this.mustUpdateRessources) {
  61210. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61211. }
  61212. else {
  61213. saveAndLoadImage();
  61214. }
  61215. };
  61216. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61217. if (this.isSupported && this.db !== null) {
  61218. var texture;
  61219. var transaction = this.db.transaction(["textures"]);
  61220. transaction.onabort = function (event) {
  61221. image.src = url;
  61222. };
  61223. transaction.oncomplete = function (event) {
  61224. var blobTextureURL;
  61225. if (texture) {
  61226. var URL = window.URL || window.webkitURL;
  61227. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61228. image.onerror = function () {
  61229. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61230. image.src = url;
  61231. };
  61232. image.src = blobTextureURL;
  61233. }
  61234. else {
  61235. notInDBCallback();
  61236. }
  61237. };
  61238. var getRequest = transaction.objectStore("textures").get(url);
  61239. getRequest.onsuccess = function (event) {
  61240. texture = (event.target).result;
  61241. };
  61242. getRequest.onerror = function (event) {
  61243. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61244. image.src = url;
  61245. };
  61246. }
  61247. else {
  61248. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61249. image.src = url;
  61250. }
  61251. };
  61252. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61253. var _this = this;
  61254. if (this.isSupported) {
  61255. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61256. var generateBlobUrl = function () {
  61257. var blobTextureURL;
  61258. if (blob) {
  61259. var URL = window.URL || window.webkitURL;
  61260. try {
  61261. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61262. }
  61263. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61264. catch (ex) {
  61265. blobTextureURL = URL.createObjectURL(blob);
  61266. }
  61267. }
  61268. if (blobTextureURL) {
  61269. image.src = blobTextureURL;
  61270. }
  61271. };
  61272. if (Database.IsUASupportingBlobStorage) {
  61273. var xhr = new XMLHttpRequest(), blob;
  61274. xhr.open("GET", url, true);
  61275. xhr.responseType = "blob";
  61276. xhr.addEventListener("load", function () {
  61277. if (xhr.status === 200 && _this.db) {
  61278. // Blob as response (XHR2)
  61279. blob = xhr.response;
  61280. var transaction = _this.db.transaction(["textures"], "readwrite");
  61281. // the transaction could abort because of a QuotaExceededError error
  61282. transaction.onabort = function (event) {
  61283. try {
  61284. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61285. var srcElement = (event.srcElement || event.target);
  61286. var error = srcElement.error;
  61287. if (error && error.name === "QuotaExceededError") {
  61288. _this.hasReachedQuota = true;
  61289. }
  61290. }
  61291. catch (ex) { }
  61292. generateBlobUrl();
  61293. };
  61294. transaction.oncomplete = function (event) {
  61295. generateBlobUrl();
  61296. };
  61297. var newTexture = { textureUrl: url, data: blob };
  61298. try {
  61299. // Put the blob into the dabase
  61300. var addRequest = transaction.objectStore("textures").put(newTexture);
  61301. addRequest.onsuccess = function (event) {
  61302. };
  61303. addRequest.onerror = function (event) {
  61304. generateBlobUrl();
  61305. };
  61306. }
  61307. catch (ex) {
  61308. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61309. if (ex.code === 25) {
  61310. Database.IsUASupportingBlobStorage = false;
  61311. }
  61312. image.src = url;
  61313. }
  61314. }
  61315. else {
  61316. image.src = url;
  61317. }
  61318. }, false);
  61319. xhr.addEventListener("error", function (event) {
  61320. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61321. image.src = url;
  61322. }, false);
  61323. xhr.send();
  61324. }
  61325. else {
  61326. image.src = url;
  61327. }
  61328. }
  61329. else {
  61330. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61331. image.src = url;
  61332. }
  61333. };
  61334. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61335. var _this = this;
  61336. var updateVersion = function () {
  61337. // the version is not yet in the DB or we need to update it
  61338. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61339. };
  61340. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61341. };
  61342. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61343. var _this = this;
  61344. if (this.isSupported && this.db) {
  61345. var version;
  61346. try {
  61347. var transaction = this.db.transaction(["versions"]);
  61348. transaction.oncomplete = function (event) {
  61349. if (version) {
  61350. // If the version in the JSON file is > than the version in DB
  61351. if (_this.manifestVersionFound > version.data) {
  61352. _this.mustUpdateRessources = true;
  61353. updateInDBCallback();
  61354. }
  61355. else {
  61356. callback(version.data);
  61357. }
  61358. }
  61359. else {
  61360. _this.mustUpdateRessources = true;
  61361. updateInDBCallback();
  61362. }
  61363. };
  61364. transaction.onabort = function (event) {
  61365. callback(-1);
  61366. };
  61367. var getRequest = transaction.objectStore("versions").get(url);
  61368. getRequest.onsuccess = function (event) {
  61369. version = (event.target).result;
  61370. };
  61371. getRequest.onerror = function (event) {
  61372. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61373. callback(-1);
  61374. };
  61375. }
  61376. catch (ex) {
  61377. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61378. callback(-1);
  61379. }
  61380. }
  61381. else {
  61382. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61383. callback(-1);
  61384. }
  61385. };
  61386. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61387. var _this = this;
  61388. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61389. try {
  61390. // Open a transaction to the database
  61391. var transaction = this.db.transaction(["versions"], "readwrite");
  61392. // the transaction could abort because of a QuotaExceededError error
  61393. transaction.onabort = function (event) {
  61394. try {
  61395. var error = event.srcElement['error'];
  61396. if (error && error.name === "QuotaExceededError") {
  61397. _this.hasReachedQuota = true;
  61398. }
  61399. }
  61400. catch (ex) { }
  61401. callback(-1);
  61402. };
  61403. transaction.oncomplete = function (event) {
  61404. callback(_this.manifestVersionFound);
  61405. };
  61406. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61407. // Put the scene into the database
  61408. var addRequest = transaction.objectStore("versions").put(newVersion);
  61409. addRequest.onsuccess = function (event) {
  61410. };
  61411. addRequest.onerror = function (event) {
  61412. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61413. };
  61414. }
  61415. catch (ex) {
  61416. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61417. callback(-1);
  61418. }
  61419. }
  61420. else {
  61421. callback(-1);
  61422. }
  61423. };
  61424. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61425. var _this = this;
  61426. var completeUrl = Database.ReturnFullUrlLocation(url);
  61427. var saveAndLoadFile = function () {
  61428. // the scene is not yet in the DB, let's try to save it
  61429. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61430. };
  61431. this._checkVersionFromDB(completeUrl, function (version) {
  61432. if (version !== -1) {
  61433. if (!_this.mustUpdateRessources) {
  61434. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61435. }
  61436. else {
  61437. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61438. }
  61439. }
  61440. else {
  61441. if (errorCallback) {
  61442. errorCallback();
  61443. }
  61444. }
  61445. });
  61446. };
  61447. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61448. if (this.isSupported && this.db) {
  61449. var targetStore;
  61450. if (url.indexOf(".babylon") !== -1) {
  61451. targetStore = "scenes";
  61452. }
  61453. else {
  61454. targetStore = "textures";
  61455. }
  61456. var file;
  61457. var transaction = this.db.transaction([targetStore]);
  61458. transaction.oncomplete = function (event) {
  61459. if (file) {
  61460. callback(file.data);
  61461. }
  61462. else {
  61463. notInDBCallback();
  61464. }
  61465. };
  61466. transaction.onabort = function (event) {
  61467. notInDBCallback();
  61468. };
  61469. var getRequest = transaction.objectStore(targetStore).get(url);
  61470. getRequest.onsuccess = function (event) {
  61471. file = (event.target).result;
  61472. };
  61473. getRequest.onerror = function (event) {
  61474. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61475. notInDBCallback();
  61476. };
  61477. }
  61478. else {
  61479. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61480. callback();
  61481. }
  61482. };
  61483. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61484. var _this = this;
  61485. if (this.isSupported) {
  61486. var targetStore;
  61487. if (url.indexOf(".babylon") !== -1) {
  61488. targetStore = "scenes";
  61489. }
  61490. else {
  61491. targetStore = "textures";
  61492. }
  61493. // Create XHR
  61494. var xhr = new XMLHttpRequest();
  61495. var fileData;
  61496. xhr.open("GET", url, true);
  61497. if (useArrayBuffer) {
  61498. xhr.responseType = "arraybuffer";
  61499. }
  61500. if (progressCallback) {
  61501. xhr.onprogress = progressCallback;
  61502. }
  61503. xhr.addEventListener("load", function () {
  61504. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61505. // Blob as response (XHR2)
  61506. //fileData = xhr.responseText;
  61507. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61508. if (!_this.hasReachedQuota && _this.db) {
  61509. // Open a transaction to the database
  61510. var transaction = _this.db.transaction([targetStore], "readwrite");
  61511. // the transaction could abort because of a QuotaExceededError error
  61512. transaction.onabort = function (event) {
  61513. try {
  61514. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61515. var error = event.srcElement['error'];
  61516. if (error && error.name === "QuotaExceededError") {
  61517. _this.hasReachedQuota = true;
  61518. }
  61519. }
  61520. catch (ex) { }
  61521. callback(fileData);
  61522. };
  61523. transaction.oncomplete = function (event) {
  61524. callback(fileData);
  61525. };
  61526. var newFile;
  61527. if (targetStore === "scenes") {
  61528. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61529. }
  61530. else {
  61531. newFile = { textureUrl: url, data: fileData };
  61532. }
  61533. try {
  61534. // Put the scene into the database
  61535. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61536. addRequest.onsuccess = function (event) {
  61537. };
  61538. addRequest.onerror = function (event) {
  61539. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61540. };
  61541. }
  61542. catch (ex) {
  61543. callback(fileData);
  61544. }
  61545. }
  61546. else {
  61547. callback(fileData);
  61548. }
  61549. }
  61550. else {
  61551. callback();
  61552. }
  61553. }, false);
  61554. xhr.addEventListener("error", function (event) {
  61555. BABYLON.Tools.Error("error on XHR request.");
  61556. callback();
  61557. }, false);
  61558. xhr.send();
  61559. }
  61560. else {
  61561. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61562. callback();
  61563. }
  61564. };
  61565. Database.IsUASupportingBlobStorage = true;
  61566. Database.IDBStorageEnabled = true;
  61567. Database.parseURL = function (url) {
  61568. var a = document.createElement('a');
  61569. a.href = url;
  61570. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61571. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61572. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61573. return absLocation;
  61574. };
  61575. Database.ReturnFullUrlLocation = function (url) {
  61576. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61577. return (Database.parseURL(window.location.href) + url);
  61578. }
  61579. else {
  61580. return url;
  61581. }
  61582. };
  61583. return Database;
  61584. }());
  61585. BABYLON.Database = Database;
  61586. })(BABYLON || (BABYLON = {}));
  61587. //# sourceMappingURL=babylon.database.js.map
  61588. var BABYLON;
  61589. (function (BABYLON) {
  61590. var FresnelParameters = /** @class */ (function () {
  61591. function FresnelParameters() {
  61592. this._isEnabled = true;
  61593. this.leftColor = BABYLON.Color3.White();
  61594. this.rightColor = BABYLON.Color3.Black();
  61595. this.bias = 0;
  61596. this.power = 1;
  61597. }
  61598. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61599. get: function () {
  61600. return this._isEnabled;
  61601. },
  61602. set: function (value) {
  61603. if (this._isEnabled === value) {
  61604. return;
  61605. }
  61606. this._isEnabled = value;
  61607. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61608. },
  61609. enumerable: true,
  61610. configurable: true
  61611. });
  61612. FresnelParameters.prototype.clone = function () {
  61613. var newFresnelParameters = new FresnelParameters();
  61614. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61615. return newFresnelParameters;
  61616. };
  61617. FresnelParameters.prototype.serialize = function () {
  61618. var serializationObject = {};
  61619. serializationObject.isEnabled = this.isEnabled;
  61620. serializationObject.leftColor = this.leftColor;
  61621. serializationObject.rightColor = this.rightColor;
  61622. serializationObject.bias = this.bias;
  61623. serializationObject.power = this.power;
  61624. return serializationObject;
  61625. };
  61626. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61627. var fresnelParameters = new FresnelParameters();
  61628. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61629. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61630. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61631. fresnelParameters.bias = parsedFresnelParameters.bias;
  61632. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61633. return fresnelParameters;
  61634. };
  61635. return FresnelParameters;
  61636. }());
  61637. BABYLON.FresnelParameters = FresnelParameters;
  61638. })(BABYLON || (BABYLON = {}));
  61639. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61640. var BABYLON;
  61641. (function (BABYLON) {
  61642. var MultiMaterial = /** @class */ (function (_super) {
  61643. __extends(MultiMaterial, _super);
  61644. function MultiMaterial(name, scene) {
  61645. var _this = _super.call(this, name, scene, true) || this;
  61646. scene.multiMaterials.push(_this);
  61647. _this.subMaterials = new Array();
  61648. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61649. return _this;
  61650. }
  61651. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61652. get: function () {
  61653. return this._subMaterials;
  61654. },
  61655. set: function (value) {
  61656. this._subMaterials = value;
  61657. this._hookArray(value);
  61658. },
  61659. enumerable: true,
  61660. configurable: true
  61661. });
  61662. MultiMaterial.prototype._hookArray = function (array) {
  61663. var _this = this;
  61664. var oldPush = array.push;
  61665. array.push = function () {
  61666. var items = [];
  61667. for (var _i = 0; _i < arguments.length; _i++) {
  61668. items[_i] = arguments[_i];
  61669. }
  61670. var result = oldPush.apply(array, items);
  61671. _this._markAllSubMeshesAsTexturesDirty();
  61672. return result;
  61673. };
  61674. var oldSplice = array.splice;
  61675. array.splice = function (index, deleteCount) {
  61676. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61677. _this._markAllSubMeshesAsTexturesDirty();
  61678. return deleted;
  61679. };
  61680. };
  61681. // Properties
  61682. MultiMaterial.prototype.getSubMaterial = function (index) {
  61683. if (index < 0 || index >= this.subMaterials.length) {
  61684. return this.getScene().defaultMaterial;
  61685. }
  61686. return this.subMaterials[index];
  61687. };
  61688. MultiMaterial.prototype.getActiveTextures = function () {
  61689. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61690. if (subMaterial) {
  61691. return subMaterial.getActiveTextures();
  61692. }
  61693. else {
  61694. return [];
  61695. }
  61696. }));
  61697. var _a;
  61698. };
  61699. // Methods
  61700. MultiMaterial.prototype.getClassName = function () {
  61701. return "MultiMaterial";
  61702. };
  61703. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61704. for (var index = 0; index < this.subMaterials.length; index++) {
  61705. var subMaterial = this.subMaterials[index];
  61706. if (subMaterial) {
  61707. if (subMaterial.storeEffectOnSubMeshes) {
  61708. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61709. return false;
  61710. }
  61711. continue;
  61712. }
  61713. if (!subMaterial.isReady(mesh)) {
  61714. return false;
  61715. }
  61716. }
  61717. }
  61718. return true;
  61719. };
  61720. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61721. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61722. for (var index = 0; index < this.subMaterials.length; index++) {
  61723. var subMaterial = null;
  61724. var current = this.subMaterials[index];
  61725. if (cloneChildren && current) {
  61726. subMaterial = current.clone(name + "-" + current.name);
  61727. }
  61728. else {
  61729. subMaterial = this.subMaterials[index];
  61730. }
  61731. newMultiMaterial.subMaterials.push(subMaterial);
  61732. }
  61733. return newMultiMaterial;
  61734. };
  61735. MultiMaterial.prototype.serialize = function () {
  61736. var serializationObject = {};
  61737. serializationObject.name = this.name;
  61738. serializationObject.id = this.id;
  61739. if (BABYLON.Tags) {
  61740. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61741. }
  61742. serializationObject.materials = [];
  61743. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61744. var subMat = this.subMaterials[matIndex];
  61745. if (subMat) {
  61746. serializationObject.materials.push(subMat.id);
  61747. }
  61748. else {
  61749. serializationObject.materials.push(null);
  61750. }
  61751. }
  61752. return serializationObject;
  61753. };
  61754. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61755. var scene = this.getScene();
  61756. if (!scene) {
  61757. return;
  61758. }
  61759. var index = scene.multiMaterials.indexOf(this);
  61760. if (index >= 0) {
  61761. scene.multiMaterials.splice(index, 1);
  61762. }
  61763. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61764. };
  61765. return MultiMaterial;
  61766. }(BABYLON.Material));
  61767. BABYLON.MultiMaterial = MultiMaterial;
  61768. })(BABYLON || (BABYLON = {}));
  61769. //# sourceMappingURL=babylon.multiMaterial.js.map
  61770. var BABYLON;
  61771. (function (BABYLON) {
  61772. var FreeCameraTouchInput = /** @class */ (function () {
  61773. function FreeCameraTouchInput() {
  61774. this._offsetX = null;
  61775. this._offsetY = null;
  61776. this._pointerPressed = new Array();
  61777. this.touchAngularSensibility = 200000.0;
  61778. this.touchMoveSensibility = 250.0;
  61779. }
  61780. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61781. var _this = this;
  61782. var previousPosition = null;
  61783. if (this._pointerInput === undefined) {
  61784. this._onLostFocus = function (evt) {
  61785. _this._offsetX = null;
  61786. _this._offsetY = null;
  61787. };
  61788. this._pointerInput = function (p, s) {
  61789. var evt = p.event;
  61790. if (evt.pointerType === "mouse") {
  61791. return;
  61792. }
  61793. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61794. if (!noPreventDefault) {
  61795. evt.preventDefault();
  61796. }
  61797. _this._pointerPressed.push(evt.pointerId);
  61798. if (_this._pointerPressed.length !== 1) {
  61799. return;
  61800. }
  61801. previousPosition = {
  61802. x: evt.clientX,
  61803. y: evt.clientY
  61804. };
  61805. }
  61806. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61807. if (!noPreventDefault) {
  61808. evt.preventDefault();
  61809. }
  61810. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61811. if (index === -1) {
  61812. return;
  61813. }
  61814. _this._pointerPressed.splice(index, 1);
  61815. if (index != 0) {
  61816. return;
  61817. }
  61818. previousPosition = null;
  61819. _this._offsetX = null;
  61820. _this._offsetY = null;
  61821. }
  61822. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61823. if (!noPreventDefault) {
  61824. evt.preventDefault();
  61825. }
  61826. if (!previousPosition) {
  61827. return;
  61828. }
  61829. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61830. if (index != 0) {
  61831. return;
  61832. }
  61833. _this._offsetX = evt.clientX - previousPosition.x;
  61834. _this._offsetY = -(evt.clientY - previousPosition.y);
  61835. }
  61836. };
  61837. }
  61838. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61839. if (this._onLostFocus) {
  61840. element.addEventListener("blur", this._onLostFocus);
  61841. }
  61842. };
  61843. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61844. if (this._pointerInput && element) {
  61845. if (this._observer) {
  61846. this.camera.getScene().onPointerObservable.remove(this._observer);
  61847. this._observer = null;
  61848. }
  61849. if (this._onLostFocus) {
  61850. element.removeEventListener("blur", this._onLostFocus);
  61851. this._onLostFocus = null;
  61852. }
  61853. this._pointerPressed = [];
  61854. this._offsetX = null;
  61855. this._offsetY = null;
  61856. }
  61857. };
  61858. FreeCameraTouchInput.prototype.checkInputs = function () {
  61859. if (this._offsetX && this._offsetY) {
  61860. var camera = this.camera;
  61861. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61862. if (this._pointerPressed.length > 1) {
  61863. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61864. }
  61865. else {
  61866. var speed = camera._computeLocalCameraSpeed();
  61867. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61868. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61869. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61870. }
  61871. }
  61872. };
  61873. FreeCameraTouchInput.prototype.getClassName = function () {
  61874. return "FreeCameraTouchInput";
  61875. };
  61876. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61877. return "touch";
  61878. };
  61879. __decorate([
  61880. BABYLON.serialize()
  61881. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61882. __decorate([
  61883. BABYLON.serialize()
  61884. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61885. return FreeCameraTouchInput;
  61886. }());
  61887. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61888. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61889. })(BABYLON || (BABYLON = {}));
  61890. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61891. var BABYLON;
  61892. (function (BABYLON) {
  61893. // We're mainly based on the logic defined into the FreeCamera code
  61894. var TouchCamera = /** @class */ (function (_super) {
  61895. __extends(TouchCamera, _super);
  61896. //-- end properties for backward compatibility for inputs
  61897. function TouchCamera(name, position, scene) {
  61898. var _this = _super.call(this, name, position, scene) || this;
  61899. _this.inputs.addTouch();
  61900. _this._setupInputs();
  61901. return _this;
  61902. }
  61903. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61904. //-- Begin properties for backward compatibility for inputs
  61905. get: function () {
  61906. var touch = this.inputs.attached["touch"];
  61907. if (touch)
  61908. return touch.touchAngularSensibility;
  61909. return 0;
  61910. },
  61911. set: function (value) {
  61912. var touch = this.inputs.attached["touch"];
  61913. if (touch)
  61914. touch.touchAngularSensibility = value;
  61915. },
  61916. enumerable: true,
  61917. configurable: true
  61918. });
  61919. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61920. get: function () {
  61921. var touch = this.inputs.attached["touch"];
  61922. if (touch)
  61923. return touch.touchMoveSensibility;
  61924. return 0;
  61925. },
  61926. set: function (value) {
  61927. var touch = this.inputs.attached["touch"];
  61928. if (touch)
  61929. touch.touchMoveSensibility = value;
  61930. },
  61931. enumerable: true,
  61932. configurable: true
  61933. });
  61934. TouchCamera.prototype.getClassName = function () {
  61935. return "TouchCamera";
  61936. };
  61937. TouchCamera.prototype._setupInputs = function () {
  61938. var mouse = this.inputs.attached["mouse"];
  61939. if (mouse) {
  61940. mouse.touchEnabled = false;
  61941. }
  61942. };
  61943. return TouchCamera;
  61944. }(BABYLON.FreeCamera));
  61945. BABYLON.TouchCamera = TouchCamera;
  61946. })(BABYLON || (BABYLON = {}));
  61947. //# sourceMappingURL=babylon.touchCamera.js.map
  61948. var BABYLON;
  61949. (function (BABYLON) {
  61950. var ProceduralTexture = /** @class */ (function (_super) {
  61951. __extends(ProceduralTexture, _super);
  61952. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  61953. if (fallbackTexture === void 0) { fallbackTexture = null; }
  61954. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61955. if (isCube === void 0) { isCube = false; }
  61956. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61957. _this.isCube = isCube;
  61958. _this.isEnabled = true;
  61959. _this._currentRefreshId = -1;
  61960. _this._refreshRate = 1;
  61961. _this._vertexBuffers = {};
  61962. _this._uniforms = new Array();
  61963. _this._samplers = new Array();
  61964. _this._textures = {};
  61965. _this._floats = {};
  61966. _this._floatsArrays = {};
  61967. _this._colors3 = {};
  61968. _this._colors4 = {};
  61969. _this._vectors2 = {};
  61970. _this._vectors3 = {};
  61971. _this._matrices = {};
  61972. _this._fallbackTextureUsed = false;
  61973. scene._proceduralTextures.push(_this);
  61974. _this._engine = scene.getEngine();
  61975. _this.name = name;
  61976. _this.isRenderTarget = true;
  61977. _this._size = size;
  61978. _this._generateMipMaps = generateMipMaps;
  61979. _this.setFragment(fragment);
  61980. _this._fallbackTexture = fallbackTexture;
  61981. if (isCube) {
  61982. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  61983. _this.setFloat("face", 0);
  61984. }
  61985. else {
  61986. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  61987. }
  61988. // VBO
  61989. var vertices = [];
  61990. vertices.push(1, 1);
  61991. vertices.push(-1, 1);
  61992. vertices.push(-1, -1);
  61993. vertices.push(1, -1);
  61994. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61995. _this._createIndexBuffer();
  61996. return _this;
  61997. }
  61998. ProceduralTexture.prototype._createIndexBuffer = function () {
  61999. var engine = this._engine;
  62000. // Indices
  62001. var indices = [];
  62002. indices.push(0);
  62003. indices.push(1);
  62004. indices.push(2);
  62005. indices.push(0);
  62006. indices.push(2);
  62007. indices.push(3);
  62008. this._indexBuffer = engine.createIndexBuffer(indices);
  62009. };
  62010. ProceduralTexture.prototype._rebuild = function () {
  62011. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62012. if (vb) {
  62013. vb._rebuild();
  62014. }
  62015. this._createIndexBuffer();
  62016. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62017. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62018. }
  62019. };
  62020. ProceduralTexture.prototype.reset = function () {
  62021. if (this._effect === undefined) {
  62022. return;
  62023. }
  62024. var engine = this._engine;
  62025. engine._releaseEffect(this._effect);
  62026. };
  62027. ProceduralTexture.prototype.isReady = function () {
  62028. var _this = this;
  62029. var engine = this._engine;
  62030. var shaders;
  62031. if (!this._fragment) {
  62032. return false;
  62033. }
  62034. if (this._fallbackTextureUsed) {
  62035. return true;
  62036. }
  62037. if (this._fragment.fragmentElement !== undefined) {
  62038. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62039. }
  62040. else {
  62041. shaders = { vertex: "procedural", fragment: this._fragment };
  62042. }
  62043. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62044. _this.releaseInternalTexture();
  62045. if (_this._fallbackTexture) {
  62046. _this._texture = _this._fallbackTexture._texture;
  62047. if (_this._texture) {
  62048. _this._texture.incrementReferences();
  62049. }
  62050. }
  62051. _this._fallbackTextureUsed = true;
  62052. });
  62053. return this._effect.isReady();
  62054. };
  62055. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62056. this._currentRefreshId = -1;
  62057. };
  62058. ProceduralTexture.prototype.setFragment = function (fragment) {
  62059. this._fragment = fragment;
  62060. };
  62061. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  62062. get: function () {
  62063. return this._refreshRate;
  62064. },
  62065. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62066. set: function (value) {
  62067. this._refreshRate = value;
  62068. this.resetRefreshCounter();
  62069. },
  62070. enumerable: true,
  62071. configurable: true
  62072. });
  62073. ProceduralTexture.prototype._shouldRender = function () {
  62074. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62075. return false;
  62076. }
  62077. if (this._fallbackTextureUsed) {
  62078. return false;
  62079. }
  62080. if (this._currentRefreshId === -1) {
  62081. this._currentRefreshId = 1;
  62082. return true;
  62083. }
  62084. if (this.refreshRate === this._currentRefreshId) {
  62085. this._currentRefreshId = 1;
  62086. return true;
  62087. }
  62088. this._currentRefreshId++;
  62089. return false;
  62090. };
  62091. ProceduralTexture.prototype.getRenderSize = function () {
  62092. return this._size;
  62093. };
  62094. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62095. if (this._fallbackTextureUsed) {
  62096. return;
  62097. }
  62098. this.releaseInternalTexture();
  62099. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62100. };
  62101. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62102. if (this._uniforms.indexOf(uniformName) === -1) {
  62103. this._uniforms.push(uniformName);
  62104. }
  62105. };
  62106. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62107. if (this._samplers.indexOf(name) === -1) {
  62108. this._samplers.push(name);
  62109. }
  62110. this._textures[name] = texture;
  62111. return this;
  62112. };
  62113. ProceduralTexture.prototype.setFloat = function (name, value) {
  62114. this._checkUniform(name);
  62115. this._floats[name] = value;
  62116. return this;
  62117. };
  62118. ProceduralTexture.prototype.setFloats = function (name, value) {
  62119. this._checkUniform(name);
  62120. this._floatsArrays[name] = value;
  62121. return this;
  62122. };
  62123. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62124. this._checkUniform(name);
  62125. this._colors3[name] = value;
  62126. return this;
  62127. };
  62128. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62129. this._checkUniform(name);
  62130. this._colors4[name] = value;
  62131. return this;
  62132. };
  62133. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62134. this._checkUniform(name);
  62135. this._vectors2[name] = value;
  62136. return this;
  62137. };
  62138. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62139. this._checkUniform(name);
  62140. this._vectors3[name] = value;
  62141. return this;
  62142. };
  62143. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62144. this._checkUniform(name);
  62145. this._matrices[name] = value;
  62146. return this;
  62147. };
  62148. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62149. var scene = this.getScene();
  62150. if (!scene) {
  62151. return;
  62152. }
  62153. var engine = this._engine;
  62154. // Render
  62155. engine.enableEffect(this._effect);
  62156. engine.setState(false);
  62157. // Texture
  62158. for (var name in this._textures) {
  62159. this._effect.setTexture(name, this._textures[name]);
  62160. }
  62161. // Float
  62162. for (name in this._floats) {
  62163. this._effect.setFloat(name, this._floats[name]);
  62164. }
  62165. // Floats
  62166. for (name in this._floatsArrays) {
  62167. this._effect.setArray(name, this._floatsArrays[name]);
  62168. }
  62169. // Color3
  62170. for (name in this._colors3) {
  62171. this._effect.setColor3(name, this._colors3[name]);
  62172. }
  62173. // Color4
  62174. for (name in this._colors4) {
  62175. var color = this._colors4[name];
  62176. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62177. }
  62178. // Vector2
  62179. for (name in this._vectors2) {
  62180. this._effect.setVector2(name, this._vectors2[name]);
  62181. }
  62182. // Vector3
  62183. for (name in this._vectors3) {
  62184. this._effect.setVector3(name, this._vectors3[name]);
  62185. }
  62186. // Matrix
  62187. for (name in this._matrices) {
  62188. this._effect.setMatrix(name, this._matrices[name]);
  62189. }
  62190. if (!this._texture) {
  62191. return;
  62192. }
  62193. if (this.isCube) {
  62194. for (var face = 0; face < 6; face++) {
  62195. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62196. // VBOs
  62197. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62198. this._effect.setFloat("face", face);
  62199. // Clear
  62200. engine.clear(scene.clearColor, true, true, true);
  62201. // Draw order
  62202. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62203. // Mipmaps
  62204. if (face === 5) {
  62205. engine.generateMipMapsForCubemap(this._texture);
  62206. }
  62207. }
  62208. }
  62209. else {
  62210. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62211. // VBOs
  62212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62213. // Clear
  62214. engine.clear(scene.clearColor, true, true, true);
  62215. // Draw order
  62216. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62217. }
  62218. // Unbind
  62219. engine.unBindFramebuffer(this._texture, this.isCube);
  62220. if (this.onGenerated) {
  62221. this.onGenerated();
  62222. }
  62223. };
  62224. ProceduralTexture.prototype.clone = function () {
  62225. var textureSize = this.getSize();
  62226. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62227. // Base texture
  62228. newTexture.hasAlpha = this.hasAlpha;
  62229. newTexture.level = this.level;
  62230. // RenderTarget Texture
  62231. newTexture.coordinatesMode = this.coordinatesMode;
  62232. return newTexture;
  62233. };
  62234. ProceduralTexture.prototype.dispose = function () {
  62235. var scene = this.getScene();
  62236. if (!scene) {
  62237. return;
  62238. }
  62239. var index = scene._proceduralTextures.indexOf(this);
  62240. if (index >= 0) {
  62241. scene._proceduralTextures.splice(index, 1);
  62242. }
  62243. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62244. if (vertexBuffer) {
  62245. vertexBuffer.dispose();
  62246. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62247. }
  62248. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62249. this._indexBuffer = null;
  62250. }
  62251. _super.prototype.dispose.call(this);
  62252. };
  62253. return ProceduralTexture;
  62254. }(BABYLON.Texture));
  62255. BABYLON.ProceduralTexture = ProceduralTexture;
  62256. })(BABYLON || (BABYLON = {}));
  62257. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62258. var BABYLON;
  62259. (function (BABYLON) {
  62260. var CustomProceduralTexture = /** @class */ (function (_super) {
  62261. __extends(CustomProceduralTexture, _super);
  62262. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62263. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62264. _this._animate = true;
  62265. _this._time = 0;
  62266. _this._texturePath = texturePath;
  62267. //Try to load json
  62268. _this.loadJson(texturePath);
  62269. _this.refreshRate = 1;
  62270. return _this;
  62271. }
  62272. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62273. var _this = this;
  62274. var noConfigFile = function () {
  62275. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62276. try {
  62277. _this.setFragment(_this._texturePath);
  62278. }
  62279. catch (ex) {
  62280. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62281. }
  62282. };
  62283. var configFileUrl = jsonUrl + "/config.json";
  62284. var xhr = new XMLHttpRequest();
  62285. xhr.open("GET", configFileUrl, true);
  62286. xhr.addEventListener("load", function () {
  62287. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62288. try {
  62289. _this._config = JSON.parse(xhr.response);
  62290. _this.updateShaderUniforms();
  62291. _this.updateTextures();
  62292. _this.setFragment(_this._texturePath + "/custom");
  62293. _this._animate = _this._config.animate;
  62294. _this.refreshRate = _this._config.refreshrate;
  62295. }
  62296. catch (ex) {
  62297. noConfigFile();
  62298. }
  62299. }
  62300. else {
  62301. noConfigFile();
  62302. }
  62303. }, false);
  62304. xhr.addEventListener("error", function () {
  62305. noConfigFile();
  62306. }, false);
  62307. try {
  62308. xhr.send();
  62309. }
  62310. catch (ex) {
  62311. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62312. }
  62313. };
  62314. CustomProceduralTexture.prototype.isReady = function () {
  62315. if (!_super.prototype.isReady.call(this)) {
  62316. return false;
  62317. }
  62318. for (var name in this._textures) {
  62319. var texture = this._textures[name];
  62320. if (!texture.isReady()) {
  62321. return false;
  62322. }
  62323. }
  62324. return true;
  62325. };
  62326. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62327. var scene = this.getScene();
  62328. if (this._animate && scene) {
  62329. this._time += scene.getAnimationRatio() * 0.03;
  62330. this.updateShaderUniforms();
  62331. }
  62332. _super.prototype.render.call(this, useCameraPostProcess);
  62333. };
  62334. CustomProceduralTexture.prototype.updateTextures = function () {
  62335. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62336. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62337. }
  62338. };
  62339. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62340. if (this._config) {
  62341. for (var j = 0; j < this._config.uniforms.length; j++) {
  62342. var uniform = this._config.uniforms[j];
  62343. switch (uniform.type) {
  62344. case "float":
  62345. this.setFloat(uniform.name, uniform.value);
  62346. break;
  62347. case "color3":
  62348. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62349. break;
  62350. case "color4":
  62351. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62352. break;
  62353. case "vector2":
  62354. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62355. break;
  62356. case "vector3":
  62357. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62358. break;
  62359. }
  62360. }
  62361. }
  62362. this.setFloat("time", this._time);
  62363. };
  62364. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62365. get: function () {
  62366. return this._animate;
  62367. },
  62368. set: function (value) {
  62369. this._animate = value;
  62370. },
  62371. enumerable: true,
  62372. configurable: true
  62373. });
  62374. return CustomProceduralTexture;
  62375. }(BABYLON.ProceduralTexture));
  62376. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62377. })(BABYLON || (BABYLON = {}));
  62378. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62379. var BABYLON;
  62380. (function (BABYLON) {
  62381. var FreeCameraGamepadInput = /** @class */ (function () {
  62382. function FreeCameraGamepadInput() {
  62383. this.gamepadAngularSensibility = 200;
  62384. this.gamepadMoveSensibility = 40;
  62385. // private members
  62386. this._cameraTransform = BABYLON.Matrix.Identity();
  62387. this._deltaTransform = BABYLON.Vector3.Zero();
  62388. this._vector3 = BABYLON.Vector3.Zero();
  62389. this._vector2 = BABYLON.Vector2.Zero();
  62390. }
  62391. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62392. var _this = this;
  62393. var manager = this.camera.getScene().gamepadManager;
  62394. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62395. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62396. // prioritize XBOX gamepads.
  62397. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62398. _this.gamepad = gamepad;
  62399. }
  62400. }
  62401. });
  62402. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62403. if (_this.gamepad === gamepad) {
  62404. _this.gamepad = null;
  62405. }
  62406. });
  62407. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62408. };
  62409. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62410. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62411. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62412. this.gamepad = null;
  62413. };
  62414. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62415. if (this.gamepad && this.gamepad.leftStick) {
  62416. var camera = this.camera;
  62417. var LSValues = this.gamepad.leftStick;
  62418. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62419. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62420. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62421. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62422. var RSValues = this.gamepad.rightStick;
  62423. if (RSValues) {
  62424. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62425. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62426. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62427. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62428. }
  62429. else {
  62430. RSValues = { x: 0, y: 0 };
  62431. }
  62432. if (!camera.rotationQuaternion) {
  62433. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62434. }
  62435. else {
  62436. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62437. }
  62438. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62439. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62440. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62441. camera.cameraDirection.addInPlace(this._deltaTransform);
  62442. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62443. camera.cameraRotation.addInPlace(this._vector2);
  62444. }
  62445. };
  62446. FreeCameraGamepadInput.prototype.getClassName = function () {
  62447. return "FreeCameraGamepadInput";
  62448. };
  62449. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62450. return "gamepad";
  62451. };
  62452. __decorate([
  62453. BABYLON.serialize()
  62454. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62455. __decorate([
  62456. BABYLON.serialize()
  62457. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62458. return FreeCameraGamepadInput;
  62459. }());
  62460. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62461. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62462. })(BABYLON || (BABYLON = {}));
  62463. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62464. var BABYLON;
  62465. (function (BABYLON) {
  62466. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62467. function ArcRotateCameraGamepadInput() {
  62468. this.gamepadRotationSensibility = 80;
  62469. this.gamepadMoveSensibility = 40;
  62470. }
  62471. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62472. var _this = this;
  62473. var manager = this.camera.getScene().gamepadManager;
  62474. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62475. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62476. // prioritize XBOX gamepads.
  62477. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62478. _this.gamepad = gamepad;
  62479. }
  62480. }
  62481. });
  62482. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62483. if (_this.gamepad === gamepad) {
  62484. _this.gamepad = null;
  62485. }
  62486. });
  62487. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62488. };
  62489. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62490. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62491. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62492. this.gamepad = null;
  62493. };
  62494. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62495. if (this.gamepad) {
  62496. var camera = this.camera;
  62497. var RSValues = this.gamepad.rightStick;
  62498. if (RSValues) {
  62499. if (RSValues.x != 0) {
  62500. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62501. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62502. camera.inertialAlphaOffset += normalizedRX;
  62503. }
  62504. }
  62505. if (RSValues.y != 0) {
  62506. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62507. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62508. camera.inertialBetaOffset += normalizedRY;
  62509. }
  62510. }
  62511. }
  62512. var LSValues = this.gamepad.leftStick;
  62513. if (LSValues && LSValues.y != 0) {
  62514. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62515. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62516. this.camera.inertialRadiusOffset -= normalizedLY;
  62517. }
  62518. }
  62519. }
  62520. };
  62521. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62522. return "ArcRotateCameraGamepadInput";
  62523. };
  62524. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62525. return "gamepad";
  62526. };
  62527. __decorate([
  62528. BABYLON.serialize()
  62529. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62530. __decorate([
  62531. BABYLON.serialize()
  62532. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62533. return ArcRotateCameraGamepadInput;
  62534. }());
  62535. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62536. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62537. })(BABYLON || (BABYLON = {}));
  62538. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62539. var BABYLON;
  62540. (function (BABYLON) {
  62541. var GamepadManager = /** @class */ (function () {
  62542. function GamepadManager(_scene) {
  62543. var _this = this;
  62544. this._scene = _scene;
  62545. this._babylonGamepads = [];
  62546. this._oneGamepadConnected = false;
  62547. this._isMonitoring = false;
  62548. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62549. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62550. this._gamepadEventSupported = false;
  62551. }
  62552. else {
  62553. this._gamepadEventSupported = 'GamepadEvent' in window;
  62554. this._gamepadSupport = (navigator.getGamepads ||
  62555. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62556. }
  62557. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62558. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62559. for (var i in _this._babylonGamepads) {
  62560. var gamepad = _this._babylonGamepads[i];
  62561. if (gamepad && gamepad._isConnected) {
  62562. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62563. }
  62564. }
  62565. });
  62566. this._onGamepadConnectedEvent = function (evt) {
  62567. var gamepad = evt.gamepad;
  62568. if (gamepad.index in _this._babylonGamepads) {
  62569. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62570. return;
  62571. }
  62572. }
  62573. var newGamepad;
  62574. if (_this._babylonGamepads[gamepad.index]) {
  62575. newGamepad = _this._babylonGamepads[gamepad.index];
  62576. newGamepad.browserGamepad = gamepad;
  62577. newGamepad._isConnected = true;
  62578. }
  62579. else {
  62580. newGamepad = _this._addNewGamepad(gamepad);
  62581. }
  62582. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62583. _this._startMonitoringGamepads();
  62584. };
  62585. this._onGamepadDisconnectedEvent = function (evt) {
  62586. var gamepad = evt.gamepad;
  62587. // Remove the gamepad from the list of gamepads to monitor.
  62588. for (var i in _this._babylonGamepads) {
  62589. if (_this._babylonGamepads[i].index === gamepad.index) {
  62590. var disconnectedGamepad = _this._babylonGamepads[i];
  62591. disconnectedGamepad._isConnected = false;
  62592. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62593. break;
  62594. }
  62595. }
  62596. };
  62597. if (this._gamepadSupport) {
  62598. //first add already-connected gamepads
  62599. this._updateGamepadObjects();
  62600. if (this._babylonGamepads.length) {
  62601. this._startMonitoringGamepads();
  62602. }
  62603. // Checking if the gamepad connected event is supported (like in Firefox)
  62604. if (this._gamepadEventSupported) {
  62605. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62606. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62607. }
  62608. else {
  62609. this._startMonitoringGamepads();
  62610. }
  62611. }
  62612. }
  62613. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62614. get: function () {
  62615. return this._babylonGamepads;
  62616. },
  62617. enumerable: true,
  62618. configurable: true
  62619. });
  62620. GamepadManager.prototype.getGamepadByType = function (type) {
  62621. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62622. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62623. var gamepad = _a[_i];
  62624. if (gamepad && gamepad.type === type) {
  62625. return gamepad;
  62626. }
  62627. }
  62628. return null;
  62629. };
  62630. GamepadManager.prototype.dispose = function () {
  62631. if (this._gamepadEventSupported) {
  62632. if (this._onGamepadConnectedEvent) {
  62633. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62634. }
  62635. if (this._onGamepadDisconnectedEvent) {
  62636. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62637. }
  62638. this._onGamepadConnectedEvent = null;
  62639. this._onGamepadDisconnectedEvent = null;
  62640. }
  62641. this._babylonGamepads.forEach(function (gamepad) {
  62642. gamepad.dispose();
  62643. });
  62644. this.onGamepadConnectedObservable.clear();
  62645. this.onGamepadDisconnectedObservable.clear();
  62646. this._oneGamepadConnected = false;
  62647. this._stopMonitoringGamepads();
  62648. this._babylonGamepads = [];
  62649. };
  62650. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62651. if (!this._oneGamepadConnected) {
  62652. this._oneGamepadConnected = true;
  62653. }
  62654. var newGamepad;
  62655. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62656. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62657. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62658. }
  62659. else if (gamepad.pose) {
  62660. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62661. }
  62662. else {
  62663. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62664. }
  62665. this._babylonGamepads[newGamepad.index] = newGamepad;
  62666. return newGamepad;
  62667. };
  62668. GamepadManager.prototype._startMonitoringGamepads = function () {
  62669. if (!this._isMonitoring) {
  62670. this._isMonitoring = true;
  62671. //back-comp
  62672. if (!this._scene) {
  62673. this._checkGamepadsStatus();
  62674. }
  62675. }
  62676. };
  62677. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62678. this._isMonitoring = false;
  62679. };
  62680. GamepadManager.prototype._checkGamepadsStatus = function () {
  62681. var _this = this;
  62682. // Hack to be compatible Chrome
  62683. this._updateGamepadObjects();
  62684. for (var i in this._babylonGamepads) {
  62685. var gamepad = this._babylonGamepads[i];
  62686. if (!gamepad || !gamepad.isConnected) {
  62687. continue;
  62688. }
  62689. gamepad.update();
  62690. }
  62691. if (this._isMonitoring && !this._scene) {
  62692. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62693. }
  62694. };
  62695. // This function is called only on Chrome, which does not properly support
  62696. // connection/disconnection events and forces you to recopy again the gamepad object
  62697. GamepadManager.prototype._updateGamepadObjects = function () {
  62698. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62699. for (var i = 0; i < gamepads.length; i++) {
  62700. if (gamepads[i]) {
  62701. if (!this._babylonGamepads[gamepads[i].index]) {
  62702. var newGamepad = this._addNewGamepad(gamepads[i]);
  62703. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62704. }
  62705. else {
  62706. // Forced to copy again this object for Chrome for unknown reason
  62707. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62708. if (!this._babylonGamepads[i].isConnected) {
  62709. this._babylonGamepads[i]._isConnected = true;
  62710. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62711. }
  62712. }
  62713. }
  62714. }
  62715. };
  62716. return GamepadManager;
  62717. }());
  62718. BABYLON.GamepadManager = GamepadManager;
  62719. })(BABYLON || (BABYLON = {}));
  62720. //# sourceMappingURL=babylon.gamepadManager.js.map
  62721. var BABYLON;
  62722. (function (BABYLON) {
  62723. var StickValues = /** @class */ (function () {
  62724. function StickValues(x, y) {
  62725. this.x = x;
  62726. this.y = y;
  62727. }
  62728. return StickValues;
  62729. }());
  62730. BABYLON.StickValues = StickValues;
  62731. var Gamepad = /** @class */ (function () {
  62732. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62733. if (leftStickX === void 0) { leftStickX = 0; }
  62734. if (leftStickY === void 0) { leftStickY = 1; }
  62735. if (rightStickX === void 0) { rightStickX = 2; }
  62736. if (rightStickY === void 0) { rightStickY = 3; }
  62737. this.id = id;
  62738. this.index = index;
  62739. this.browserGamepad = browserGamepad;
  62740. this._isConnected = true;
  62741. this._invertLeftStickY = false;
  62742. this.type = Gamepad.GAMEPAD;
  62743. this._leftStickAxisX = leftStickX;
  62744. this._leftStickAxisY = leftStickY;
  62745. this._rightStickAxisX = rightStickX;
  62746. this._rightStickAxisY = rightStickY;
  62747. if (this.browserGamepad.axes.length >= 2) {
  62748. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62749. }
  62750. if (this.browserGamepad.axes.length >= 4) {
  62751. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62752. }
  62753. }
  62754. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62755. get: function () {
  62756. return this._isConnected;
  62757. },
  62758. enumerable: true,
  62759. configurable: true
  62760. });
  62761. Gamepad.prototype.onleftstickchanged = function (callback) {
  62762. this._onleftstickchanged = callback;
  62763. };
  62764. Gamepad.prototype.onrightstickchanged = function (callback) {
  62765. this._onrightstickchanged = callback;
  62766. };
  62767. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62768. get: function () {
  62769. return this._leftStick;
  62770. },
  62771. set: function (newValues) {
  62772. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62773. this._onleftstickchanged(newValues);
  62774. }
  62775. this._leftStick = newValues;
  62776. },
  62777. enumerable: true,
  62778. configurable: true
  62779. });
  62780. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62781. get: function () {
  62782. return this._rightStick;
  62783. },
  62784. set: function (newValues) {
  62785. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62786. this._onrightstickchanged(newValues);
  62787. }
  62788. this._rightStick = newValues;
  62789. },
  62790. enumerable: true,
  62791. configurable: true
  62792. });
  62793. Gamepad.prototype.update = function () {
  62794. if (this._leftStick) {
  62795. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62796. if (this._invertLeftStickY) {
  62797. this.leftStick.y *= -1;
  62798. }
  62799. }
  62800. if (this._rightStick) {
  62801. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62802. }
  62803. };
  62804. Gamepad.prototype.dispose = function () {
  62805. };
  62806. Gamepad.GAMEPAD = 0;
  62807. Gamepad.GENERIC = 1;
  62808. Gamepad.XBOX = 2;
  62809. Gamepad.POSE_ENABLED = 3;
  62810. return Gamepad;
  62811. }());
  62812. BABYLON.Gamepad = Gamepad;
  62813. var GenericPad = /** @class */ (function (_super) {
  62814. __extends(GenericPad, _super);
  62815. function GenericPad(id, index, browserGamepad) {
  62816. var _this = _super.call(this, id, index, browserGamepad) || this;
  62817. _this.onButtonDownObservable = new BABYLON.Observable();
  62818. _this.onButtonUpObservable = new BABYLON.Observable();
  62819. _this.type = Gamepad.GENERIC;
  62820. _this._buttons = new Array(browserGamepad.buttons.length);
  62821. return _this;
  62822. }
  62823. GenericPad.prototype.onbuttondown = function (callback) {
  62824. this._onbuttondown = callback;
  62825. };
  62826. GenericPad.prototype.onbuttonup = function (callback) {
  62827. this._onbuttonup = callback;
  62828. };
  62829. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62830. if (newValue !== currentValue) {
  62831. if (newValue === 1) {
  62832. if (this._onbuttondown) {
  62833. this._onbuttondown(buttonIndex);
  62834. }
  62835. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62836. }
  62837. if (newValue === 0) {
  62838. if (this._onbuttonup) {
  62839. this._onbuttonup(buttonIndex);
  62840. }
  62841. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62842. }
  62843. }
  62844. return newValue;
  62845. };
  62846. GenericPad.prototype.update = function () {
  62847. _super.prototype.update.call(this);
  62848. for (var index = 0; index < this._buttons.length; index++) {
  62849. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62850. }
  62851. };
  62852. GenericPad.prototype.dispose = function () {
  62853. _super.prototype.dispose.call(this);
  62854. this.onButtonDownObservable.clear();
  62855. this.onButtonUpObservable.clear();
  62856. };
  62857. return GenericPad;
  62858. }(Gamepad));
  62859. BABYLON.GenericPad = GenericPad;
  62860. })(BABYLON || (BABYLON = {}));
  62861. //# sourceMappingURL=babylon.gamepad.js.map
  62862. var BABYLON;
  62863. (function (BABYLON) {
  62864. var Xbox360Button;
  62865. (function (Xbox360Button) {
  62866. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62867. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62868. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62869. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62870. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62871. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62872. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62873. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62874. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62875. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62876. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62877. var Xbox360Dpad;
  62878. (function (Xbox360Dpad) {
  62879. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62880. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62881. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62882. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62883. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62884. var Xbox360Pad = /** @class */ (function (_super) {
  62885. __extends(Xbox360Pad, _super);
  62886. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62887. if (xboxOne === void 0) { xboxOne = false; }
  62888. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62889. _this._leftTrigger = 0;
  62890. _this._rightTrigger = 0;
  62891. _this.onButtonDownObservable = new BABYLON.Observable();
  62892. _this.onButtonUpObservable = new BABYLON.Observable();
  62893. _this.onPadDownObservable = new BABYLON.Observable();
  62894. _this.onPadUpObservable = new BABYLON.Observable();
  62895. _this._buttonA = 0;
  62896. _this._buttonB = 0;
  62897. _this._buttonX = 0;
  62898. _this._buttonY = 0;
  62899. _this._buttonBack = 0;
  62900. _this._buttonStart = 0;
  62901. _this._buttonLB = 0;
  62902. _this._buttonRB = 0;
  62903. _this._buttonLeftStick = 0;
  62904. _this._buttonRightStick = 0;
  62905. _this._dPadUp = 0;
  62906. _this._dPadDown = 0;
  62907. _this._dPadLeft = 0;
  62908. _this._dPadRight = 0;
  62909. _this._isXboxOnePad = false;
  62910. _this.type = BABYLON.Gamepad.XBOX;
  62911. _this._isXboxOnePad = xboxOne;
  62912. return _this;
  62913. }
  62914. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62915. this._onlefttriggerchanged = callback;
  62916. };
  62917. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62918. this._onrighttriggerchanged = callback;
  62919. };
  62920. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62921. get: function () {
  62922. return this._leftTrigger;
  62923. },
  62924. set: function (newValue) {
  62925. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62926. this._onlefttriggerchanged(newValue);
  62927. }
  62928. this._leftTrigger = newValue;
  62929. },
  62930. enumerable: true,
  62931. configurable: true
  62932. });
  62933. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62934. get: function () {
  62935. return this._rightTrigger;
  62936. },
  62937. set: function (newValue) {
  62938. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  62939. this._onrighttriggerchanged(newValue);
  62940. }
  62941. this._rightTrigger = newValue;
  62942. },
  62943. enumerable: true,
  62944. configurable: true
  62945. });
  62946. Xbox360Pad.prototype.onbuttondown = function (callback) {
  62947. this._onbuttondown = callback;
  62948. };
  62949. Xbox360Pad.prototype.onbuttonup = function (callback) {
  62950. this._onbuttonup = callback;
  62951. };
  62952. Xbox360Pad.prototype.ondpaddown = function (callback) {
  62953. this._ondpaddown = callback;
  62954. };
  62955. Xbox360Pad.prototype.ondpadup = function (callback) {
  62956. this._ondpadup = callback;
  62957. };
  62958. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  62959. if (newValue !== currentValue) {
  62960. if (newValue === 1) {
  62961. if (this._onbuttondown) {
  62962. this._onbuttondown(buttonType);
  62963. }
  62964. this.onButtonDownObservable.notifyObservers(buttonType);
  62965. }
  62966. if (newValue === 0) {
  62967. if (this._onbuttonup) {
  62968. this._onbuttonup(buttonType);
  62969. }
  62970. this.onButtonUpObservable.notifyObservers(buttonType);
  62971. }
  62972. }
  62973. return newValue;
  62974. };
  62975. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  62976. if (newValue !== currentValue) {
  62977. if (newValue === 1) {
  62978. if (this._ondpaddown) {
  62979. this._ondpaddown(buttonType);
  62980. }
  62981. this.onPadDownObservable.notifyObservers(buttonType);
  62982. }
  62983. if (newValue === 0) {
  62984. if (this._ondpadup) {
  62985. this._ondpadup(buttonType);
  62986. }
  62987. this.onPadUpObservable.notifyObservers(buttonType);
  62988. }
  62989. }
  62990. return newValue;
  62991. };
  62992. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  62993. get: function () {
  62994. return this._buttonA;
  62995. },
  62996. set: function (value) {
  62997. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  62998. },
  62999. enumerable: true,
  63000. configurable: true
  63001. });
  63002. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63003. get: function () {
  63004. return this._buttonB;
  63005. },
  63006. set: function (value) {
  63007. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63008. },
  63009. enumerable: true,
  63010. configurable: true
  63011. });
  63012. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63013. get: function () {
  63014. return this._buttonX;
  63015. },
  63016. set: function (value) {
  63017. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63018. },
  63019. enumerable: true,
  63020. configurable: true
  63021. });
  63022. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63023. get: function () {
  63024. return this._buttonY;
  63025. },
  63026. set: function (value) {
  63027. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63028. },
  63029. enumerable: true,
  63030. configurable: true
  63031. });
  63032. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63033. get: function () {
  63034. return this._buttonStart;
  63035. },
  63036. set: function (value) {
  63037. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63038. },
  63039. enumerable: true,
  63040. configurable: true
  63041. });
  63042. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63043. get: function () {
  63044. return this._buttonBack;
  63045. },
  63046. set: function (value) {
  63047. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63048. },
  63049. enumerable: true,
  63050. configurable: true
  63051. });
  63052. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63053. get: function () {
  63054. return this._buttonLB;
  63055. },
  63056. set: function (value) {
  63057. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63058. },
  63059. enumerable: true,
  63060. configurable: true
  63061. });
  63062. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  63063. get: function () {
  63064. return this._buttonRB;
  63065. },
  63066. set: function (value) {
  63067. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63068. },
  63069. enumerable: true,
  63070. configurable: true
  63071. });
  63072. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63073. get: function () {
  63074. return this._buttonLeftStick;
  63075. },
  63076. set: function (value) {
  63077. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63078. },
  63079. enumerable: true,
  63080. configurable: true
  63081. });
  63082. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63083. get: function () {
  63084. return this._buttonRightStick;
  63085. },
  63086. set: function (value) {
  63087. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63088. },
  63089. enumerable: true,
  63090. configurable: true
  63091. });
  63092. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63093. get: function () {
  63094. return this._dPadUp;
  63095. },
  63096. set: function (value) {
  63097. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63098. },
  63099. enumerable: true,
  63100. configurable: true
  63101. });
  63102. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63103. get: function () {
  63104. return this._dPadDown;
  63105. },
  63106. set: function (value) {
  63107. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63108. },
  63109. enumerable: true,
  63110. configurable: true
  63111. });
  63112. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63113. get: function () {
  63114. return this._dPadLeft;
  63115. },
  63116. set: function (value) {
  63117. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63118. },
  63119. enumerable: true,
  63120. configurable: true
  63121. });
  63122. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63123. get: function () {
  63124. return this._dPadRight;
  63125. },
  63126. set: function (value) {
  63127. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63128. },
  63129. enumerable: true,
  63130. configurable: true
  63131. });
  63132. Xbox360Pad.prototype.update = function () {
  63133. _super.prototype.update.call(this);
  63134. if (this._isXboxOnePad) {
  63135. this.buttonA = this.browserGamepad.buttons[0].value;
  63136. this.buttonB = this.browserGamepad.buttons[1].value;
  63137. this.buttonX = this.browserGamepad.buttons[2].value;
  63138. this.buttonY = this.browserGamepad.buttons[3].value;
  63139. this.buttonLB = this.browserGamepad.buttons[4].value;
  63140. this.buttonRB = this.browserGamepad.buttons[5].value;
  63141. this.leftTrigger = this.browserGamepad.axes[2];
  63142. this.rightTrigger = this.browserGamepad.axes[5];
  63143. this.buttonBack = this.browserGamepad.buttons[9].value;
  63144. this.buttonStart = this.browserGamepad.buttons[8].value;
  63145. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63146. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63147. this.dPadUp = this.browserGamepad.buttons[11].value;
  63148. this.dPadDown = this.browserGamepad.buttons[12].value;
  63149. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63150. this.dPadRight = this.browserGamepad.buttons[14].value;
  63151. }
  63152. else {
  63153. this.buttonA = this.browserGamepad.buttons[0].value;
  63154. this.buttonB = this.browserGamepad.buttons[1].value;
  63155. this.buttonX = this.browserGamepad.buttons[2].value;
  63156. this.buttonY = this.browserGamepad.buttons[3].value;
  63157. this.buttonLB = this.browserGamepad.buttons[4].value;
  63158. this.buttonRB = this.browserGamepad.buttons[5].value;
  63159. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63160. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63161. this.buttonBack = this.browserGamepad.buttons[8].value;
  63162. this.buttonStart = this.browserGamepad.buttons[9].value;
  63163. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63164. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63165. this.dPadUp = this.browserGamepad.buttons[12].value;
  63166. this.dPadDown = this.browserGamepad.buttons[13].value;
  63167. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63168. this.dPadRight = this.browserGamepad.buttons[15].value;
  63169. }
  63170. };
  63171. Xbox360Pad.prototype.dispose = function () {
  63172. _super.prototype.dispose.call(this);
  63173. this.onButtonDownObservable.clear();
  63174. this.onButtonUpObservable.clear();
  63175. this.onPadDownObservable.clear();
  63176. this.onPadUpObservable.clear();
  63177. };
  63178. return Xbox360Pad;
  63179. }(BABYLON.Gamepad));
  63180. BABYLON.Xbox360Pad = Xbox360Pad;
  63181. })(BABYLON || (BABYLON = {}));
  63182. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63183. var BABYLON;
  63184. (function (BABYLON) {
  63185. var PoseEnabledControllerType;
  63186. (function (PoseEnabledControllerType) {
  63187. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63188. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63189. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63190. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63191. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63192. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63193. var PoseEnabledControllerHelper = /** @class */ (function () {
  63194. function PoseEnabledControllerHelper() {
  63195. }
  63196. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63197. // Oculus Touch
  63198. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63199. return new BABYLON.OculusTouchController(vrGamepad);
  63200. }
  63201. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63202. return new BABYLON.WindowsMotionController(vrGamepad);
  63203. }
  63204. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63205. return new BABYLON.ViveController(vrGamepad);
  63206. }
  63207. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63208. return new BABYLON.GearVRController(vrGamepad);
  63209. }
  63210. else {
  63211. return new BABYLON.GenericController(vrGamepad);
  63212. }
  63213. };
  63214. return PoseEnabledControllerHelper;
  63215. }());
  63216. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63217. var PoseEnabledController = /** @class */ (function (_super) {
  63218. __extends(PoseEnabledController, _super);
  63219. function PoseEnabledController(browserGamepad) {
  63220. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63221. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63222. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63223. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63224. // Represents device position and rotation in babylon space
  63225. _this.devicePosition = BABYLON.Vector3.Zero();
  63226. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63227. _this.deviceScaleFactor = 1;
  63228. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63229. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63230. _this._workingMatrix = BABYLON.Matrix.Identity();
  63231. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63232. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63233. _this.position = BABYLON.Vector3.Zero();
  63234. _this.rotationQuaternion = new BABYLON.Quaternion();
  63235. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63236. _this._calculatedRotation = new BABYLON.Quaternion();
  63237. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63238. return _this;
  63239. }
  63240. PoseEnabledController.prototype.update = function () {
  63241. _super.prototype.update.call(this);
  63242. var pose = this.browserGamepad.pose;
  63243. this.updateFromDevice(pose);
  63244. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63245. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63246. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63247. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63248. if (this._mesh) {
  63249. this._mesh.position.copyFrom(this.devicePosition);
  63250. if (this._mesh.rotationQuaternion) {
  63251. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63252. }
  63253. }
  63254. };
  63255. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63256. if (poseData) {
  63257. this.rawPose = poseData;
  63258. if (poseData.position) {
  63259. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63260. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63261. this._deviceRoomPosition.z *= -1;
  63262. }
  63263. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63264. this._calculatedPosition.addInPlace(this.position);
  63265. }
  63266. var pose = this.rawPose;
  63267. if (poseData.orientation && pose.orientation) {
  63268. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63269. if (this._mesh) {
  63270. if (this._mesh.getScene().useRightHandedSystem) {
  63271. this._deviceRoomRotationQuaternion.z *= -1;
  63272. this._deviceRoomRotationQuaternion.w *= -1;
  63273. }
  63274. else {
  63275. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63276. }
  63277. }
  63278. // if the camera is set, rotate to the camera's rotation
  63279. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63280. }
  63281. }
  63282. };
  63283. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63284. if (this._mesh) {
  63285. this._mesh.parent = null;
  63286. }
  63287. this._mesh = mesh;
  63288. if (this._poseControlledCamera) {
  63289. this._mesh.parent = this._poseControlledCamera;
  63290. }
  63291. if (!this._mesh.rotationQuaternion) {
  63292. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63293. }
  63294. };
  63295. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63296. this._poseControlledCamera = camera;
  63297. if (this._mesh) {
  63298. this._mesh.parent = this._poseControlledCamera;
  63299. }
  63300. };
  63301. PoseEnabledController.prototype.dispose = function () {
  63302. if (this._mesh) {
  63303. this._mesh.dispose();
  63304. }
  63305. this._mesh = null;
  63306. _super.prototype.dispose.call(this);
  63307. };
  63308. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63309. get: function () {
  63310. return this._mesh;
  63311. },
  63312. enumerable: true,
  63313. configurable: true
  63314. });
  63315. PoseEnabledController.prototype.getForwardRay = function (length) {
  63316. if (length === void 0) { length = 100; }
  63317. if (!this.mesh) {
  63318. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63319. }
  63320. var m = this.mesh.getWorldMatrix();
  63321. var origin = m.getTranslation();
  63322. var forward = new BABYLON.Vector3(0, 0, -1);
  63323. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63324. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63325. return new BABYLON.Ray(origin, direction, length);
  63326. };
  63327. return PoseEnabledController;
  63328. }(BABYLON.Gamepad));
  63329. BABYLON.PoseEnabledController = PoseEnabledController;
  63330. })(BABYLON || (BABYLON = {}));
  63331. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63332. var BABYLON;
  63333. (function (BABYLON) {
  63334. var WebVRController = /** @class */ (function (_super) {
  63335. __extends(WebVRController, _super);
  63336. function WebVRController(vrGamepad) {
  63337. var _this = _super.call(this, vrGamepad) || this;
  63338. // Observables
  63339. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63340. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63341. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63342. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63343. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63344. _this.pad = { x: 0, y: 0 };
  63345. // avoid GC, store state in a tmp object
  63346. _this._changes = {
  63347. pressChanged: false,
  63348. touchChanged: false,
  63349. valueChanged: false,
  63350. changed: false
  63351. };
  63352. _this._buttons = new Array(vrGamepad.buttons.length);
  63353. _this.hand = vrGamepad.hand;
  63354. return _this;
  63355. }
  63356. WebVRController.prototype.onButtonStateChange = function (callback) {
  63357. this._onButtonStateChange = callback;
  63358. };
  63359. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63360. get: function () {
  63361. return this._defaultModel;
  63362. },
  63363. enumerable: true,
  63364. configurable: true
  63365. });
  63366. WebVRController.prototype.update = function () {
  63367. _super.prototype.update.call(this);
  63368. for (var index = 0; index < this._buttons.length; index++) {
  63369. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63370. }
  63371. ;
  63372. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63373. this.pad.x = this.leftStick.x;
  63374. this.pad.y = this.leftStick.y;
  63375. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63376. }
  63377. };
  63378. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63379. if (!newState) {
  63380. newState = {
  63381. pressed: false,
  63382. touched: false,
  63383. value: 0
  63384. };
  63385. }
  63386. if (!currentState) {
  63387. this._buttons[buttonIndex] = {
  63388. pressed: newState.pressed,
  63389. touched: newState.touched,
  63390. value: newState.value
  63391. };
  63392. return;
  63393. }
  63394. this._checkChanges(newState, currentState);
  63395. if (this._changes.changed) {
  63396. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63397. this.handleButtonChange(buttonIndex, newState, this._changes);
  63398. }
  63399. this._buttons[buttonIndex].pressed = newState.pressed;
  63400. this._buttons[buttonIndex].touched = newState.touched;
  63401. // oculus triggers are never 0, thou not touched.
  63402. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63403. };
  63404. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63405. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63406. this._changes.touchChanged = newState.touched !== currentState.touched;
  63407. this._changes.valueChanged = newState.value !== currentState.value;
  63408. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63409. return this._changes;
  63410. };
  63411. WebVRController.prototype.dispose = function () {
  63412. _super.prototype.dispose.call(this);
  63413. this.onTriggerStateChangedObservable.clear();
  63414. this.onMainButtonStateChangedObservable.clear();
  63415. this.onSecondaryButtonStateChangedObservable.clear();
  63416. this.onPadStateChangedObservable.clear();
  63417. this.onPadValuesChangedObservable.clear();
  63418. };
  63419. return WebVRController;
  63420. }(BABYLON.PoseEnabledController));
  63421. BABYLON.WebVRController = WebVRController;
  63422. })(BABYLON || (BABYLON = {}));
  63423. //# sourceMappingURL=babylon.webVRController.js.map
  63424. var BABYLON;
  63425. (function (BABYLON) {
  63426. var OculusTouchController = /** @class */ (function (_super) {
  63427. __extends(OculusTouchController, _super);
  63428. function OculusTouchController(vrGamepad) {
  63429. var _this = _super.call(this, vrGamepad) || this;
  63430. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63431. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63432. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63433. return _this;
  63434. }
  63435. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63436. var _this = this;
  63437. var meshName;
  63438. // Hand
  63439. if (this.hand === 'left') {
  63440. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63441. }
  63442. else {
  63443. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63444. }
  63445. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63446. /*
  63447. Parent Mesh name: oculus_touch_left
  63448. - body
  63449. - trigger
  63450. - thumbstick
  63451. - grip
  63452. - button_y
  63453. - button_x
  63454. - button_enter
  63455. */
  63456. _this._defaultModel = newMeshes[1];
  63457. _this.attachToMesh(_this._defaultModel);
  63458. if (meshLoaded) {
  63459. meshLoaded(_this._defaultModel);
  63460. }
  63461. });
  63462. };
  63463. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63464. // helper getters for left and right hand.
  63465. get: function () {
  63466. if (this.hand === 'right') {
  63467. return this.onMainButtonStateChangedObservable;
  63468. }
  63469. else {
  63470. throw new Error('No A button on left hand');
  63471. }
  63472. },
  63473. enumerable: true,
  63474. configurable: true
  63475. });
  63476. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63477. get: function () {
  63478. if (this.hand === 'right') {
  63479. return this.onSecondaryButtonStateChangedObservable;
  63480. }
  63481. else {
  63482. throw new Error('No B button on left hand');
  63483. }
  63484. },
  63485. enumerable: true,
  63486. configurable: true
  63487. });
  63488. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63489. get: function () {
  63490. if (this.hand === 'left') {
  63491. return this.onMainButtonStateChangedObservable;
  63492. }
  63493. else {
  63494. throw new Error('No X button on right hand');
  63495. }
  63496. },
  63497. enumerable: true,
  63498. configurable: true
  63499. });
  63500. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63501. get: function () {
  63502. if (this.hand === 'left') {
  63503. return this.onSecondaryButtonStateChangedObservable;
  63504. }
  63505. else {
  63506. throw new Error('No Y button on right hand');
  63507. }
  63508. },
  63509. enumerable: true,
  63510. configurable: true
  63511. });
  63512. /*
  63513. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63514. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63515. 2) secondary trigger (same)
  63516. 3) A (right) X (left), touch, pressed = value
  63517. 4) B / Y
  63518. 5) thumb rest
  63519. */
  63520. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63521. var notifyObject = state; //{ state: state, changes: changes };
  63522. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63523. switch (buttonIdx) {
  63524. case 0:
  63525. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63526. return;
  63527. case 1:// index trigger
  63528. if (this._defaultModel) {
  63529. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63530. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63531. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63532. }
  63533. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63534. return;
  63535. case 2:// secondary trigger
  63536. if (this._defaultModel) {
  63537. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63538. }
  63539. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63540. return;
  63541. case 3:
  63542. if (this._defaultModel) {
  63543. if (notifyObject.pressed) {
  63544. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63545. }
  63546. else {
  63547. (this._defaultModel.getChildren()[1]).position.y = 0;
  63548. }
  63549. }
  63550. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63551. return;
  63552. case 4:
  63553. if (this._defaultModel) {
  63554. if (notifyObject.pressed) {
  63555. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63556. }
  63557. else {
  63558. (this._defaultModel.getChildren()[2]).position.y = 0;
  63559. }
  63560. }
  63561. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63562. return;
  63563. case 5:
  63564. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63565. return;
  63566. }
  63567. };
  63568. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63569. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63570. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63571. return OculusTouchController;
  63572. }(BABYLON.WebVRController));
  63573. BABYLON.OculusTouchController = OculusTouchController;
  63574. })(BABYLON || (BABYLON = {}));
  63575. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63576. var BABYLON;
  63577. (function (BABYLON) {
  63578. var ViveController = /** @class */ (function (_super) {
  63579. __extends(ViveController, _super);
  63580. function ViveController(vrGamepad) {
  63581. var _this = _super.call(this, vrGamepad) || this;
  63582. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63583. _this._invertLeftStickY = true;
  63584. return _this;
  63585. }
  63586. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63587. var _this = this;
  63588. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63589. /*
  63590. Parent Mesh name: ViveWand
  63591. - body
  63592. - r_gripper
  63593. - l_gripper
  63594. - menu_button
  63595. - system_button
  63596. - trackpad
  63597. - trigger
  63598. - LED
  63599. */
  63600. _this._defaultModel = newMeshes[1];
  63601. _this.attachToMesh(_this._defaultModel);
  63602. if (meshLoaded) {
  63603. meshLoaded(_this._defaultModel);
  63604. }
  63605. });
  63606. };
  63607. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63608. get: function () {
  63609. return this.onMainButtonStateChangedObservable;
  63610. },
  63611. enumerable: true,
  63612. configurable: true
  63613. });
  63614. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63615. get: function () {
  63616. return this.onMainButtonStateChangedObservable;
  63617. },
  63618. enumerable: true,
  63619. configurable: true
  63620. });
  63621. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63622. get: function () {
  63623. return this.onSecondaryButtonStateChangedObservable;
  63624. },
  63625. enumerable: true,
  63626. configurable: true
  63627. });
  63628. /**
  63629. * Vive mapping:
  63630. * 0: touchpad
  63631. * 1: trigger
  63632. * 2: left AND right buttons
  63633. * 3: menu button
  63634. */
  63635. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63636. var notifyObject = state; //{ state: state, changes: changes };
  63637. switch (buttonIdx) {
  63638. case 0:
  63639. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63640. return;
  63641. case 1:// index trigger
  63642. if (this._defaultModel) {
  63643. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63644. }
  63645. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63646. return;
  63647. case 2:// left AND right button
  63648. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63649. return;
  63650. case 3:
  63651. if (this._defaultModel) {
  63652. if (notifyObject.pressed) {
  63653. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63654. }
  63655. else {
  63656. (this._defaultModel.getChildren()[2]).position.y = 0;
  63657. }
  63658. }
  63659. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63660. return;
  63661. }
  63662. };
  63663. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63664. ViveController.MODEL_FILENAME = 'wand.babylon';
  63665. return ViveController;
  63666. }(BABYLON.WebVRController));
  63667. BABYLON.ViveController = ViveController;
  63668. })(BABYLON || (BABYLON = {}));
  63669. //# sourceMappingURL=babylon.viveController.js.map
  63670. var BABYLON;
  63671. (function (BABYLON) {
  63672. var GenericController = /** @class */ (function (_super) {
  63673. __extends(GenericController, _super);
  63674. function GenericController(vrGamepad) {
  63675. return _super.call(this, vrGamepad) || this;
  63676. }
  63677. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63678. var _this = this;
  63679. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63680. _this._defaultModel = newMeshes[1];
  63681. _this.attachToMesh(_this._defaultModel);
  63682. if (meshLoaded) {
  63683. meshLoaded(_this._defaultModel);
  63684. }
  63685. });
  63686. };
  63687. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63688. console.log("Button id: " + buttonIdx + "state: ");
  63689. console.dir(state);
  63690. };
  63691. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63692. GenericController.MODEL_FILENAME = 'generic.babylon';
  63693. return GenericController;
  63694. }(BABYLON.WebVRController));
  63695. BABYLON.GenericController = GenericController;
  63696. })(BABYLON || (BABYLON = {}));
  63697. //# sourceMappingURL=babylon.genericController.js.map
  63698. var BABYLON;
  63699. (function (BABYLON) {
  63700. var LoadedMeshInfo = /** @class */ (function () {
  63701. function LoadedMeshInfo() {
  63702. this.buttonMeshes = {};
  63703. this.axisMeshes = {};
  63704. }
  63705. return LoadedMeshInfo;
  63706. }());
  63707. var WindowsMotionController = /** @class */ (function (_super) {
  63708. __extends(WindowsMotionController, _super);
  63709. function WindowsMotionController(vrGamepad) {
  63710. var _this = _super.call(this, vrGamepad) || this;
  63711. _this._mapping = {
  63712. // Semantic button names
  63713. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63714. // A mapping of the button name to glTF model node name
  63715. // that should be transformed by button value.
  63716. buttonMeshNames: {
  63717. 'trigger': 'SELECT',
  63718. 'menu': 'MENU',
  63719. 'grip': 'GRASP',
  63720. 'thumbstick': 'THUMBSTICK_PRESS',
  63721. 'trackpad': 'TOUCHPAD_PRESS'
  63722. },
  63723. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63724. buttonObservableNames: {
  63725. 'trigger': 'onTriggerStateChangedObservable',
  63726. 'menu': 'onSecondaryButtonStateChangedObservable',
  63727. 'grip': 'onMainButtonStateChangedObservable',
  63728. 'thumbstick': 'onPadStateChangedObservable',
  63729. 'trackpad': 'onTrackpadChangedObservable'
  63730. },
  63731. // A mapping of the axis name to glTF model node name
  63732. // that should be transformed by axis value.
  63733. // This array mirrors the browserGamepad.axes array, such that
  63734. // the mesh corresponding to axis 0 is in this array index 0.
  63735. axisMeshNames: [
  63736. 'THUMBSTICK_X',
  63737. 'THUMBSTICK_Y',
  63738. 'TOUCHPAD_TOUCH_X',
  63739. 'TOUCHPAD_TOUCH_Y'
  63740. ],
  63741. pointingPoseMeshName: 'POINTING_POSE'
  63742. };
  63743. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63744. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63745. _this.trackpad = { x: 0, y: 0 };
  63746. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63747. _this._loadedMeshInfo = null;
  63748. return _this;
  63749. }
  63750. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63751. get: function () {
  63752. return this.onTriggerStateChangedObservable;
  63753. },
  63754. enumerable: true,
  63755. configurable: true
  63756. });
  63757. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63758. get: function () {
  63759. return this.onSecondaryButtonStateChangedObservable;
  63760. },
  63761. enumerable: true,
  63762. configurable: true
  63763. });
  63764. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63765. get: function () {
  63766. return this.onMainButtonStateChangedObservable;
  63767. },
  63768. enumerable: true,
  63769. configurable: true
  63770. });
  63771. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63772. get: function () {
  63773. return this.onPadStateChangedObservable;
  63774. },
  63775. enumerable: true,
  63776. configurable: true
  63777. });
  63778. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63779. get: function () {
  63780. return this.onTrackpadChangedObservable;
  63781. },
  63782. enumerable: true,
  63783. configurable: true
  63784. });
  63785. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63786. get: function () {
  63787. return this.onTrackpadValuesChangedObservable;
  63788. },
  63789. enumerable: true,
  63790. configurable: true
  63791. });
  63792. /**
  63793. * Called once per frame by the engine.
  63794. */
  63795. WindowsMotionController.prototype.update = function () {
  63796. _super.prototype.update.call(this);
  63797. // Only need to animate axes if there is a loaded mesh
  63798. if (this._loadedMeshInfo) {
  63799. if (this.browserGamepad.axes) {
  63800. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63801. this.trackpad.x = this.browserGamepad["axes"][2];
  63802. this.trackpad.y = this.browserGamepad["axes"][3];
  63803. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63804. }
  63805. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63806. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63807. }
  63808. }
  63809. }
  63810. };
  63811. /**
  63812. * Called once for each button that changed state since the last frame
  63813. * @param buttonIdx Which button index changed
  63814. * @param state New state of the button
  63815. * @param changes Which properties on the state changed since last frame
  63816. */
  63817. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63818. var buttonName = this._mapping.buttons[buttonIdx];
  63819. if (!buttonName) {
  63820. return;
  63821. }
  63822. // Only emit events for buttons that we know how to map from index to name
  63823. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63824. if (observable) {
  63825. observable.notifyObservers(state);
  63826. }
  63827. this.lerpButtonTransform(buttonName, state.value);
  63828. };
  63829. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63830. // If there is no loaded mesh, there is nothing to transform.
  63831. if (!this._loadedMeshInfo) {
  63832. return;
  63833. }
  63834. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63835. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63836. return;
  63837. }
  63838. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63839. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63840. };
  63841. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63842. if (!this._loadedMeshInfo) {
  63843. return;
  63844. }
  63845. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63846. if (!meshInfo) {
  63847. return;
  63848. }
  63849. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63850. return;
  63851. }
  63852. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63853. var lerpValue = axisValue * 0.5 + 0.5;
  63854. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63855. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63856. };
  63857. /**
  63858. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63859. * @param scene scene in which to add meshes
  63860. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63861. */
  63862. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63863. var _this = this;
  63864. if (forceDefault === void 0) { forceDefault = false; }
  63865. var path;
  63866. var filename;
  63867. // Checking if GLB loader is present
  63868. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63869. // Determine the device specific folder based on the ID suffix
  63870. var device = 'default';
  63871. if (this.id && !forceDefault) {
  63872. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63873. device = ((match && match[0]) || device);
  63874. }
  63875. // Hand
  63876. if (this.hand === 'left') {
  63877. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63878. }
  63879. else {
  63880. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63881. }
  63882. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63883. }
  63884. else {
  63885. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63886. path = BABYLON.GenericController.MODEL_BASE_URL;
  63887. filename = BABYLON.GenericController.MODEL_FILENAME;
  63888. }
  63889. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63890. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63891. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63892. if (!_this._loadedMeshInfo) {
  63893. return;
  63894. }
  63895. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63896. _this.attachToMesh(_this._defaultModel);
  63897. if (meshLoaded) {
  63898. meshLoaded(_this._defaultModel);
  63899. }
  63900. }, null, function (scene, message) {
  63901. BABYLON.Tools.Log(message);
  63902. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63903. if (!forceDefault) {
  63904. _this.initControllerMesh(scene, meshLoaded, true);
  63905. }
  63906. });
  63907. };
  63908. /**
  63909. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63910. * can be transformed by button presses and axes values, based on this._mapping.
  63911. *
  63912. * @param scene scene in which the meshes exist
  63913. * @param meshes list of meshes that make up the controller model to process
  63914. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63915. */
  63916. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63917. var loadedMeshInfo = null;
  63918. // Create a new mesh to contain the glTF hierarchy
  63919. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63920. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63921. var childMesh = null;
  63922. for (var i = 0; i < meshes.length; i++) {
  63923. var mesh = meshes[i];
  63924. if (!mesh.parent) {
  63925. // Exclude controller meshes from picking results
  63926. mesh.isPickable = false;
  63927. // Handle root node, attach to the new parentMesh
  63928. childMesh = mesh;
  63929. break;
  63930. }
  63931. }
  63932. if (childMesh) {
  63933. childMesh.setParent(parentMesh);
  63934. // Create our mesh info. Note that this method will always return non-null.
  63935. loadedMeshInfo = this.createMeshInfo(parentMesh);
  63936. }
  63937. else {
  63938. BABYLON.Tools.Warn('Could not find root node in model file.');
  63939. }
  63940. return loadedMeshInfo;
  63941. };
  63942. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  63943. var loadedMeshInfo = new LoadedMeshInfo();
  63944. var i;
  63945. loadedMeshInfo.rootNode = rootNode;
  63946. // Reset the caches
  63947. loadedMeshInfo.buttonMeshes = {};
  63948. loadedMeshInfo.axisMeshes = {};
  63949. // Button Meshes
  63950. for (i = 0; i < this._mapping.buttons.length; i++) {
  63951. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  63952. if (!buttonMeshName) {
  63953. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  63954. continue;
  63955. }
  63956. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  63957. if (!buttonMesh) {
  63958. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  63959. continue;
  63960. }
  63961. var buttonMeshInfo = {
  63962. index: i,
  63963. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  63964. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  63965. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  63966. };
  63967. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  63968. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  63969. }
  63970. else {
  63971. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  63972. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  63973. '(VALUE: ' + !!buttonMeshInfo.value +
  63974. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  63975. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  63976. ')');
  63977. }
  63978. }
  63979. // Axis Meshes
  63980. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  63981. var axisMeshName = this._mapping.axisMeshNames[i];
  63982. if (!axisMeshName) {
  63983. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  63984. continue;
  63985. }
  63986. var axisMesh = getChildByName(rootNode, axisMeshName);
  63987. if (!axisMesh) {
  63988. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  63989. continue;
  63990. }
  63991. var axisMeshInfo = {
  63992. index: i,
  63993. value: getImmediateChildByName(axisMesh, 'VALUE'),
  63994. min: getImmediateChildByName(axisMesh, 'MIN'),
  63995. max: getImmediateChildByName(axisMesh, 'MAX')
  63996. };
  63997. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  63998. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  63999. }
  64000. else {
  64001. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64002. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64003. '(VALUE: ' + !!axisMeshInfo.value +
  64004. ', MIN: ' + !!axisMeshInfo.min +
  64005. ', MAX:' + !!axisMeshInfo.max +
  64006. ')');
  64007. }
  64008. }
  64009. // Pointing Ray
  64010. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64011. if (!loadedMeshInfo.pointingPoseNode) {
  64012. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64013. }
  64014. return loadedMeshInfo;
  64015. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64016. function getChildByName(node, name) {
  64017. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64018. }
  64019. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64020. function getImmediateChildByName(node, name) {
  64021. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64022. }
  64023. };
  64024. WindowsMotionController.prototype.getForwardRay = function (length) {
  64025. if (length === void 0) { length = 100; }
  64026. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64027. return _super.prototype.getForwardRay.call(this, length);
  64028. }
  64029. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64030. var origin = m.getTranslation();
  64031. var forward = new BABYLON.Vector3(0, 0, -1);
  64032. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64033. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64034. return new BABYLON.Ray(origin, direction, length);
  64035. };
  64036. WindowsMotionController.prototype.dispose = function () {
  64037. _super.prototype.dispose.call(this);
  64038. this.onTrackpadChangedObservable.clear();
  64039. };
  64040. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64041. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64042. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64043. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64044. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64045. return WindowsMotionController;
  64046. }(BABYLON.WebVRController));
  64047. BABYLON.WindowsMotionController = WindowsMotionController;
  64048. })(BABYLON || (BABYLON = {}));
  64049. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64050. var BABYLON;
  64051. (function (BABYLON) {
  64052. var GearVRController = /** @class */ (function (_super) {
  64053. __extends(GearVRController, _super);
  64054. function GearVRController(vrGamepad) {
  64055. var _this = _super.call(this, vrGamepad) || this;
  64056. _this._buttonIndexToObservableNameMap = [
  64057. 'onTrackpadChangedObservable',
  64058. 'onTriggerStateChangedObservable' // Trigger
  64059. ];
  64060. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  64061. return _this;
  64062. }
  64063. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64064. var _this = this;
  64065. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64066. _this._defaultModel = newMeshes[1];
  64067. _this.attachToMesh(_this._defaultModel);
  64068. if (meshLoaded) {
  64069. meshLoaded(_this._defaultModel);
  64070. }
  64071. });
  64072. };
  64073. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64074. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64075. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64076. // Only emit events for buttons that we know how to map from index to observable
  64077. var observable = this[observableName];
  64078. if (observable) {
  64079. observable.notifyObservers(state);
  64080. }
  64081. }
  64082. };
  64083. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64084. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64085. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64086. return GearVRController;
  64087. }(BABYLON.WebVRController));
  64088. BABYLON.GearVRController = GearVRController;
  64089. })(BABYLON || (BABYLON = {}));
  64090. //# sourceMappingURL=babylon.gearVRController.js.map
  64091. var BABYLON;
  64092. (function (BABYLON) {
  64093. var FollowCamera = /** @class */ (function (_super) {
  64094. __extends(FollowCamera, _super);
  64095. function FollowCamera(name, position, scene, lockedTarget) {
  64096. if (lockedTarget === void 0) { lockedTarget = null; }
  64097. var _this = _super.call(this, name, position, scene) || this;
  64098. _this.radius = 12;
  64099. _this.rotationOffset = 0;
  64100. _this.heightOffset = 4;
  64101. _this.cameraAcceleration = 0.05;
  64102. _this.maxCameraSpeed = 20;
  64103. _this.lockedTarget = lockedTarget;
  64104. return _this;
  64105. }
  64106. FollowCamera.prototype.getRadians = function (degrees) {
  64107. return degrees * Math.PI / 180;
  64108. };
  64109. FollowCamera.prototype.follow = function (cameraTarget) {
  64110. if (!cameraTarget)
  64111. return;
  64112. var yRotation;
  64113. if (cameraTarget.rotationQuaternion) {
  64114. var rotMatrix = new BABYLON.Matrix();
  64115. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64116. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64117. }
  64118. else {
  64119. yRotation = cameraTarget.rotation.y;
  64120. }
  64121. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64122. var targetPosition = cameraTarget.getAbsolutePosition();
  64123. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64124. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64125. var dx = targetX - this.position.x;
  64126. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64127. var dz = (targetZ) - this.position.z;
  64128. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64129. var vy = dy * this.cameraAcceleration;
  64130. var vz = dz * this.cameraAcceleration * 2;
  64131. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64132. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64133. }
  64134. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64135. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64136. }
  64137. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64138. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64139. }
  64140. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64141. this.setTarget(targetPosition);
  64142. };
  64143. FollowCamera.prototype._checkInputs = function () {
  64144. _super.prototype._checkInputs.call(this);
  64145. if (this.lockedTarget) {
  64146. this.follow(this.lockedTarget);
  64147. }
  64148. };
  64149. FollowCamera.prototype.getClassName = function () {
  64150. return "FollowCamera";
  64151. };
  64152. __decorate([
  64153. BABYLON.serialize()
  64154. ], FollowCamera.prototype, "radius", void 0);
  64155. __decorate([
  64156. BABYLON.serialize()
  64157. ], FollowCamera.prototype, "rotationOffset", void 0);
  64158. __decorate([
  64159. BABYLON.serialize()
  64160. ], FollowCamera.prototype, "heightOffset", void 0);
  64161. __decorate([
  64162. BABYLON.serialize()
  64163. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64164. __decorate([
  64165. BABYLON.serialize()
  64166. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64167. __decorate([
  64168. BABYLON.serializeAsMeshReference("lockedTargetId")
  64169. ], FollowCamera.prototype, "lockedTarget", void 0);
  64170. return FollowCamera;
  64171. }(BABYLON.TargetCamera));
  64172. BABYLON.FollowCamera = FollowCamera;
  64173. var ArcFollowCamera = /** @class */ (function (_super) {
  64174. __extends(ArcFollowCamera, _super);
  64175. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64176. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64177. _this.alpha = alpha;
  64178. _this.beta = beta;
  64179. _this.radius = radius;
  64180. _this.target = target;
  64181. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64182. _this.follow();
  64183. return _this;
  64184. }
  64185. ArcFollowCamera.prototype.follow = function () {
  64186. if (!this.target) {
  64187. return;
  64188. }
  64189. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64190. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64191. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64192. var targetPosition = this.target.getAbsolutePosition();
  64193. this.position = targetPosition.add(this._cartesianCoordinates);
  64194. this.setTarget(targetPosition);
  64195. };
  64196. ArcFollowCamera.prototype._checkInputs = function () {
  64197. _super.prototype._checkInputs.call(this);
  64198. this.follow();
  64199. };
  64200. ArcFollowCamera.prototype.getClassName = function () {
  64201. return "ArcFollowCamera";
  64202. };
  64203. return ArcFollowCamera;
  64204. }(BABYLON.TargetCamera));
  64205. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64206. })(BABYLON || (BABYLON = {}));
  64207. //# sourceMappingURL=babylon.followCamera.js.map
  64208. var BABYLON;
  64209. (function (BABYLON) {
  64210. // We're mainly based on the logic defined into the FreeCamera code
  64211. var UniversalCamera = /** @class */ (function (_super) {
  64212. __extends(UniversalCamera, _super);
  64213. //-- end properties for backward compatibility for inputs
  64214. function UniversalCamera(name, position, scene) {
  64215. var _this = _super.call(this, name, position, scene) || this;
  64216. _this.inputs.addGamepad();
  64217. return _this;
  64218. }
  64219. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64220. //-- Begin properties for backward compatibility for inputs
  64221. get: function () {
  64222. var gamepad = this.inputs.attached["gamepad"];
  64223. if (gamepad)
  64224. return gamepad.gamepadAngularSensibility;
  64225. return 0;
  64226. },
  64227. set: function (value) {
  64228. var gamepad = this.inputs.attached["gamepad"];
  64229. if (gamepad)
  64230. gamepad.gamepadAngularSensibility = value;
  64231. },
  64232. enumerable: true,
  64233. configurable: true
  64234. });
  64235. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64236. get: function () {
  64237. var gamepad = this.inputs.attached["gamepad"];
  64238. if (gamepad)
  64239. return gamepad.gamepadMoveSensibility;
  64240. return 0;
  64241. },
  64242. set: function (value) {
  64243. var gamepad = this.inputs.attached["gamepad"];
  64244. if (gamepad)
  64245. gamepad.gamepadMoveSensibility = value;
  64246. },
  64247. enumerable: true,
  64248. configurable: true
  64249. });
  64250. UniversalCamera.prototype.getClassName = function () {
  64251. return "UniversalCamera";
  64252. };
  64253. return UniversalCamera;
  64254. }(BABYLON.TouchCamera));
  64255. BABYLON.UniversalCamera = UniversalCamera;
  64256. })(BABYLON || (BABYLON = {}));
  64257. //# sourceMappingURL=babylon.universalCamera.js.map
  64258. var BABYLON;
  64259. (function (BABYLON) {
  64260. // We're mainly based on the logic defined into the FreeCamera code
  64261. var GamepadCamera = /** @class */ (function (_super) {
  64262. __extends(GamepadCamera, _super);
  64263. //-- end properties for backward compatibility for inputs
  64264. function GamepadCamera(name, position, scene) {
  64265. return _super.call(this, name, position, scene) || this;
  64266. }
  64267. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64268. //-- Begin properties for backward compatibility for inputs
  64269. get: function () {
  64270. var gamepad = this.inputs.attached["gamepad"];
  64271. if (gamepad)
  64272. return gamepad.gamepadAngularSensibility;
  64273. return 0;
  64274. },
  64275. set: function (value) {
  64276. var gamepad = this.inputs.attached["gamepad"];
  64277. if (gamepad)
  64278. gamepad.gamepadAngularSensibility = value;
  64279. },
  64280. enumerable: true,
  64281. configurable: true
  64282. });
  64283. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64284. get: function () {
  64285. var gamepad = this.inputs.attached["gamepad"];
  64286. if (gamepad)
  64287. return gamepad.gamepadMoveSensibility;
  64288. return 0;
  64289. },
  64290. set: function (value) {
  64291. var gamepad = this.inputs.attached["gamepad"];
  64292. if (gamepad)
  64293. gamepad.gamepadMoveSensibility = value;
  64294. },
  64295. enumerable: true,
  64296. configurable: true
  64297. });
  64298. GamepadCamera.prototype.getClassName = function () {
  64299. return "GamepadCamera";
  64300. };
  64301. return GamepadCamera;
  64302. }(BABYLON.UniversalCamera));
  64303. BABYLON.GamepadCamera = GamepadCamera;
  64304. })(BABYLON || (BABYLON = {}));
  64305. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64306. var BABYLON;
  64307. (function (BABYLON) {
  64308. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64309. function PostProcessRenderPipelineManager() {
  64310. this._renderPipelines = {};
  64311. }
  64312. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64313. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64314. };
  64315. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64316. if (unique === void 0) { unique = false; }
  64317. var renderPipeline = this._renderPipelines[renderPipelineName];
  64318. if (!renderPipeline) {
  64319. return;
  64320. }
  64321. renderPipeline._attachCameras(cameras, unique);
  64322. };
  64323. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64324. var renderPipeline = this._renderPipelines[renderPipelineName];
  64325. if (!renderPipeline) {
  64326. return;
  64327. }
  64328. renderPipeline._detachCameras(cameras);
  64329. };
  64330. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64331. var renderPipeline = this._renderPipelines[renderPipelineName];
  64332. if (!renderPipeline) {
  64333. return;
  64334. }
  64335. renderPipeline._enableEffect(renderEffectName, cameras);
  64336. };
  64337. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64338. var renderPipeline = this._renderPipelines[renderPipelineName];
  64339. if (!renderPipeline) {
  64340. return;
  64341. }
  64342. renderPipeline._disableEffect(renderEffectName, cameras);
  64343. };
  64344. PostProcessRenderPipelineManager.prototype.update = function () {
  64345. for (var renderPipelineName in this._renderPipelines) {
  64346. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64347. var pipeline = this._renderPipelines[renderPipelineName];
  64348. if (!pipeline.isSupported) {
  64349. pipeline.dispose();
  64350. delete this._renderPipelines[renderPipelineName];
  64351. }
  64352. else {
  64353. pipeline._update();
  64354. }
  64355. }
  64356. }
  64357. };
  64358. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64359. for (var renderPipelineName in this._renderPipelines) {
  64360. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64361. var pipeline = this._renderPipelines[renderPipelineName];
  64362. pipeline._rebuild();
  64363. }
  64364. }
  64365. };
  64366. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64367. for (var renderPipelineName in this._renderPipelines) {
  64368. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64369. var pipeline = this._renderPipelines[renderPipelineName];
  64370. pipeline.dispose();
  64371. }
  64372. }
  64373. };
  64374. return PostProcessRenderPipelineManager;
  64375. }());
  64376. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64377. })(BABYLON || (BABYLON = {}));
  64378. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64379. var BABYLON;
  64380. (function (BABYLON) {
  64381. /**
  64382. * This represents a set of one or more post processes in Babylon.
  64383. * A post process can be used to apply a shader to a texture after it is rendered.
  64384. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64385. */
  64386. var PostProcessRenderEffect = /** @class */ (function () {
  64387. /**
  64388. * Instantiates a post process render effect.
  64389. * A post process can be used to apply a shader to a texture after it is rendered.
  64390. * @param engine The engine the effect is tied to
  64391. * @param name The name of the effect
  64392. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64393. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64394. */
  64395. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64396. this._name = name;
  64397. this._singleInstance = singleInstance || true;
  64398. this._getPostProcesses = getPostProcesses;
  64399. this._cameras = {};
  64400. this._indicesForCamera = {};
  64401. this._postProcesses = {};
  64402. }
  64403. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64404. /**
  64405. * Checks if all the post processes in the effect are supported.
  64406. */
  64407. get: function () {
  64408. for (var index in this._postProcesses) {
  64409. for (var ppIndex in this._postProcesses[index]) {
  64410. if (!this._postProcesses[index][ppIndex].isSupported) {
  64411. return false;
  64412. }
  64413. }
  64414. }
  64415. return true;
  64416. },
  64417. enumerable: true,
  64418. configurable: true
  64419. });
  64420. /**
  64421. * Updates the current state of the effect
  64422. */
  64423. PostProcessRenderEffect.prototype._update = function () {
  64424. };
  64425. /**
  64426. * Attaches the effect on cameras
  64427. * @param cameras The camera to attach to.
  64428. */
  64429. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64430. var _this = this;
  64431. var cameraKey;
  64432. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64433. if (!cams) {
  64434. return;
  64435. }
  64436. for (var i = 0; i < cams.length; i++) {
  64437. var camera = cams[i];
  64438. var cameraName = camera.name;
  64439. if (this._singleInstance) {
  64440. cameraKey = 0;
  64441. }
  64442. else {
  64443. cameraKey = cameraName;
  64444. }
  64445. if (!this._postProcesses[cameraKey]) {
  64446. var postProcess = this._getPostProcesses();
  64447. if (postProcess) {
  64448. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64449. }
  64450. }
  64451. if (!this._indicesForCamera[cameraName]) {
  64452. this._indicesForCamera[cameraName] = [];
  64453. }
  64454. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64455. var index = camera.attachPostProcess(postProcess);
  64456. _this._indicesForCamera[cameraName].push(index);
  64457. });
  64458. if (!this._cameras[cameraName]) {
  64459. this._cameras[cameraName] = camera;
  64460. }
  64461. }
  64462. };
  64463. /**
  64464. * Detatches the effect on cameras
  64465. * @param cameras The camera to detatch from.
  64466. */
  64467. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64468. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64469. if (!cams) {
  64470. return;
  64471. }
  64472. for (var i = 0; i < cams.length; i++) {
  64473. var camera = cams[i];
  64474. var cameraName = camera.name;
  64475. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64476. camera.detachPostProcess(postProcess);
  64477. });
  64478. if (this._cameras[cameraName]) {
  64479. //this._indicesForCamera.splice(index, 1);
  64480. this._cameras[cameraName] = null;
  64481. }
  64482. }
  64483. };
  64484. /**
  64485. * Enables the effect on given cameras
  64486. * @param cameras The camera to enable.
  64487. */
  64488. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64489. var _this = this;
  64490. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64491. if (!cams) {
  64492. return;
  64493. }
  64494. for (var i = 0; i < cams.length; i++) {
  64495. var camera = cams[i];
  64496. var cameraName = camera.name;
  64497. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64498. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64499. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64500. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64501. });
  64502. }
  64503. }
  64504. }
  64505. };
  64506. /**
  64507. * Disables the effect on the given cameras
  64508. * @param cameras The camera to disable.
  64509. */
  64510. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64511. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64512. if (!cams) {
  64513. return;
  64514. }
  64515. for (var i = 0; i < cams.length; i++) {
  64516. var camera = cams[i];
  64517. var cameraName = camera.name;
  64518. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64519. camera.detachPostProcess(postProcess);
  64520. });
  64521. }
  64522. };
  64523. /**
  64524. * Gets a list of the post processes contained in the effect.
  64525. * @param camera The camera to get the post processes on.
  64526. * @returns The list of the post processes in the effect.
  64527. */
  64528. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64529. if (this._singleInstance) {
  64530. return this._postProcesses[0];
  64531. }
  64532. else {
  64533. if (!camera) {
  64534. return null;
  64535. }
  64536. return this._postProcesses[camera.name];
  64537. }
  64538. };
  64539. return PostProcessRenderEffect;
  64540. }());
  64541. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64542. })(BABYLON || (BABYLON = {}));
  64543. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64544. var BABYLON;
  64545. (function (BABYLON) {
  64546. var PostProcessRenderPipeline = /** @class */ (function () {
  64547. function PostProcessRenderPipeline(engine, name) {
  64548. this._name = name;
  64549. this._renderEffects = {};
  64550. this._renderEffectsForIsolatedPass = new Array();
  64551. this._cameras = [];
  64552. }
  64553. PostProcessRenderPipeline.prototype.getClassName = function () {
  64554. return "PostProcessRenderPipeline";
  64555. };
  64556. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64557. get: function () {
  64558. for (var renderEffectName in this._renderEffects) {
  64559. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64560. if (!this._renderEffects[renderEffectName].isSupported) {
  64561. return false;
  64562. }
  64563. }
  64564. }
  64565. return true;
  64566. },
  64567. enumerable: true,
  64568. configurable: true
  64569. });
  64570. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64571. this._renderEffects[renderEffect._name] = renderEffect;
  64572. };
  64573. // private
  64574. PostProcessRenderPipeline.prototype._rebuild = function () {
  64575. };
  64576. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64577. var renderEffects = this._renderEffects[renderEffectName];
  64578. if (!renderEffects) {
  64579. return;
  64580. }
  64581. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64582. };
  64583. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64584. var renderEffects = this._renderEffects[renderEffectName];
  64585. if (!renderEffects) {
  64586. return;
  64587. }
  64588. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64589. };
  64590. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64591. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64592. if (!cams) {
  64593. return;
  64594. }
  64595. var indicesToDelete = [];
  64596. var i;
  64597. for (i = 0; i < cams.length; i++) {
  64598. var camera = cams[i];
  64599. var cameraName = camera.name;
  64600. if (this._cameras.indexOf(camera) === -1) {
  64601. this._cameras[cameraName] = camera;
  64602. }
  64603. else if (unique) {
  64604. indicesToDelete.push(i);
  64605. }
  64606. }
  64607. for (i = 0; i < indicesToDelete.length; i++) {
  64608. cameras.splice(indicesToDelete[i], 1);
  64609. }
  64610. for (var renderEffectName in this._renderEffects) {
  64611. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64612. this._renderEffects[renderEffectName]._attachCameras(cams);
  64613. }
  64614. }
  64615. };
  64616. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64617. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64618. if (!cams) {
  64619. return;
  64620. }
  64621. for (var renderEffectName in this._renderEffects) {
  64622. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64623. this._renderEffects[renderEffectName]._detachCameras(cams);
  64624. }
  64625. }
  64626. for (var i = 0; i < cams.length; i++) {
  64627. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64628. }
  64629. };
  64630. PostProcessRenderPipeline.prototype._update = function () {
  64631. for (var renderEffectName in this._renderEffects) {
  64632. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64633. this._renderEffects[renderEffectName]._update();
  64634. }
  64635. }
  64636. for (var i = 0; i < this._cameras.length; i++) {
  64637. var cameraName = this._cameras[i].name;
  64638. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64639. this._renderEffectsForIsolatedPass[cameraName]._update();
  64640. }
  64641. }
  64642. };
  64643. PostProcessRenderPipeline.prototype._reset = function () {
  64644. this._renderEffects = {};
  64645. this._renderEffectsForIsolatedPass = new Array();
  64646. };
  64647. PostProcessRenderPipeline.prototype.dispose = function () {
  64648. // Must be implemented by children
  64649. };
  64650. __decorate([
  64651. BABYLON.serialize()
  64652. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64653. return PostProcessRenderPipeline;
  64654. }());
  64655. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64656. })(BABYLON || (BABYLON = {}));
  64657. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64658. var BABYLON;
  64659. (function (BABYLON) {
  64660. var DepthRenderer = /** @class */ (function () {
  64661. function DepthRenderer(scene, type) {
  64662. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64663. var _this = this;
  64664. this._scene = scene;
  64665. var engine = scene.getEngine();
  64666. // Render target
  64667. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64668. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64669. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64670. this._depthMap.refreshRate = 1;
  64671. this._depthMap.renderParticles = false;
  64672. this._depthMap.renderList = null;
  64673. // set default depth value to 1.0 (far away)
  64674. this._depthMap.onClearObservable.add(function (engine) {
  64675. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64676. });
  64677. // Custom render function
  64678. var renderSubMesh = function (subMesh) {
  64679. var mesh = subMesh.getRenderingMesh();
  64680. var scene = _this._scene;
  64681. var engine = scene.getEngine();
  64682. var material = subMesh.getMaterial();
  64683. if (!material) {
  64684. return;
  64685. }
  64686. // Culling and reverse (right handed system)
  64687. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64688. // Managing instances
  64689. var batch = mesh._getInstancesRenderList(subMesh._id);
  64690. if (batch.mustReturn) {
  64691. return;
  64692. }
  64693. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64694. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64695. engine.enableEffect(_this._effect);
  64696. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64697. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64698. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64699. // Alpha test
  64700. if (material && material.needAlphaTesting()) {
  64701. var alphaTexture = material.getAlphaTestTexture();
  64702. if (alphaTexture) {
  64703. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64704. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64705. }
  64706. }
  64707. // Bones
  64708. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64709. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64710. }
  64711. // Draw
  64712. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64713. }
  64714. };
  64715. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64716. var index;
  64717. if (depthOnlySubMeshes.length) {
  64718. engine.setColorWrite(false);
  64719. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64720. renderSubMesh(depthOnlySubMeshes.data[index]);
  64721. }
  64722. engine.setColorWrite(true);
  64723. }
  64724. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64725. renderSubMesh(opaqueSubMeshes.data[index]);
  64726. }
  64727. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64728. renderSubMesh(alphaTestSubMeshes.data[index]);
  64729. }
  64730. };
  64731. }
  64732. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64733. var material = subMesh.getMaterial();
  64734. if (material.disableDepthWrite) {
  64735. return false;
  64736. }
  64737. var defines = [];
  64738. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64739. var mesh = subMesh.getMesh();
  64740. // Alpha test
  64741. if (material && material.needAlphaTesting()) {
  64742. defines.push("#define ALPHATEST");
  64743. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64744. attribs.push(BABYLON.VertexBuffer.UVKind);
  64745. defines.push("#define UV1");
  64746. }
  64747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64748. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64749. defines.push("#define UV2");
  64750. }
  64751. }
  64752. // Bones
  64753. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64754. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64755. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64756. if (mesh.numBoneInfluencers > 4) {
  64757. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64758. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64759. }
  64760. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64761. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64762. }
  64763. else {
  64764. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64765. }
  64766. // Instances
  64767. if (useInstances) {
  64768. defines.push("#define INSTANCES");
  64769. attribs.push("world0");
  64770. attribs.push("world1");
  64771. attribs.push("world2");
  64772. attribs.push("world3");
  64773. }
  64774. // Get correct effect
  64775. var join = defines.join("\n");
  64776. if (this._cachedDefines !== join) {
  64777. this._cachedDefines = join;
  64778. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64779. }
  64780. return this._effect.isReady();
  64781. };
  64782. DepthRenderer.prototype.getDepthMap = function () {
  64783. return this._depthMap;
  64784. };
  64785. // Methods
  64786. DepthRenderer.prototype.dispose = function () {
  64787. this._depthMap.dispose();
  64788. };
  64789. return DepthRenderer;
  64790. }());
  64791. BABYLON.DepthRenderer = DepthRenderer;
  64792. })(BABYLON || (BABYLON = {}));
  64793. //# sourceMappingURL=babylon.depthRenderer.js.map
  64794. var BABYLON;
  64795. (function (BABYLON) {
  64796. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64797. __extends(SSAORenderingPipeline, _super);
  64798. /**
  64799. * @constructor
  64800. * @param {string} name - The rendering pipeline name
  64801. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64802. * @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 }
  64803. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64804. */
  64805. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64806. var _this = _super.call(this, scene.getEngine(), name) || this;
  64807. // Members
  64808. /**
  64809. * The PassPostProcess id in the pipeline that contains the original scene color
  64810. * @type {string}
  64811. */
  64812. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64813. /**
  64814. * The SSAO PostProcess id in the pipeline
  64815. * @type {string}
  64816. */
  64817. _this.SSAORenderEffect = "SSAORenderEffect";
  64818. /**
  64819. * The horizontal blur PostProcess id in the pipeline
  64820. * @type {string}
  64821. */
  64822. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64823. /**
  64824. * The vertical blur PostProcess id in the pipeline
  64825. * @type {string}
  64826. */
  64827. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64828. /**
  64829. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64830. * @type {string}
  64831. */
  64832. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64833. /**
  64834. * The output strength of the SSAO post-process. Default value is 1.0.
  64835. * @type {number}
  64836. */
  64837. _this.totalStrength = 1.0;
  64838. /**
  64839. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64840. * @type {number}
  64841. */
  64842. _this.radius = 0.0001;
  64843. /**
  64844. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64845. * Must not be equal to fallOff and superior to fallOff.
  64846. * Default value is 0.975
  64847. * @type {number}
  64848. */
  64849. _this.area = 0.0075;
  64850. /**
  64851. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64852. * Must not be equal to area and inferior to area.
  64853. * Default value is 0.0
  64854. * @type {number}
  64855. */
  64856. _this.fallOff = 0.000001;
  64857. /**
  64858. * The base color of the SSAO post-process
  64859. * The final result is "base + ssao" between [0, 1]
  64860. * @type {number}
  64861. */
  64862. _this.base = 0.5;
  64863. _this._firstUpdate = true;
  64864. _this._scene = scene;
  64865. // Set up assets
  64866. _this._createRandomTexture();
  64867. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64868. var ssaoRatio = ratio.ssaoRatio || ratio;
  64869. var combineRatio = ratio.combineRatio || ratio;
  64870. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64871. _this._createSSAOPostProcess(ssaoRatio);
  64872. _this._createBlurPostProcess(ssaoRatio);
  64873. _this._createSSAOCombinePostProcess(combineRatio);
  64874. // Set up pipeline
  64875. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64876. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64877. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64878. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64879. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64880. // Finish
  64881. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64882. if (cameras)
  64883. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64884. return _this;
  64885. }
  64886. // Public Methods
  64887. /**
  64888. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64889. */
  64890. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64891. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64892. for (var i = 0; i < this._scene.cameras.length; i++) {
  64893. var camera = this._scene.cameras[i];
  64894. this._originalColorPostProcess.dispose(camera);
  64895. this._ssaoPostProcess.dispose(camera);
  64896. this._blurHPostProcess.dispose(camera);
  64897. this._blurVPostProcess.dispose(camera);
  64898. this._ssaoCombinePostProcess.dispose(camera);
  64899. }
  64900. this._randomTexture.dispose();
  64901. if (disableDepthRender)
  64902. this._scene.disableDepthRenderer();
  64903. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64904. _super.prototype.dispose.call(this);
  64905. };
  64906. // Private Methods
  64907. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64908. var _this = this;
  64909. var size = 16;
  64910. 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);
  64911. 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);
  64912. this._blurHPostProcess.onActivateObservable.add(function () {
  64913. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64914. _this._blurHPostProcess.kernel = size * dw;
  64915. });
  64916. this._blurVPostProcess.onActivateObservable.add(function () {
  64917. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64918. _this._blurVPostProcess.kernel = size * dw;
  64919. });
  64920. };
  64921. SSAORenderingPipeline.prototype._rebuild = function () {
  64922. this._firstUpdate = true;
  64923. _super.prototype._rebuild.call(this);
  64924. };
  64925. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64926. var _this = this;
  64927. var numSamples = 16;
  64928. var sampleSphere = [
  64929. 0.5381, 0.1856, -0.4319,
  64930. 0.1379, 0.2486, 0.4430,
  64931. 0.3371, 0.5679, -0.0057,
  64932. -0.6999, -0.0451, -0.0019,
  64933. 0.0689, -0.1598, -0.8547,
  64934. 0.0560, 0.0069, -0.1843,
  64935. -0.0146, 0.1402, 0.0762,
  64936. 0.0100, -0.1924, -0.0344,
  64937. -0.3577, -0.5301, -0.4358,
  64938. -0.3169, 0.1063, 0.0158,
  64939. 0.0103, -0.5869, 0.0046,
  64940. -0.0897, -0.4940, 0.3287,
  64941. 0.7119, -0.0154, -0.0918,
  64942. -0.0533, 0.0596, -0.5411,
  64943. 0.0352, -0.0631, 0.5460,
  64944. -0.4776, 0.2847, -0.0271
  64945. ];
  64946. var samplesFactor = 1.0 / numSamples;
  64947. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  64948. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64949. "area", "fallOff", "base", "range", "viewport"
  64950. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64951. this._ssaoPostProcess.onApply = function (effect) {
  64952. if (_this._firstUpdate) {
  64953. effect.setArray3("sampleSphere", sampleSphere);
  64954. effect.setFloat("samplesFactor", samplesFactor);
  64955. effect.setFloat("randTextureTiles", 4.0);
  64956. }
  64957. effect.setFloat("totalStrength", _this.totalStrength);
  64958. effect.setFloat("radius", _this.radius);
  64959. effect.setFloat("area", _this.area);
  64960. effect.setFloat("fallOff", _this.fallOff);
  64961. effect.setFloat("base", _this.base);
  64962. effect.setTexture("textureSampler", _this._depthTexture);
  64963. effect.setTexture("randomSampler", _this._randomTexture);
  64964. };
  64965. };
  64966. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64967. var _this = this;
  64968. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64969. this._ssaoCombinePostProcess.onApply = function (effect) {
  64970. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64971. };
  64972. };
  64973. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  64974. var size = 512;
  64975. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64976. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64977. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64978. var context = this._randomTexture.getContext();
  64979. var rand = function (min, max) {
  64980. return Math.random() * (max - min) + min;
  64981. };
  64982. var randVector = BABYLON.Vector3.Zero();
  64983. for (var x = 0; x < size; x++) {
  64984. for (var y = 0; y < size; y++) {
  64985. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  64986. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  64987. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  64988. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64989. context.fillRect(x, y, 1, 1);
  64990. }
  64991. }
  64992. this._randomTexture.update(false);
  64993. };
  64994. __decorate([
  64995. BABYLON.serialize()
  64996. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  64997. __decorate([
  64998. BABYLON.serialize()
  64999. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65000. __decorate([
  65001. BABYLON.serialize()
  65002. ], SSAORenderingPipeline.prototype, "area", void 0);
  65003. __decorate([
  65004. BABYLON.serialize()
  65005. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65006. __decorate([
  65007. BABYLON.serialize()
  65008. ], SSAORenderingPipeline.prototype, "base", void 0);
  65009. return SSAORenderingPipeline;
  65010. }(BABYLON.PostProcessRenderPipeline));
  65011. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65012. })(BABYLON || (BABYLON = {}));
  65013. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65014. var BABYLON;
  65015. (function (BABYLON) {
  65016. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65017. __extends(SSAO2RenderingPipeline, _super);
  65018. /**
  65019. * @constructor
  65020. * @param {string} name - The rendering pipeline name
  65021. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65022. * @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 }
  65023. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65024. */
  65025. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65026. var _this = _super.call(this, scene.getEngine(), name) || this;
  65027. // Members
  65028. /**
  65029. * The PassPostProcess id in the pipeline that contains the original scene color
  65030. * @type {string}
  65031. */
  65032. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65033. /**
  65034. * The SSAO PostProcess id in the pipeline
  65035. * @type {string}
  65036. */
  65037. _this.SSAORenderEffect = "SSAORenderEffect";
  65038. /**
  65039. * The horizontal blur PostProcess id in the pipeline
  65040. * @type {string}
  65041. */
  65042. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65043. /**
  65044. * The vertical blur PostProcess id in the pipeline
  65045. * @type {string}
  65046. */
  65047. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65048. /**
  65049. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65050. * @type {string}
  65051. */
  65052. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65053. /**
  65054. * The output strength of the SSAO post-process. Default value is 1.0.
  65055. * @type {number}
  65056. */
  65057. _this.totalStrength = 1.0;
  65058. /**
  65059. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  65060. * @type {number}
  65061. */
  65062. _this.maxZ = 100.0;
  65063. /**
  65064. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  65065. * @type {number}
  65066. */
  65067. _this.minZAspect = 0.2;
  65068. /**
  65069. * Number of samples used for the SSAO calculations. Default value is 8
  65070. * @type {number}
  65071. */
  65072. _this._samples = 8;
  65073. /**
  65074. * Are we using bilateral blur ?
  65075. * @type {boolean}
  65076. */
  65077. _this._expensiveBlur = true;
  65078. /**
  65079. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65080. * @type {number}
  65081. */
  65082. _this.radius = 2.0;
  65083. /**
  65084. * The base color of the SSAO post-process
  65085. * The final result is "base + ssao" between [0, 1]
  65086. * @type {number}
  65087. */
  65088. _this.base = 0.1;
  65089. _this._firstUpdate = true;
  65090. _this._scene = scene;
  65091. if (!_this.isSupported) {
  65092. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65093. return _this;
  65094. }
  65095. var ssaoRatio = ratio.ssaoRatio || ratio;
  65096. var blurRatio = ratio.blurRatio || ratio;
  65097. // Set up assets
  65098. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65099. _this._createRandomTexture();
  65100. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65101. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65102. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65103. _this._createSSAOPostProcess(1.0);
  65104. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65105. _this._createSSAOCombinePostProcess(blurRatio);
  65106. // Set up pipeline
  65107. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65108. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65109. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65110. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65111. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65112. // Finish
  65113. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65114. if (cameras)
  65115. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65116. return _this;
  65117. }
  65118. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65119. get: function () {
  65120. return this._samples;
  65121. },
  65122. set: function (n) {
  65123. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65124. this._samples = n;
  65125. this._sampleSphere = this._generateHemisphere();
  65126. this._firstUpdate = true;
  65127. },
  65128. enumerable: true,
  65129. configurable: true
  65130. });
  65131. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65132. get: function () {
  65133. return this._expensiveBlur;
  65134. },
  65135. set: function (b) {
  65136. 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"]);
  65137. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65138. this._expensiveBlur = b;
  65139. this._firstUpdate = true;
  65140. },
  65141. enumerable: true,
  65142. configurable: true
  65143. });
  65144. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65145. /**
  65146. * Support test.
  65147. * @type {boolean}
  65148. */
  65149. get: function () {
  65150. var engine = BABYLON.Engine.LastCreatedEngine;
  65151. if (!engine) {
  65152. return false;
  65153. }
  65154. return engine.getCaps().drawBuffersExtension;
  65155. },
  65156. enumerable: true,
  65157. configurable: true
  65158. });
  65159. // Public Methods
  65160. /**
  65161. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65162. */
  65163. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65164. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65165. for (var i = 0; i < this._scene.cameras.length; i++) {
  65166. var camera = this._scene.cameras[i];
  65167. this._originalColorPostProcess.dispose(camera);
  65168. this._ssaoPostProcess.dispose(camera);
  65169. this._blurHPostProcess.dispose(camera);
  65170. this._blurVPostProcess.dispose(camera);
  65171. this._ssaoCombinePostProcess.dispose(camera);
  65172. }
  65173. this._randomTexture.dispose();
  65174. if (disableGeometryBufferRenderer)
  65175. this._scene.disableGeometryBufferRenderer();
  65176. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65177. _super.prototype.dispose.call(this);
  65178. };
  65179. // Private Methods
  65180. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65181. var _this = this;
  65182. this._samplerOffsets = [];
  65183. var expensive = this.expensiveBlur;
  65184. for (var i = -8; i < 8; i++) {
  65185. this._samplerOffsets.push(i * 2 + 0.5);
  65186. }
  65187. 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");
  65188. this._blurHPostProcess.onApply = function (effect) {
  65189. if (!_this._scene.activeCamera) {
  65190. return;
  65191. }
  65192. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65193. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65194. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65195. effect.setFloat("radius", _this.radius);
  65196. effect.setTexture("depthSampler", _this._depthTexture);
  65197. if (_this._firstUpdate) {
  65198. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65199. }
  65200. };
  65201. 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");
  65202. this._blurVPostProcess.onApply = function (effect) {
  65203. if (!_this._scene.activeCamera) {
  65204. return;
  65205. }
  65206. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65207. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65208. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65209. effect.setFloat("radius", _this.radius);
  65210. effect.setTexture("depthSampler", _this._depthTexture);
  65211. if (_this._firstUpdate) {
  65212. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65213. _this._firstUpdate = false;
  65214. }
  65215. };
  65216. };
  65217. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65218. this._firstUpdate = true;
  65219. _super.prototype._rebuild.call(this);
  65220. };
  65221. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65222. var numSamples = this.samples;
  65223. var result = [];
  65224. var vector, scale;
  65225. var rand = function (min, max) {
  65226. return Math.random() * (max - min) + min;
  65227. };
  65228. var i = 0;
  65229. while (i < numSamples) {
  65230. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65231. vector.normalize();
  65232. scale = i / numSamples;
  65233. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65234. vector.scaleInPlace(scale);
  65235. result.push(vector.x, vector.y, vector.z);
  65236. i++;
  65237. }
  65238. return result;
  65239. };
  65240. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65241. var _this = this;
  65242. var numSamples = this.samples;
  65243. this._sampleSphere = this._generateHemisphere();
  65244. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65245. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65246. "base", "range", "projection", "near", "far", "texelSize",
  65247. "xViewport", "yViewport", "maxZ", "minZAspect"
  65248. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65249. this._ssaoPostProcess.onApply = function (effect) {
  65250. if (_this._firstUpdate) {
  65251. effect.setArray3("sampleSphere", _this._sampleSphere);
  65252. effect.setFloat("randTextureTiles", 4.0);
  65253. }
  65254. if (!_this._scene.activeCamera) {
  65255. return;
  65256. }
  65257. effect.setFloat("samplesFactor", 1 / _this.samples);
  65258. effect.setFloat("totalStrength", _this.totalStrength);
  65259. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65260. effect.setFloat("radius", _this.radius);
  65261. effect.setFloat("maxZ", _this.maxZ);
  65262. effect.setFloat("minZAspect", _this.minZAspect);
  65263. effect.setFloat("base", _this.base);
  65264. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65265. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65266. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65267. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65268. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65269. effect.setTexture("textureSampler", _this._depthTexture);
  65270. effect.setTexture("normalSampler", _this._normalTexture);
  65271. effect.setTexture("randomSampler", _this._randomTexture);
  65272. };
  65273. };
  65274. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65275. var _this = this;
  65276. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65277. this._ssaoCombinePostProcess.onApply = function (effect) {
  65278. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65279. };
  65280. };
  65281. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65282. var size = 512;
  65283. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65284. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65285. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65286. var context = this._randomTexture.getContext();
  65287. var rand = function (min, max) {
  65288. return Math.random() * (max - min) + min;
  65289. };
  65290. var randVector = BABYLON.Vector3.Zero();
  65291. for (var x = 0; x < size; x++) {
  65292. for (var y = 0; y < size; y++) {
  65293. randVector.x = rand(0.0, 1.0);
  65294. randVector.y = rand(0.0, 1.0);
  65295. randVector.z = 0.0;
  65296. randVector.normalize();
  65297. randVector.scaleInPlace(255);
  65298. randVector.x = Math.floor(randVector.x);
  65299. randVector.y = Math.floor(randVector.y);
  65300. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65301. context.fillRect(x, y, 1, 1);
  65302. }
  65303. }
  65304. this._randomTexture.update(false);
  65305. };
  65306. __decorate([
  65307. BABYLON.serialize()
  65308. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65309. __decorate([
  65310. BABYLON.serialize()
  65311. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65312. __decorate([
  65313. BABYLON.serialize()
  65314. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65315. __decorate([
  65316. BABYLON.serialize("samples")
  65317. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65318. __decorate([
  65319. BABYLON.serialize("expensiveBlur")
  65320. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65321. __decorate([
  65322. BABYLON.serialize()
  65323. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65324. __decorate([
  65325. BABYLON.serialize()
  65326. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65327. return SSAO2RenderingPipeline;
  65328. }(BABYLON.PostProcessRenderPipeline));
  65329. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65330. })(BABYLON || (BABYLON = {}));
  65331. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65332. // BABYLON.JS Chromatic Aberration GLSL Shader
  65333. // Author: Olivier Guyot
  65334. // Separates very slightly R, G and B colors on the edges of the screen
  65335. // Inspired by Francois Tarlier & Martins Upitis
  65336. var BABYLON;
  65337. (function (BABYLON) {
  65338. var LensRenderingPipeline = /** @class */ (function (_super) {
  65339. __extends(LensRenderingPipeline, _super);
  65340. /**
  65341. * @constructor
  65342. *
  65343. * Effect parameters are as follow:
  65344. * {
  65345. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65346. * edge_blur: number; // from 0 to x (1 for realism)
  65347. * distortion: number; // from 0 to x (1 for realism)
  65348. * grain_amount: number; // from 0 to 1
  65349. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65350. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65351. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65352. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65353. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65354. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65355. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65356. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65357. * }
  65358. * Note: if an effect parameter is unset, effect is disabled
  65359. *
  65360. * @param {string} name - The rendering pipeline name
  65361. * @param {object} parameters - An object containing all parameters (see above)
  65362. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65363. * @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)
  65364. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65365. */
  65366. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65367. if (ratio === void 0) { ratio = 1.0; }
  65368. var _this = _super.call(this, scene.getEngine(), name) || this;
  65369. // Lens effects can be of the following:
  65370. // - chromatic aberration (slight shift of RGB colors)
  65371. // - blur on the edge of the lens
  65372. // - lens distortion
  65373. // - depth-of-field blur & highlights enhancing
  65374. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65375. // - grain effect (noise or custom texture)
  65376. // Two additional texture samplers are needed:
  65377. // - depth map (for depth-of-field)
  65378. // - grain texture
  65379. /**
  65380. * The chromatic aberration PostProcess id in the pipeline
  65381. * @type {string}
  65382. */
  65383. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65384. /**
  65385. * The highlights enhancing PostProcess id in the pipeline
  65386. * @type {string}
  65387. */
  65388. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65389. /**
  65390. * The depth-of-field PostProcess id in the pipeline
  65391. * @type {string}
  65392. */
  65393. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65394. _this._scene = scene;
  65395. // Fetch texture samplers
  65396. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65397. if (parameters.grain_texture) {
  65398. _this._grainTexture = parameters.grain_texture;
  65399. }
  65400. else {
  65401. _this._createGrainTexture();
  65402. }
  65403. // save parameters
  65404. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65405. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65406. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65407. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65408. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65409. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65410. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65411. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65412. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65413. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65414. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65415. // Create effects
  65416. _this._createChromaticAberrationPostProcess(ratio);
  65417. _this._createHighlightsPostProcess(ratio);
  65418. _this._createDepthOfFieldPostProcess(ratio / 4);
  65419. // Set up pipeline
  65420. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65421. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65422. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65423. if (_this._highlightsGain === -1) {
  65424. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65425. }
  65426. // Finish
  65427. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65428. if (cameras) {
  65429. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65430. }
  65431. return _this;
  65432. }
  65433. // public methods (self explanatory)
  65434. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65435. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65436. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65437. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65438. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65439. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65440. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65441. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65442. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65443. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65444. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65445. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65446. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65447. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65448. };
  65449. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65450. this._highlightsPostProcess.updateEffect();
  65451. };
  65452. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65453. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65454. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65455. this._highlightsGain = amount;
  65456. };
  65457. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65458. if (this._highlightsGain === -1) {
  65459. this._highlightsGain = 1.0;
  65460. }
  65461. this._highlightsThreshold = amount;
  65462. };
  65463. LensRenderingPipeline.prototype.disableHighlights = function () {
  65464. this._highlightsGain = -1;
  65465. };
  65466. /**
  65467. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65468. */
  65469. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65470. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65471. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65472. this._chromaticAberrationPostProcess = null;
  65473. this._highlightsPostProcess = null;
  65474. this._depthOfFieldPostProcess = null;
  65475. this._grainTexture.dispose();
  65476. if (disableDepthRender)
  65477. this._scene.disableDepthRenderer();
  65478. };
  65479. // colors shifting and distortion
  65480. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65481. var _this = this;
  65482. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65483. [], // samplers
  65484. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65485. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65486. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65487. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65488. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65489. };
  65490. };
  65491. // highlights enhancing
  65492. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65493. var _this = this;
  65494. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65495. [], // samplers
  65496. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65497. this._highlightsPostProcess.onApply = function (effect) {
  65498. effect.setFloat('gain', _this._highlightsGain);
  65499. effect.setFloat('threshold', _this._highlightsThreshold);
  65500. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65501. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65502. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65503. };
  65504. };
  65505. // colors shifting and distortion
  65506. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65507. var _this = this;
  65508. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65509. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65510. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65511. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65512. this._depthOfFieldPostProcess.onApply = function (effect) {
  65513. effect.setTexture("depthSampler", _this._depthTexture);
  65514. effect.setTexture("grainSampler", _this._grainTexture);
  65515. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65516. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65517. effect.setFloat('grain_amount', _this._grainAmount);
  65518. effect.setBool('blur_noise', _this._blurNoise);
  65519. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65520. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65521. effect.setFloat('distortion', _this._distortion);
  65522. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65523. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65524. effect.setFloat('aperture', _this._dofAperture);
  65525. effect.setFloat('darken', _this._dofDarken);
  65526. effect.setFloat('edge_blur', _this._edgeBlur);
  65527. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65528. if (_this._scene.activeCamera) {
  65529. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65530. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65531. }
  65532. };
  65533. };
  65534. // creates a black and white random noise texture, 512x512
  65535. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65536. var size = 512;
  65537. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65538. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65539. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65540. var context = this._grainTexture.getContext();
  65541. var rand = function (min, max) {
  65542. return Math.random() * (max - min) + min;
  65543. };
  65544. var value;
  65545. for (var x = 0; x < size; x++) {
  65546. for (var y = 0; y < size; y++) {
  65547. value = Math.floor(rand(0.42, 0.58) * 255);
  65548. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65549. context.fillRect(x, y, 1, 1);
  65550. }
  65551. }
  65552. this._grainTexture.update(false);
  65553. };
  65554. return LensRenderingPipeline;
  65555. }(BABYLON.PostProcessRenderPipeline));
  65556. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65557. })(BABYLON || (BABYLON = {}));
  65558. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65559. var BABYLON;
  65560. (function (BABYLON) {
  65561. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65562. __extends(StandardRenderingPipeline, _super);
  65563. /**
  65564. * @constructor
  65565. * @param {string} name - The rendering pipeline name
  65566. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65567. * @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)
  65568. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65569. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65570. */
  65571. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65572. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65573. var _this = _super.call(this, scene.getEngine(), name) || this;
  65574. _this.downSampleX4PostProcess = null;
  65575. _this.brightPassPostProcess = null;
  65576. _this.blurHPostProcesses = [];
  65577. _this.blurVPostProcesses = [];
  65578. _this.textureAdderPostProcess = null;
  65579. _this.volumetricLightPostProcess = null;
  65580. _this.volumetricLightSmoothXPostProcess = null;
  65581. _this.volumetricLightSmoothYPostProcess = null;
  65582. _this.volumetricLightMergePostProces = null;
  65583. _this.volumetricLightFinalPostProcess = null;
  65584. _this.luminancePostProcess = null;
  65585. _this.luminanceDownSamplePostProcesses = [];
  65586. _this.hdrPostProcess = null;
  65587. _this.textureAdderFinalPostProcess = null;
  65588. _this.lensFlareFinalPostProcess = null;
  65589. _this.hdrFinalPostProcess = null;
  65590. _this.lensFlarePostProcess = null;
  65591. _this.lensFlareComposePostProcess = null;
  65592. _this.motionBlurPostProcess = null;
  65593. _this.depthOfFieldPostProcess = null;
  65594. // Values
  65595. _this.brightThreshold = 1.0;
  65596. _this.blurWidth = 512.0;
  65597. _this.horizontalBlur = false;
  65598. _this.exposure = 1.0;
  65599. _this.lensTexture = null;
  65600. _this.volumetricLightCoefficient = 0.2;
  65601. _this.volumetricLightPower = 4.0;
  65602. _this.volumetricLightBlurScale = 64.0;
  65603. _this.sourceLight = null;
  65604. _this.hdrMinimumLuminance = 1.0;
  65605. _this.hdrDecreaseRate = 0.5;
  65606. _this.hdrIncreaseRate = 0.5;
  65607. _this.lensColorTexture = null;
  65608. _this.lensFlareStrength = 20.0;
  65609. _this.lensFlareGhostDispersal = 1.4;
  65610. _this.lensFlareHaloWidth = 0.7;
  65611. _this.lensFlareDistortionStrength = 16.0;
  65612. _this.lensStarTexture = null;
  65613. _this.lensFlareDirtTexture = null;
  65614. _this.depthOfFieldDistance = 10.0;
  65615. _this.depthOfFieldBlurWidth = 64.0;
  65616. _this.motionStrength = 1.0;
  65617. // IAnimatable
  65618. _this.animations = [];
  65619. _this._currentDepthOfFieldSource = null;
  65620. _this._hdrCurrentLuminance = 1.0;
  65621. // Getters and setters
  65622. _this._bloomEnabled = true;
  65623. _this._depthOfFieldEnabled = false;
  65624. _this._vlsEnabled = false;
  65625. _this._lensFlareEnabled = false;
  65626. _this._hdrEnabled = false;
  65627. _this._motionBlurEnabled = false;
  65628. _this._motionBlurSamples = 64.0;
  65629. _this._volumetricLightStepsCount = 50.0;
  65630. _this._cameras = cameras || [];
  65631. // Initialize
  65632. _this._scene = scene;
  65633. _this._basePostProcess = originalPostProcess;
  65634. _this._ratio = ratio;
  65635. // Misc
  65636. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65637. // Finish
  65638. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65639. _this._buildPipeline();
  65640. return _this;
  65641. }
  65642. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65643. get: function () {
  65644. return this._bloomEnabled;
  65645. },
  65646. set: function (enabled) {
  65647. if (this._bloomEnabled === enabled) {
  65648. return;
  65649. }
  65650. this._bloomEnabled = enabled;
  65651. this._buildPipeline();
  65652. },
  65653. enumerable: true,
  65654. configurable: true
  65655. });
  65656. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65657. get: function () {
  65658. return this._depthOfFieldEnabled;
  65659. },
  65660. set: function (enabled) {
  65661. if (this._depthOfFieldEnabled === enabled) {
  65662. return;
  65663. }
  65664. this._depthOfFieldEnabled = enabled;
  65665. this._buildPipeline();
  65666. },
  65667. enumerable: true,
  65668. configurable: true
  65669. });
  65670. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65671. get: function () {
  65672. return this._lensFlareEnabled;
  65673. },
  65674. set: function (enabled) {
  65675. if (this._lensFlareEnabled === enabled) {
  65676. return;
  65677. }
  65678. this._lensFlareEnabled = enabled;
  65679. this._buildPipeline();
  65680. },
  65681. enumerable: true,
  65682. configurable: true
  65683. });
  65684. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65685. get: function () {
  65686. return this._hdrEnabled;
  65687. },
  65688. set: function (enabled) {
  65689. if (this._hdrEnabled === enabled) {
  65690. return;
  65691. }
  65692. this._hdrEnabled = enabled;
  65693. this._buildPipeline();
  65694. },
  65695. enumerable: true,
  65696. configurable: true
  65697. });
  65698. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65699. get: function () {
  65700. return this._vlsEnabled;
  65701. },
  65702. set: function (enabled) {
  65703. if (this._vlsEnabled === enabled) {
  65704. return;
  65705. }
  65706. if (enabled) {
  65707. var geometry = this._scene.enableGeometryBufferRenderer();
  65708. if (!geometry) {
  65709. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65710. return;
  65711. }
  65712. }
  65713. this._vlsEnabled = enabled;
  65714. this._buildPipeline();
  65715. },
  65716. enumerable: true,
  65717. configurable: true
  65718. });
  65719. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65720. get: function () {
  65721. return this._motionBlurEnabled;
  65722. },
  65723. set: function (enabled) {
  65724. if (this._motionBlurEnabled === enabled) {
  65725. return;
  65726. }
  65727. this._motionBlurEnabled = enabled;
  65728. this._buildPipeline();
  65729. },
  65730. enumerable: true,
  65731. configurable: true
  65732. });
  65733. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65734. get: function () {
  65735. return this._volumetricLightStepsCount;
  65736. },
  65737. set: function (count) {
  65738. if (this.volumetricLightPostProcess) {
  65739. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65740. }
  65741. this._volumetricLightStepsCount = count;
  65742. },
  65743. enumerable: true,
  65744. configurable: true
  65745. });
  65746. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65747. get: function () {
  65748. return this._motionBlurSamples;
  65749. },
  65750. set: function (samples) {
  65751. if (this.motionBlurPostProcess) {
  65752. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65753. }
  65754. this._motionBlurSamples = samples;
  65755. },
  65756. enumerable: true,
  65757. configurable: true
  65758. });
  65759. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65760. var _this = this;
  65761. var ratio = this._ratio;
  65762. var scene = this._scene;
  65763. this._disposePostProcesses();
  65764. this._reset();
  65765. // Create pass post-process
  65766. if (!this._basePostProcess) {
  65767. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65768. this.originalPostProcess.onApply = function (effect) {
  65769. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65770. };
  65771. }
  65772. else {
  65773. this.originalPostProcess = this._basePostProcess;
  65774. }
  65775. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65776. this._currentDepthOfFieldSource = this.originalPostProcess;
  65777. if (this._vlsEnabled) {
  65778. // Create volumetric light
  65779. this._createVolumetricLightPostProcess(scene, ratio);
  65780. // Create volumetric light final post-process
  65781. 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);
  65782. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65783. }
  65784. if (this._bloomEnabled) {
  65785. // Create down sample X4 post-process
  65786. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65787. // Create bright pass post-process
  65788. this._createBrightPassPostProcess(scene, ratio / 2);
  65789. // Create gaussian blur post-processes (down sampling blurs)
  65790. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65791. // Create texture adder post-process
  65792. this._createTextureAdderPostProcess(scene, ratio);
  65793. // Create depth-of-field source post-process
  65794. 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);
  65795. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65796. }
  65797. if (this._lensFlareEnabled) {
  65798. // Create lens flare post-process
  65799. this._createLensFlarePostProcess(scene, ratio);
  65800. // Create depth-of-field source post-process post lens-flare and disable it now
  65801. 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);
  65802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65803. }
  65804. if (this._hdrEnabled) {
  65805. // Create luminance
  65806. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65807. // Create HDR
  65808. this._createHdrPostProcess(scene, ratio);
  65809. // Create depth-of-field source post-process post hdr and disable it now
  65810. 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);
  65811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65812. }
  65813. if (this._depthOfFieldEnabled) {
  65814. // Create gaussian blur used by depth-of-field
  65815. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65816. // Create depth-of-field post-process
  65817. this._createDepthOfFieldPostProcess(scene, ratio);
  65818. }
  65819. if (this._motionBlurEnabled) {
  65820. // Create motion blur post-process
  65821. this._createMotionBlurPostProcess(scene, ratio);
  65822. }
  65823. if (this._cameras !== null) {
  65824. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65825. }
  65826. };
  65827. // Down Sample X4 Post-Processs
  65828. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65829. var _this = this;
  65830. var downSampleX4Offsets = new Array(32);
  65831. 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);
  65832. this.downSampleX4PostProcess.onApply = function (effect) {
  65833. var id = 0;
  65834. var width = _this.downSampleX4PostProcess.width;
  65835. var height = _this.downSampleX4PostProcess.height;
  65836. for (var i = -2; i < 2; i++) {
  65837. for (var j = -2; j < 2; j++) {
  65838. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65839. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65840. id += 2;
  65841. }
  65842. }
  65843. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65844. };
  65845. // Add to pipeline
  65846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65847. };
  65848. // Brightpass Post-Process
  65849. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65850. var _this = this;
  65851. var brightOffsets = new Array(8);
  65852. 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);
  65853. this.brightPassPostProcess.onApply = function (effect) {
  65854. var sU = (1.0 / _this.brightPassPostProcess.width);
  65855. var sV = (1.0 / _this.brightPassPostProcess.height);
  65856. brightOffsets[0] = -0.5 * sU;
  65857. brightOffsets[1] = 0.5 * sV;
  65858. brightOffsets[2] = 0.5 * sU;
  65859. brightOffsets[3] = 0.5 * sV;
  65860. brightOffsets[4] = -0.5 * sU;
  65861. brightOffsets[5] = -0.5 * sV;
  65862. brightOffsets[6] = 0.5 * sU;
  65863. brightOffsets[7] = -0.5 * sV;
  65864. effect.setArray2("dsOffsets", brightOffsets);
  65865. effect.setFloat("brightThreshold", _this.brightThreshold);
  65866. };
  65867. // Add to pipeline
  65868. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65869. };
  65870. // Create blur H&V post-processes
  65871. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65872. var _this = this;
  65873. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65874. var engine = scene.getEngine();
  65875. 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);
  65876. 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);
  65877. blurX.onActivateObservable.add(function () {
  65878. var dw = blurX.width / engine.getRenderWidth();
  65879. blurX.kernel = _this[blurWidthKey] * dw;
  65880. });
  65881. blurY.onActivateObservable.add(function () {
  65882. var dw = blurY.height / engine.getRenderHeight();
  65883. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65884. });
  65885. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65886. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65887. this.blurHPostProcesses.push(blurX);
  65888. this.blurVPostProcesses.push(blurY);
  65889. };
  65890. // Create texture adder post-process
  65891. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65892. var _this = this;
  65893. 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);
  65894. this.textureAdderPostProcess.onApply = function (effect) {
  65895. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65896. effect.setTexture("lensSampler", _this.lensTexture);
  65897. effect.setFloat("exposure", _this.exposure);
  65898. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65899. };
  65900. // Add to pipeline
  65901. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65902. };
  65903. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65904. var _this = this;
  65905. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65906. geometryRenderer.enablePosition = true;
  65907. var geometry = geometryRenderer.getGBuffer();
  65908. // Base post-process
  65909. 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));
  65910. var depthValues = BABYLON.Vector2.Zero();
  65911. this.volumetricLightPostProcess.onApply = function (effect) {
  65912. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65913. var generator = _this.sourceLight.getShadowGenerator();
  65914. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65915. effect.setTexture("positionSampler", geometry.textures[2]);
  65916. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65917. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65918. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65919. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65920. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65921. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65922. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65923. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65924. effect.setVector2("depthValues", depthValues);
  65925. }
  65926. };
  65927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65928. // Smooth
  65929. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65930. // Merge
  65931. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65932. this.volumetricLightMergePostProces.onApply = function (effect) {
  65933. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65934. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65935. };
  65936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  65937. };
  65938. // Create luminance
  65939. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  65940. var _this = this;
  65941. // Create luminance
  65942. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  65943. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  65944. var offsets = [];
  65945. this.luminancePostProcess.onApply = function (effect) {
  65946. var sU = (1.0 / _this.luminancePostProcess.width);
  65947. var sV = (1.0 / _this.luminancePostProcess.height);
  65948. offsets[0] = -0.5 * sU;
  65949. offsets[1] = 0.5 * sV;
  65950. offsets[2] = 0.5 * sU;
  65951. offsets[3] = 0.5 * sV;
  65952. offsets[4] = -0.5 * sU;
  65953. offsets[5] = -0.5 * sV;
  65954. offsets[6] = 0.5 * sU;
  65955. offsets[7] = -0.5 * sV;
  65956. effect.setArray2("lumOffsets", offsets);
  65957. };
  65958. // Add to pipeline
  65959. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  65960. // Create down sample luminance
  65961. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  65962. var size = Math.pow(3, i);
  65963. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  65964. if (i === 0) {
  65965. defines += "#define FINAL_DOWN_SAMPLER";
  65966. }
  65967. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  65968. this.luminanceDownSamplePostProcesses.push(postProcess);
  65969. }
  65970. // Create callbacks and add effects
  65971. var lastLuminance = this.luminancePostProcess;
  65972. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  65973. var downSampleOffsets = new Array(18);
  65974. pp.onApply = function (effect) {
  65975. if (!lastLuminance) {
  65976. return;
  65977. }
  65978. var id = 0;
  65979. for (var x = -1; x < 2; x++) {
  65980. for (var y = -1; y < 2; y++) {
  65981. downSampleOffsets[id] = x / lastLuminance.width;
  65982. downSampleOffsets[id + 1] = y / lastLuminance.height;
  65983. id += 2;
  65984. }
  65985. }
  65986. effect.setArray2("dsOffsets", downSampleOffsets);
  65987. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  65988. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65989. lastLuminance = _this.luminancePostProcess;
  65990. }
  65991. else {
  65992. lastLuminance = pp;
  65993. }
  65994. };
  65995. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65996. pp.onAfterRender = function (effect) {
  65997. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  65998. 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);
  65999. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66000. };
  66001. }
  66002. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66003. });
  66004. };
  66005. // Create HDR post-process
  66006. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66007. var _this = this;
  66008. 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);
  66009. var outputLiminance = 1;
  66010. var time = 0;
  66011. var lastTime = 0;
  66012. this.hdrPostProcess.onApply = function (effect) {
  66013. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66014. time += scene.getEngine().getDeltaTime();
  66015. if (outputLiminance < 0) {
  66016. outputLiminance = _this._hdrCurrentLuminance;
  66017. }
  66018. else {
  66019. var dt = (lastTime - time) / 1000.0;
  66020. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66021. outputLiminance += _this.hdrDecreaseRate * dt;
  66022. }
  66023. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66024. outputLiminance -= _this.hdrIncreaseRate * dt;
  66025. }
  66026. else {
  66027. outputLiminance = _this._hdrCurrentLuminance;
  66028. }
  66029. }
  66030. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  66031. effect.setFloat("averageLuminance", outputLiminance);
  66032. lastTime = time;
  66033. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  66034. };
  66035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  66036. };
  66037. // Create lens flare post-process
  66038. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  66039. var _this = this;
  66040. 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);
  66041. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  66042. this._createBlurPostProcesses(scene, ratio / 4, 2);
  66043. 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);
  66044. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  66045. var resolution = new BABYLON.Vector2(0, 0);
  66046. // Lens flare
  66047. this.lensFlarePostProcess.onApply = function (effect) {
  66048. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  66049. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  66050. effect.setFloat("strength", _this.lensFlareStrength);
  66051. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  66052. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  66053. // Shift
  66054. resolution.x = _this.lensFlarePostProcess.width;
  66055. resolution.y = _this.lensFlarePostProcess.height;
  66056. effect.setVector2("resolution", resolution);
  66057. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  66058. };
  66059. // Compose
  66060. 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);
  66061. 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);
  66062. this.lensFlareComposePostProcess.onApply = function (effect) {
  66063. if (!_this._scene.activeCamera) {
  66064. return;
  66065. }
  66066. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66067. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66068. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66069. // Lens start rotation matrix
  66070. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66071. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66072. 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));
  66073. camRot *= 4.0;
  66074. 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);
  66075. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66076. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66077. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66078. };
  66079. };
  66080. // Create depth-of-field post-process
  66081. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66082. var _this = this;
  66083. 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);
  66084. this.depthOfFieldPostProcess.onApply = function (effect) {
  66085. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66086. effect.setTexture("depthSampler", _this._getDepthTexture());
  66087. effect.setFloat("distance", _this.depthOfFieldDistance);
  66088. };
  66089. // Add to pipeline
  66090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66091. };
  66092. // Create motion blur post-process
  66093. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66094. var _this = this;
  66095. 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);
  66096. var motionScale = 0;
  66097. var prevViewProjection = BABYLON.Matrix.Identity();
  66098. var invViewProjection = BABYLON.Matrix.Identity();
  66099. var viewProjection = BABYLON.Matrix.Identity();
  66100. var screenSize = BABYLON.Vector2.Zero();
  66101. this.motionBlurPostProcess.onApply = function (effect) {
  66102. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66103. viewProjection.invertToRef(invViewProjection);
  66104. effect.setMatrix("inverseViewProjection", invViewProjection);
  66105. effect.setMatrix("prevViewProjection", prevViewProjection);
  66106. prevViewProjection = viewProjection;
  66107. screenSize.x = _this.motionBlurPostProcess.width;
  66108. screenSize.y = _this.motionBlurPostProcess.height;
  66109. effect.setVector2("screenSize", screenSize);
  66110. motionScale = scene.getEngine().getFps() / 60.0;
  66111. effect.setFloat("motionScale", motionScale);
  66112. effect.setFloat("motionStrength", _this.motionStrength);
  66113. effect.setTexture("depthSampler", _this._getDepthTexture());
  66114. };
  66115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66116. };
  66117. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66118. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66119. var renderer = this._scene.enableGeometryBufferRenderer();
  66120. return renderer.getGBuffer().textures[0];
  66121. }
  66122. return this._scene.enableDepthRenderer().getDepthMap();
  66123. };
  66124. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66125. for (var i = 0; i < this._cameras.length; i++) {
  66126. var camera = this._cameras[i];
  66127. if (this.originalPostProcess) {
  66128. this.originalPostProcess.dispose(camera);
  66129. }
  66130. if (this.downSampleX4PostProcess) {
  66131. this.downSampleX4PostProcess.dispose(camera);
  66132. }
  66133. if (this.brightPassPostProcess) {
  66134. this.brightPassPostProcess.dispose(camera);
  66135. }
  66136. if (this.textureAdderPostProcess) {
  66137. this.textureAdderPostProcess.dispose(camera);
  66138. }
  66139. if (this.textureAdderFinalPostProcess) {
  66140. this.textureAdderFinalPostProcess.dispose(camera);
  66141. }
  66142. if (this.volumetricLightPostProcess) {
  66143. this.volumetricLightPostProcess.dispose(camera);
  66144. }
  66145. if (this.volumetricLightSmoothXPostProcess) {
  66146. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66147. }
  66148. if (this.volumetricLightSmoothYPostProcess) {
  66149. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66150. }
  66151. if (this.volumetricLightMergePostProces) {
  66152. this.volumetricLightMergePostProces.dispose(camera);
  66153. }
  66154. if (this.volumetricLightFinalPostProcess) {
  66155. this.volumetricLightFinalPostProcess.dispose(camera);
  66156. }
  66157. if (this.lensFlarePostProcess) {
  66158. this.lensFlarePostProcess.dispose(camera);
  66159. }
  66160. if (this.lensFlareComposePostProcess) {
  66161. this.lensFlareComposePostProcess.dispose(camera);
  66162. }
  66163. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66164. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66165. }
  66166. if (this.luminancePostProcess) {
  66167. this.luminancePostProcess.dispose(camera);
  66168. }
  66169. if (this.hdrPostProcess) {
  66170. this.hdrPostProcess.dispose(camera);
  66171. }
  66172. if (this.hdrFinalPostProcess) {
  66173. this.hdrFinalPostProcess.dispose(camera);
  66174. }
  66175. if (this.depthOfFieldPostProcess) {
  66176. this.depthOfFieldPostProcess.dispose(camera);
  66177. }
  66178. if (this.motionBlurPostProcess) {
  66179. this.motionBlurPostProcess.dispose(camera);
  66180. }
  66181. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66182. this.blurHPostProcesses[j].dispose(camera);
  66183. }
  66184. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66185. this.blurVPostProcesses[j].dispose(camera);
  66186. }
  66187. }
  66188. this.originalPostProcess = null;
  66189. this.downSampleX4PostProcess = null;
  66190. this.brightPassPostProcess = null;
  66191. this.textureAdderPostProcess = null;
  66192. this.textureAdderFinalPostProcess = null;
  66193. this.volumetricLightPostProcess = null;
  66194. this.volumetricLightSmoothXPostProcess = null;
  66195. this.volumetricLightSmoothYPostProcess = null;
  66196. this.volumetricLightMergePostProces = null;
  66197. this.volumetricLightFinalPostProcess = null;
  66198. this.lensFlarePostProcess = null;
  66199. this.lensFlareComposePostProcess = null;
  66200. this.luminancePostProcess = null;
  66201. this.hdrPostProcess = null;
  66202. this.hdrFinalPostProcess = null;
  66203. this.depthOfFieldPostProcess = null;
  66204. this.motionBlurPostProcess = null;
  66205. this.luminanceDownSamplePostProcesses = [];
  66206. this.blurHPostProcesses = [];
  66207. this.blurVPostProcesses = [];
  66208. };
  66209. // Dispose
  66210. StandardRenderingPipeline.prototype.dispose = function () {
  66211. this._disposePostProcesses();
  66212. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66213. _super.prototype.dispose.call(this);
  66214. };
  66215. // Serialize rendering pipeline
  66216. StandardRenderingPipeline.prototype.serialize = function () {
  66217. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66218. serializationObject.customType = "StandardRenderingPipeline";
  66219. return serializationObject;
  66220. };
  66221. /**
  66222. * Static members
  66223. */
  66224. // Parse serialized pipeline
  66225. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66226. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66227. };
  66228. // Luminance steps
  66229. StandardRenderingPipeline.LuminanceSteps = 6;
  66230. __decorate([
  66231. BABYLON.serialize()
  66232. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66233. __decorate([
  66234. BABYLON.serialize()
  66235. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66236. __decorate([
  66237. BABYLON.serialize()
  66238. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66239. __decorate([
  66240. BABYLON.serialize()
  66241. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66242. __decorate([
  66243. BABYLON.serializeAsTexture("lensTexture")
  66244. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66245. __decorate([
  66246. BABYLON.serialize()
  66247. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66248. __decorate([
  66249. BABYLON.serialize()
  66250. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66251. __decorate([
  66252. BABYLON.serialize()
  66253. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66254. __decorate([
  66255. BABYLON.serialize()
  66256. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66257. __decorate([
  66258. BABYLON.serialize()
  66259. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66260. __decorate([
  66261. BABYLON.serialize()
  66262. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66263. __decorate([
  66264. BABYLON.serializeAsTexture("lensColorTexture")
  66265. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66266. __decorate([
  66267. BABYLON.serialize()
  66268. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66269. __decorate([
  66270. BABYLON.serialize()
  66271. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66272. __decorate([
  66273. BABYLON.serialize()
  66274. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66275. __decorate([
  66276. BABYLON.serialize()
  66277. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66278. __decorate([
  66279. BABYLON.serializeAsTexture("lensStarTexture")
  66280. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66281. __decorate([
  66282. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66283. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66284. __decorate([
  66285. BABYLON.serialize()
  66286. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66287. __decorate([
  66288. BABYLON.serialize()
  66289. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66290. __decorate([
  66291. BABYLON.serialize()
  66292. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66293. __decorate([
  66294. BABYLON.serialize()
  66295. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66296. __decorate([
  66297. BABYLON.serialize()
  66298. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66299. __decorate([
  66300. BABYLON.serialize()
  66301. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66302. __decorate([
  66303. BABYLON.serialize()
  66304. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66305. __decorate([
  66306. BABYLON.serialize()
  66307. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66308. __decorate([
  66309. BABYLON.serialize()
  66310. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66311. __decorate([
  66312. BABYLON.serialize()
  66313. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66314. __decorate([
  66315. BABYLON.serialize()
  66316. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66317. __decorate([
  66318. BABYLON.serialize()
  66319. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66320. return StandardRenderingPipeline;
  66321. }(BABYLON.PostProcessRenderPipeline));
  66322. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66323. })(BABYLON || (BABYLON = {}));
  66324. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66325. var BABYLON;
  66326. (function (BABYLON) {
  66327. var FxaaPostProcess = /** @class */ (function (_super) {
  66328. __extends(FxaaPostProcess, _super);
  66329. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66330. if (camera === void 0) { camera = null; }
  66331. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66332. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66333. _this.onApplyObservable.add(function (effect) {
  66334. var texelSize = _this.texelSize;
  66335. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66336. });
  66337. return _this;
  66338. }
  66339. return FxaaPostProcess;
  66340. }(BABYLON.PostProcess));
  66341. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66342. })(BABYLON || (BABYLON = {}));
  66343. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66344. var BABYLON;
  66345. (function (BABYLON) {
  66346. /**
  66347. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66348. */
  66349. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66350. __extends(CircleOfConfusionPostProcess, _super);
  66351. /**
  66352. * Creates a new instance of @see CircleOfConfusionPostProcess
  66353. * @param name The name of the effect.
  66354. * @param scene The scene the effect belongs to.
  66355. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66356. * @param options The required width/height ratio to downsize to before computing the render pass.
  66357. * @param camera The camera to apply the render pass to.
  66358. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66359. * @param engine The engine which the post process will be applied. (default: current engine)
  66360. * @param reusable If the post process can be reused on the same frame. (default: false)
  66361. * @param textureType Type of textures used when performing the post process. (default: 0)
  66362. */
  66363. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66364. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66365. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66366. /**
  66367. * 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.
  66368. */
  66369. _this.lensSize = 50;
  66370. /**
  66371. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66372. */
  66373. _this.fStop = 1.4;
  66374. /**
  66375. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66376. */
  66377. _this.focusDistance = 2000;
  66378. /**
  66379. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66380. */
  66381. _this.focalLength = 50;
  66382. _this.onApplyObservable.add(function (effect) {
  66383. effect.setTexture("depthSampler", depthTexture);
  66384. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66385. var aperture = _this.lensSize / _this.fStop;
  66386. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66387. effect.setFloat('focusDistance', _this.focusDistance);
  66388. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66389. if (scene.activeCamera) {
  66390. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66391. }
  66392. });
  66393. return _this;
  66394. }
  66395. return CircleOfConfusionPostProcess;
  66396. }(BABYLON.PostProcess));
  66397. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66398. })(BABYLON || (BABYLON = {}));
  66399. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66400. var BABYLON;
  66401. (function (BABYLON) {
  66402. /**
  66403. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66404. */
  66405. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66406. __extends(DepthOfFieldMergePostProcess, _super);
  66407. /**
  66408. * Creates a new instance of @see CircleOfConfusionPostProcess
  66409. * @param name The name of the effect.
  66410. * @param original The non-blurred image to be modified
  66411. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66412. * @param blurSteps Incrimental bluring post processes.
  66413. * @param options The required width/height ratio to downsize to before computing the render pass.
  66414. * @param camera The camera to apply the render pass to.
  66415. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66416. * @param engine The engine which the post process will be applied. (default: current engine)
  66417. * @param reusable If the post process can be reused on the same frame. (default: false)
  66418. * @param textureType Type of textures used when performing the post process. (default: 0)
  66419. */
  66420. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66421. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66422. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66423. _this.onApplyObservable.add(function (effect) {
  66424. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66425. effect.setTextureFromPostProcess("originalSampler", original);
  66426. blurSteps.forEach(function (step, index) {
  66427. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66428. });
  66429. });
  66430. return _this;
  66431. }
  66432. return DepthOfFieldMergePostProcess;
  66433. }(BABYLON.PostProcess));
  66434. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66435. })(BABYLON || (BABYLON = {}));
  66436. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66437. var BABYLON;
  66438. (function (BABYLON) {
  66439. /**
  66440. * Specifies the level of max blur that should be applied when using the depth of field effect
  66441. */
  66442. var DepthOfFieldEffectBlurLevel;
  66443. (function (DepthOfFieldEffectBlurLevel) {
  66444. /**
  66445. * Subtle blur
  66446. */
  66447. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66448. /**
  66449. * Medium blur
  66450. */
  66451. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66452. /**
  66453. * Large blur
  66454. */
  66455. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66456. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66457. ;
  66458. /**
  66459. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66460. */
  66461. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66462. __extends(DepthOfFieldEffect, _super);
  66463. /**
  66464. * Creates a new instance of @see DepthOfFieldEffect
  66465. * @param scene The scene the effect belongs to.
  66466. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66467. */
  66468. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66469. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66470. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66471. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66472. // Enable and get current depth map
  66473. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66474. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66475. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66476. // Capture circle of confusion texture
  66477. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66478. _this._depthOfFieldPass.autoClear = false;
  66479. // 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)
  66480. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66481. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66482. _this._depthOfFieldBlurY = [];
  66483. _this._depthOfFieldBlurX = [];
  66484. var blurCount = 1;
  66485. var kernelSize = 15;
  66486. switch (blurLevel) {
  66487. case DepthOfFieldEffectBlurLevel.High: {
  66488. blurCount = 3;
  66489. kernelSize = 51;
  66490. break;
  66491. }
  66492. case DepthOfFieldEffectBlurLevel.Medium: {
  66493. blurCount = 2;
  66494. kernelSize = 31;
  66495. break;
  66496. }
  66497. default: {
  66498. kernelSize = 15;
  66499. blurCount = 1;
  66500. break;
  66501. }
  66502. }
  66503. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66504. for (var i = 0; i < blurCount; i++) {
  66505. 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);
  66506. blurY.autoClear = false;
  66507. 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);
  66508. blurX.autoClear = false;
  66509. _this._depthOfFieldBlurY.push(blurY);
  66510. _this._depthOfFieldBlurX.push(blurX);
  66511. }
  66512. // Merge blurred images with original image based on circleOfConfusion
  66513. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66514. _this._depthOfFieldMerge.autoClear = false;
  66515. // Set all post processes on the effect.
  66516. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66517. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66518. effects.push(_this._depthOfFieldBlurY[i]);
  66519. effects.push(_this._depthOfFieldBlurX[i]);
  66520. }
  66521. effects.push(_this._depthOfFieldMerge);
  66522. return effects;
  66523. }, true) || this;
  66524. return _this;
  66525. }
  66526. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66527. get: function () {
  66528. return this._circleOfConfusion.focalLength;
  66529. },
  66530. /**
  66531. * The focal the length of the camera used in the effect
  66532. */
  66533. set: function (value) {
  66534. this._circleOfConfusion.focalLength = value;
  66535. },
  66536. enumerable: true,
  66537. configurable: true
  66538. });
  66539. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66540. get: function () {
  66541. return this._circleOfConfusion.fStop;
  66542. },
  66543. /**
  66544. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66545. */
  66546. set: function (value) {
  66547. this._circleOfConfusion.fStop = value;
  66548. },
  66549. enumerable: true,
  66550. configurable: true
  66551. });
  66552. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66553. get: function () {
  66554. return this._circleOfConfusion.focusDistance;
  66555. },
  66556. /**
  66557. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66558. */
  66559. set: function (value) {
  66560. this._circleOfConfusion.focusDistance = value;
  66561. },
  66562. enumerable: true,
  66563. configurable: true
  66564. });
  66565. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66566. get: function () {
  66567. return this._circleOfConfusion.lensSize;
  66568. },
  66569. /**
  66570. * 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.
  66571. */
  66572. set: function (value) {
  66573. this._circleOfConfusion.lensSize = value;
  66574. },
  66575. enumerable: true,
  66576. configurable: true
  66577. });
  66578. /**
  66579. * Disposes each of the internal effects for a given camera.
  66580. * @param camera The camera to dispose the effect on.
  66581. */
  66582. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66583. this._depthOfFieldPass.dispose(camera);
  66584. this._circleOfConfusion.dispose(camera);
  66585. this._depthOfFieldBlurX.forEach(function (element) {
  66586. element.dispose(camera);
  66587. });
  66588. this._depthOfFieldBlurY.forEach(function (element) {
  66589. element.dispose(camera);
  66590. });
  66591. this._depthOfFieldMerge.dispose(camera);
  66592. };
  66593. return DepthOfFieldEffect;
  66594. }(BABYLON.PostProcessRenderEffect));
  66595. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66596. })(BABYLON || (BABYLON = {}));
  66597. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66598. var BABYLON;
  66599. (function (BABYLON) {
  66600. /**
  66601. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66602. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66603. */
  66604. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66605. __extends(DefaultRenderingPipeline, _super);
  66606. /**
  66607. * @constructor
  66608. * @param {string} name - The rendering pipeline name
  66609. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66610. * @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)
  66611. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66612. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66613. */
  66614. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66615. if (automaticBuild === void 0) { automaticBuild = true; }
  66616. var _this = _super.call(this, scene.getEngine(), name) || this;
  66617. /**
  66618. * ID of the pass post process used for bloom,
  66619. */
  66620. _this.PassPostProcessId = "PassPostProcessEffect";
  66621. /**
  66622. * ID of the highlight post process used for bloom,
  66623. */
  66624. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66625. /**
  66626. * ID of the blurX post process used for bloom,
  66627. */
  66628. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66629. /**
  66630. * ID of the blurY post process used for bloom,
  66631. */
  66632. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66633. /**
  66634. * ID of the copy back post process used for bloom,
  66635. */
  66636. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66637. /**
  66638. * ID of the image processing post process;
  66639. */
  66640. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66641. /**
  66642. * ID of the Fast Approximate Anti-Aliasing post process;
  66643. */
  66644. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66645. /**
  66646. * ID of the final merge post process;
  66647. */
  66648. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66649. /**
  66650. * Animations which can be used to tweak settings over a period of time
  66651. */
  66652. _this.animations = [];
  66653. // Values
  66654. _this._bloomEnabled = false;
  66655. _this._depthOfFieldEnabled = false;
  66656. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66657. _this._fxaaEnabled = false;
  66658. _this._imageProcessingEnabled = true;
  66659. _this._bloomScale = 0.6;
  66660. _this._buildAllowed = true;
  66661. /**
  66662. * Specifies the size of the bloom blur kernel, relative to the final output size
  66663. */
  66664. _this.bloomKernel = 64;
  66665. /**
  66666. * Specifies the weight of the bloom in the final rendering
  66667. */
  66668. _this._bloomWeight = 0.15;
  66669. _this._cameras = cameras || [];
  66670. _this._buildAllowed = automaticBuild;
  66671. // Initialize
  66672. _this._scene = scene;
  66673. var caps = _this._scene.getEngine().getCaps();
  66674. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66675. // Misc
  66676. if (_this._hdr) {
  66677. if (caps.textureHalfFloatRender) {
  66678. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66679. }
  66680. else if (caps.textureFloatRender) {
  66681. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66682. }
  66683. }
  66684. else {
  66685. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66686. }
  66687. // Attach
  66688. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66689. _this._buildPipeline();
  66690. return _this;
  66691. }
  66692. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66693. get: function () {
  66694. return this._bloomWeight;
  66695. },
  66696. /**
  66697. * The strength of the bloom.
  66698. */
  66699. set: function (value) {
  66700. if (this._bloomWeight === value) {
  66701. return;
  66702. }
  66703. this._bloomWeight = value;
  66704. if (this._hdr && this.copyBack) {
  66705. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66706. }
  66707. },
  66708. enumerable: true,
  66709. configurable: true
  66710. });
  66711. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66712. get: function () {
  66713. return this._bloomScale;
  66714. },
  66715. /**
  66716. * The scale of the bloom, lower value will provide better performance.
  66717. */
  66718. set: function (value) {
  66719. if (this._bloomScale === value) {
  66720. return;
  66721. }
  66722. this._bloomScale = value;
  66723. this._buildPipeline();
  66724. },
  66725. enumerable: true,
  66726. configurable: true
  66727. });
  66728. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66729. get: function () {
  66730. return this._bloomEnabled;
  66731. },
  66732. /**
  66733. * Enable or disable the bloom from the pipeline
  66734. */
  66735. set: function (enabled) {
  66736. if (this._bloomEnabled === enabled) {
  66737. return;
  66738. }
  66739. this._bloomEnabled = enabled;
  66740. this._buildPipeline();
  66741. },
  66742. enumerable: true,
  66743. configurable: true
  66744. });
  66745. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66746. /**
  66747. * If the depth of field is enabled.
  66748. */
  66749. get: function () {
  66750. return this._depthOfFieldEnabled;
  66751. },
  66752. set: function (enabled) {
  66753. if (this._depthOfFieldEnabled === enabled) {
  66754. return;
  66755. }
  66756. this._depthOfFieldEnabled = enabled;
  66757. this._buildPipeline();
  66758. },
  66759. enumerable: true,
  66760. configurable: true
  66761. });
  66762. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66763. /**
  66764. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66765. */
  66766. get: function () {
  66767. return this._depthOfFieldBlurLevel;
  66768. },
  66769. set: function (value) {
  66770. if (this._depthOfFieldBlurLevel === value) {
  66771. return;
  66772. }
  66773. this._depthOfFieldBlurLevel = value;
  66774. this._buildPipeline();
  66775. },
  66776. enumerable: true,
  66777. configurable: true
  66778. });
  66779. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66780. get: function () {
  66781. return this._fxaaEnabled;
  66782. },
  66783. /**
  66784. * If the anti aliasing is enabled.
  66785. */
  66786. set: function (enabled) {
  66787. if (this._fxaaEnabled === enabled) {
  66788. return;
  66789. }
  66790. this._fxaaEnabled = enabled;
  66791. this._buildPipeline();
  66792. },
  66793. enumerable: true,
  66794. configurable: true
  66795. });
  66796. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66797. get: function () {
  66798. return this._imageProcessingEnabled;
  66799. },
  66800. /**
  66801. * If image processing is enabled.
  66802. */
  66803. set: function (enabled) {
  66804. if (this._imageProcessingEnabled === enabled) {
  66805. return;
  66806. }
  66807. this._imageProcessingEnabled = enabled;
  66808. this._buildPipeline();
  66809. },
  66810. enumerable: true,
  66811. configurable: true
  66812. });
  66813. /**
  66814. * Force the compilation of the entire pipeline.
  66815. */
  66816. DefaultRenderingPipeline.prototype.prepare = function () {
  66817. var previousState = this._buildAllowed;
  66818. this._buildAllowed = true;
  66819. this._buildPipeline();
  66820. this._buildAllowed = previousState;
  66821. };
  66822. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66823. var _this = this;
  66824. if (!this._buildAllowed) {
  66825. return;
  66826. }
  66827. var engine = this._scene.getEngine();
  66828. this._disposePostProcesses();
  66829. this._reset();
  66830. if (this.depthOfFieldEnabled) {
  66831. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  66832. this.addEffect(this.depthOfField);
  66833. }
  66834. if (this.bloomEnabled) {
  66835. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66836. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66837. if (!this._hdr) {
  66838. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66839. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66840. this.highlights.autoClear = false;
  66841. this.highlights.alwaysForcePOT = true;
  66842. }
  66843. 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);
  66844. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66845. this.blurX.alwaysForcePOT = true;
  66846. this.blurX.autoClear = false;
  66847. this.blurX.onActivateObservable.add(function () {
  66848. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66849. _this.blurX.kernel = _this.bloomKernel * dw;
  66850. });
  66851. 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);
  66852. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66853. this.blurY.alwaysForcePOT = true;
  66854. this.blurY.autoClear = false;
  66855. this.blurY.onActivateObservable.add(function () {
  66856. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66857. _this.blurY.kernel = _this.bloomKernel * dh;
  66858. });
  66859. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66860. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66861. this.copyBack.alwaysForcePOT = true;
  66862. if (this._hdr) {
  66863. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66864. var w = this.bloomWeight;
  66865. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66866. }
  66867. else {
  66868. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66869. }
  66870. this.copyBack.autoClear = false;
  66871. }
  66872. if (this._imageProcessingEnabled) {
  66873. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66874. if (this._hdr) {
  66875. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66876. }
  66877. else {
  66878. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66879. }
  66880. }
  66881. if (this.fxaaEnabled) {
  66882. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66883. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66884. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66885. }
  66886. else if (this._hdr && this.imageProcessing) {
  66887. this.finalMerge = this.imageProcessing;
  66888. }
  66889. else {
  66890. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66891. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66892. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66893. }
  66894. if (this.bloomEnabled) {
  66895. if (this._hdr) {
  66896. this.copyBack.shareOutputWith(this.blurX);
  66897. if (this.imageProcessing) {
  66898. this.imageProcessing.shareOutputWith(this.pass);
  66899. this.imageProcessing.autoClear = false;
  66900. }
  66901. else if (this.fxaa) {
  66902. this.fxaa.shareOutputWith(this.pass);
  66903. }
  66904. else {
  66905. this.finalMerge.shareOutputWith(this.pass);
  66906. }
  66907. }
  66908. else {
  66909. if (this.fxaa) {
  66910. this.fxaa.shareOutputWith(this.pass);
  66911. }
  66912. else {
  66913. this.finalMerge.shareOutputWith(this.pass);
  66914. }
  66915. }
  66916. }
  66917. if (this._cameras !== null) {
  66918. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66919. }
  66920. };
  66921. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66922. for (var i = 0; i < this._cameras.length; i++) {
  66923. var camera = this._cameras[i];
  66924. if (this.pass) {
  66925. this.pass.dispose(camera);
  66926. }
  66927. if (this.highlights) {
  66928. this.highlights.dispose(camera);
  66929. }
  66930. if (this.blurX) {
  66931. this.blurX.dispose(camera);
  66932. }
  66933. if (this.blurY) {
  66934. this.blurY.dispose(camera);
  66935. }
  66936. if (this.copyBack) {
  66937. this.copyBack.dispose(camera);
  66938. }
  66939. if (this.imageProcessing) {
  66940. this.imageProcessing.dispose(camera);
  66941. }
  66942. if (this.fxaa) {
  66943. this.fxaa.dispose(camera);
  66944. }
  66945. if (this.finalMerge) {
  66946. this.finalMerge.dispose(camera);
  66947. }
  66948. if (this.depthOfField) {
  66949. this.depthOfField.disposeEffects(camera);
  66950. }
  66951. }
  66952. this.pass = null;
  66953. this.highlights = null;
  66954. this.blurX = null;
  66955. this.blurY = null;
  66956. this.copyBack = null;
  66957. this.imageProcessing = null;
  66958. this.fxaa = null;
  66959. this.finalMerge = null;
  66960. this.depthOfField = null;
  66961. };
  66962. /**
  66963. * Dispose of the pipeline and stop all post processes
  66964. */
  66965. DefaultRenderingPipeline.prototype.dispose = function () {
  66966. this._disposePostProcesses();
  66967. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66968. _super.prototype.dispose.call(this);
  66969. };
  66970. /**
  66971. * Serialize the rendering pipeline (Used when exporting)
  66972. * @returns the serialized object
  66973. */
  66974. DefaultRenderingPipeline.prototype.serialize = function () {
  66975. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66976. serializationObject.customType = "DefaultRenderingPipeline";
  66977. return serializationObject;
  66978. };
  66979. /**
  66980. * Parse the serialized pipeline
  66981. * @param source Source pipeline.
  66982. * @param scene The scene to load the pipeline to.
  66983. * @param rootUrl The URL of the serialized pipeline.
  66984. * @returns An instantiated pipeline from the serialized object.
  66985. */
  66986. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66987. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  66988. };
  66989. __decorate([
  66990. BABYLON.serialize()
  66991. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  66992. __decorate([
  66993. BABYLON.serialize()
  66994. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  66995. __decorate([
  66996. BABYLON.serialize()
  66997. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  66998. __decorate([
  66999. BABYLON.serialize()
  67000. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67001. __decorate([
  67002. BABYLON.serialize()
  67003. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67004. __decorate([
  67005. BABYLON.serialize()
  67006. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67007. __decorate([
  67008. BABYLON.serialize()
  67009. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67010. __decorate([
  67011. BABYLON.serialize()
  67012. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67013. __decorate([
  67014. BABYLON.serialize()
  67015. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67016. __decorate([
  67017. BABYLON.serialize()
  67018. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67019. return DefaultRenderingPipeline;
  67020. }(BABYLON.PostProcessRenderPipeline));
  67021. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67022. })(BABYLON || (BABYLON = {}));
  67023. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67024. var BABYLON;
  67025. (function (BABYLON) {
  67026. /**
  67027. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67028. */
  67029. var GeometryBufferRenderer = /** @class */ (function () {
  67030. /**
  67031. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  67032. * @param scene The scene the buffer belongs to
  67033. * @param ratio How big is the buffer related to the main canvas.
  67034. */
  67035. function GeometryBufferRenderer(scene, ratio) {
  67036. if (ratio === void 0) { ratio = 1; }
  67037. this._enablePosition = false;
  67038. this._scene = scene;
  67039. this._ratio = ratio;
  67040. // Render target
  67041. this._createRenderTargets();
  67042. }
  67043. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  67044. /**
  67045. * Set the render list (meshes to be rendered) used in the G buffer.
  67046. */
  67047. set: function (meshes) {
  67048. this._multiRenderTarget.renderList = meshes;
  67049. },
  67050. enumerable: true,
  67051. configurable: true
  67052. });
  67053. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  67054. /**
  67055. * Gets wether or not G buffer are supported by the running hardware.
  67056. * This requires draw buffer supports
  67057. */
  67058. get: function () {
  67059. return this._multiRenderTarget.isSupported;
  67060. },
  67061. enumerable: true,
  67062. configurable: true
  67063. });
  67064. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  67065. /**
  67066. * Gets wether or not position are enabled for the G buffer.
  67067. */
  67068. get: function () {
  67069. return this._enablePosition;
  67070. },
  67071. /**
  67072. * Sets wether or not position are enabled for the G buffer.
  67073. */
  67074. set: function (enable) {
  67075. this._enablePosition = enable;
  67076. this.dispose();
  67077. this._createRenderTargets();
  67078. },
  67079. enumerable: true,
  67080. configurable: true
  67081. });
  67082. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67083. /**
  67084. * Gets the scene associated with the buffer.
  67085. */
  67086. get: function () {
  67087. return this._scene;
  67088. },
  67089. enumerable: true,
  67090. configurable: true
  67091. });
  67092. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67093. /**
  67094. * Gets the ratio used by the buffer during its creation.
  67095. * How big is the buffer related to the main canvas.
  67096. */
  67097. get: function () {
  67098. return this._ratio;
  67099. },
  67100. enumerable: true,
  67101. configurable: true
  67102. });
  67103. /**
  67104. * Checks wether everything is ready to render a submesh to the G buffer.
  67105. * @param subMesh the submesh to check readiness for
  67106. * @param useInstances is the mesh drawn using instance or not
  67107. * @returns true if ready otherwise false
  67108. */
  67109. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67110. var material = subMesh.getMaterial();
  67111. if (material && material.disableDepthWrite) {
  67112. return false;
  67113. }
  67114. var defines = [];
  67115. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67116. var mesh = subMesh.getMesh();
  67117. // Alpha test
  67118. if (material && material.needAlphaTesting()) {
  67119. defines.push("#define ALPHATEST");
  67120. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67121. attribs.push(BABYLON.VertexBuffer.UVKind);
  67122. defines.push("#define UV1");
  67123. }
  67124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67125. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67126. defines.push("#define UV2");
  67127. }
  67128. }
  67129. // Buffers
  67130. if (this._enablePosition) {
  67131. defines.push("#define POSITION");
  67132. }
  67133. // Bones
  67134. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67135. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67136. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67137. if (mesh.numBoneInfluencers > 4) {
  67138. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67139. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67140. }
  67141. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67142. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67143. }
  67144. else {
  67145. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67146. }
  67147. // Instances
  67148. if (useInstances) {
  67149. defines.push("#define INSTANCES");
  67150. attribs.push("world0");
  67151. attribs.push("world1");
  67152. attribs.push("world2");
  67153. attribs.push("world3");
  67154. }
  67155. // Get correct effect
  67156. var join = defines.join("\n");
  67157. if (this._cachedDefines !== join) {
  67158. this._cachedDefines = join;
  67159. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67160. }
  67161. return this._effect.isReady();
  67162. };
  67163. /**
  67164. * Gets the current underlying G Buffer.
  67165. * @returns the buffer
  67166. */
  67167. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67168. return this._multiRenderTarget;
  67169. };
  67170. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67171. /**
  67172. * Gets the number of samples used to render the buffer (anti aliasing).
  67173. */
  67174. get: function () {
  67175. return this._multiRenderTarget.samples;
  67176. },
  67177. /**
  67178. * Sets the number of samples used to render the buffer (anti aliasing).
  67179. */
  67180. set: function (value) {
  67181. this._multiRenderTarget.samples = value;
  67182. },
  67183. enumerable: true,
  67184. configurable: true
  67185. });
  67186. /**
  67187. * Disposes the renderer and frees up associated resources.
  67188. */
  67189. GeometryBufferRenderer.prototype.dispose = function () {
  67190. this.getGBuffer().dispose();
  67191. };
  67192. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67193. var _this = this;
  67194. var engine = this._scene.getEngine();
  67195. var count = this._enablePosition ? 3 : 2;
  67196. 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 });
  67197. if (!this.isSupported) {
  67198. return;
  67199. }
  67200. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67201. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67202. this._multiRenderTarget.refreshRate = 1;
  67203. this._multiRenderTarget.renderParticles = false;
  67204. this._multiRenderTarget.renderList = null;
  67205. // set default depth value to 1.0 (far away)
  67206. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67207. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67208. });
  67209. // Custom render function
  67210. var renderSubMesh = function (subMesh) {
  67211. var mesh = subMesh.getRenderingMesh();
  67212. var scene = _this._scene;
  67213. var engine = scene.getEngine();
  67214. var material = subMesh.getMaterial();
  67215. if (!material) {
  67216. return;
  67217. }
  67218. // Culling
  67219. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67220. // Managing instances
  67221. var batch = mesh._getInstancesRenderList(subMesh._id);
  67222. if (batch.mustReturn) {
  67223. return;
  67224. }
  67225. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67226. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67227. engine.enableEffect(_this._effect);
  67228. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67229. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67230. _this._effect.setMatrix("view", scene.getViewMatrix());
  67231. // Alpha test
  67232. if (material && material.needAlphaTesting()) {
  67233. var alphaTexture = material.getAlphaTestTexture();
  67234. if (alphaTexture) {
  67235. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67236. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67237. }
  67238. }
  67239. // Bones
  67240. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67241. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67242. }
  67243. // Draw
  67244. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67245. }
  67246. };
  67247. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67248. var index;
  67249. if (depthOnlySubMeshes.length) {
  67250. engine.setColorWrite(false);
  67251. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67252. renderSubMesh(depthOnlySubMeshes.data[index]);
  67253. }
  67254. engine.setColorWrite(true);
  67255. }
  67256. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67257. renderSubMesh(opaqueSubMeshes.data[index]);
  67258. }
  67259. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67260. renderSubMesh(alphaTestSubMeshes.data[index]);
  67261. }
  67262. };
  67263. };
  67264. return GeometryBufferRenderer;
  67265. }());
  67266. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67267. })(BABYLON || (BABYLON = {}));
  67268. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67269. var BABYLON;
  67270. (function (BABYLON) {
  67271. var RefractionPostProcess = /** @class */ (function (_super) {
  67272. __extends(RefractionPostProcess, _super);
  67273. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67274. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67275. _this.color = color;
  67276. _this.depth = depth;
  67277. _this.colorLevel = colorLevel;
  67278. _this.onActivateObservable.add(function (cam) {
  67279. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67280. });
  67281. _this.onApplyObservable.add(function (effect) {
  67282. effect.setColor3("baseColor", _this.color);
  67283. effect.setFloat("depth", _this.depth);
  67284. effect.setFloat("colorLevel", _this.colorLevel);
  67285. effect.setTexture("refractionSampler", _this._refRexture);
  67286. });
  67287. return _this;
  67288. }
  67289. // Methods
  67290. RefractionPostProcess.prototype.dispose = function (camera) {
  67291. if (this._refRexture) {
  67292. this._refRexture.dispose();
  67293. }
  67294. _super.prototype.dispose.call(this, camera);
  67295. };
  67296. return RefractionPostProcess;
  67297. }(BABYLON.PostProcess));
  67298. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67299. })(BABYLON || (BABYLON = {}));
  67300. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67301. var BABYLON;
  67302. (function (BABYLON) {
  67303. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67304. __extends(BlackAndWhitePostProcess, _super);
  67305. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67306. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67307. _this.degree = 1;
  67308. _this.onApplyObservable.add(function (effect) {
  67309. effect.setFloat("degree", _this.degree);
  67310. });
  67311. return _this;
  67312. }
  67313. return BlackAndWhitePostProcess;
  67314. }(BABYLON.PostProcess));
  67315. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67316. })(BABYLON || (BABYLON = {}));
  67317. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67318. var BABYLON;
  67319. (function (BABYLON) {
  67320. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67321. __extends(ConvolutionPostProcess, _super);
  67322. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67323. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67324. _this.kernel = kernel;
  67325. _this.onApply = function (effect) {
  67326. effect.setFloat2("screenSize", _this.width, _this.height);
  67327. effect.setArray("kernel", _this.kernel);
  67328. };
  67329. return _this;
  67330. }
  67331. // Statics
  67332. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67333. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67334. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67335. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67336. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67337. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67338. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67339. return ConvolutionPostProcess;
  67340. }(BABYLON.PostProcess));
  67341. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67342. })(BABYLON || (BABYLON = {}));
  67343. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67344. var BABYLON;
  67345. (function (BABYLON) {
  67346. var FilterPostProcess = /** @class */ (function (_super) {
  67347. __extends(FilterPostProcess, _super);
  67348. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67349. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67350. _this.kernelMatrix = kernelMatrix;
  67351. _this.onApply = function (effect) {
  67352. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67353. };
  67354. return _this;
  67355. }
  67356. return FilterPostProcess;
  67357. }(BABYLON.PostProcess));
  67358. BABYLON.FilterPostProcess = FilterPostProcess;
  67359. })(BABYLON || (BABYLON = {}));
  67360. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67361. var BABYLON;
  67362. (function (BABYLON) {
  67363. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67364. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67365. __extends(VolumetricLightScatteringPostProcess, _super);
  67366. /**
  67367. * @constructor
  67368. * @param {string} name - The post-process name
  67369. * @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)
  67370. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67371. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67372. * @param {number} samples - The post-process quality, default 100
  67373. * @param {number} samplingMode - The post-process filtering mode
  67374. * @param {BABYLON.Engine} engine - The babylon engine
  67375. * @param {boolean} reusable - If the post-process is reusable
  67376. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67377. */
  67378. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67379. if (samples === void 0) { samples = 100; }
  67380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67381. 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;
  67382. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67383. /**
  67384. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67385. * @type {Vector3}
  67386. */
  67387. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67388. /**
  67389. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67390. * @type {boolean}
  67391. */
  67392. _this.useCustomMeshPosition = false;
  67393. /**
  67394. * If the post-process should inverse the light scattering direction
  67395. * @type {boolean}
  67396. */
  67397. _this.invert = true;
  67398. /**
  67399. * Array containing the excluded meshes not rendered in the internal pass
  67400. */
  67401. _this.excludedMeshes = new Array();
  67402. /**
  67403. * Controls the overall intensity of the post-process
  67404. * @type {number}
  67405. */
  67406. _this.exposure = 0.3;
  67407. /**
  67408. * Dissipates each sample's contribution in range [0, 1]
  67409. * @type {number}
  67410. */
  67411. _this.decay = 0.96815;
  67412. /**
  67413. * Controls the overall intensity of each sample
  67414. * @type {number}
  67415. */
  67416. _this.weight = 0.58767;
  67417. /**
  67418. * Controls the density of each sample
  67419. * @type {number}
  67420. */
  67421. _this.density = 0.926;
  67422. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67423. engine = scene.getEngine();
  67424. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67425. // Configure mesh
  67426. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67427. // Configure
  67428. _this._createPass(scene, ratio.passRatio || ratio);
  67429. _this.onActivate = function (camera) {
  67430. if (!_this.isSupported) {
  67431. _this.dispose(camera);
  67432. }
  67433. _this.onActivate = null;
  67434. };
  67435. _this.onApplyObservable.add(function (effect) {
  67436. _this._updateMeshScreenCoordinates(scene);
  67437. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67438. effect.setFloat("exposure", _this.exposure);
  67439. effect.setFloat("decay", _this.decay);
  67440. effect.setFloat("weight", _this.weight);
  67441. effect.setFloat("density", _this.density);
  67442. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67443. });
  67444. return _this;
  67445. }
  67446. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67447. get: function () {
  67448. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67449. return false;
  67450. },
  67451. set: function (useDiffuseColor) {
  67452. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67453. },
  67454. enumerable: true,
  67455. configurable: true
  67456. });
  67457. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67458. return "VolumetricLightScatteringPostProcess";
  67459. };
  67460. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67461. var mesh = subMesh.getMesh();
  67462. // Render this.mesh as default
  67463. if (mesh === this.mesh && mesh.material) {
  67464. return mesh.material.isReady(mesh);
  67465. }
  67466. var defines = [];
  67467. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67468. var material = subMesh.getMaterial();
  67469. // Alpha test
  67470. if (material) {
  67471. if (material.needAlphaTesting()) {
  67472. defines.push("#define ALPHATEST");
  67473. }
  67474. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67475. attribs.push(BABYLON.VertexBuffer.UVKind);
  67476. defines.push("#define UV1");
  67477. }
  67478. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67479. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67480. defines.push("#define UV2");
  67481. }
  67482. }
  67483. // Bones
  67484. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67485. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67486. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67487. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67488. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67489. }
  67490. else {
  67491. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67492. }
  67493. // Instances
  67494. if (useInstances) {
  67495. defines.push("#define INSTANCES");
  67496. attribs.push("world0");
  67497. attribs.push("world1");
  67498. attribs.push("world2");
  67499. attribs.push("world3");
  67500. }
  67501. // Get correct effect
  67502. var join = defines.join("\n");
  67503. if (this._cachedDefines !== join) {
  67504. this._cachedDefines = join;
  67505. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67506. }
  67507. return this._volumetricLightScatteringPass.isReady();
  67508. };
  67509. /**
  67510. * Sets the new light position for light scattering effect
  67511. * @param {BABYLON.Vector3} The new custom light position
  67512. */
  67513. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67514. this.customMeshPosition = position;
  67515. };
  67516. /**
  67517. * Returns the light position for light scattering effect
  67518. * @return {BABYLON.Vector3} The custom light position
  67519. */
  67520. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67521. return this.customMeshPosition;
  67522. };
  67523. /**
  67524. * Disposes the internal assets and detaches the post-process from the camera
  67525. */
  67526. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67527. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67528. if (rttIndex !== -1) {
  67529. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67530. }
  67531. this._volumetricLightScatteringRTT.dispose();
  67532. _super.prototype.dispose.call(this, camera);
  67533. };
  67534. /**
  67535. * Returns the render target texture used by the post-process
  67536. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67537. */
  67538. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67539. return this._volumetricLightScatteringRTT;
  67540. };
  67541. // Private methods
  67542. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67543. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67544. return true;
  67545. }
  67546. return false;
  67547. };
  67548. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67549. var _this = this;
  67550. var engine = scene.getEngine();
  67551. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67552. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67553. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67554. this._volumetricLightScatteringRTT.renderList = null;
  67555. this._volumetricLightScatteringRTT.renderParticles = false;
  67556. var camera = this.getCamera();
  67557. if (camera) {
  67558. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67559. }
  67560. else {
  67561. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67562. }
  67563. // Custom render function for submeshes
  67564. var renderSubMesh = function (subMesh) {
  67565. var mesh = subMesh.getRenderingMesh();
  67566. if (_this._meshExcluded(mesh)) {
  67567. return;
  67568. }
  67569. var material = subMesh.getMaterial();
  67570. if (!material) {
  67571. return;
  67572. }
  67573. var scene = mesh.getScene();
  67574. var engine = scene.getEngine();
  67575. // Culling
  67576. engine.setState(material.backFaceCulling);
  67577. // Managing instances
  67578. var batch = mesh._getInstancesRenderList(subMesh._id);
  67579. if (batch.mustReturn) {
  67580. return;
  67581. }
  67582. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67583. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67584. var effect = _this._volumetricLightScatteringPass;
  67585. if (mesh === _this.mesh) {
  67586. if (subMesh.effect) {
  67587. effect = subMesh.effect;
  67588. }
  67589. else {
  67590. effect = material.getEffect();
  67591. }
  67592. }
  67593. engine.enableEffect(effect);
  67594. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67595. if (mesh === _this.mesh) {
  67596. material.bind(mesh.getWorldMatrix(), mesh);
  67597. }
  67598. else {
  67599. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67600. // Alpha test
  67601. if (material && material.needAlphaTesting()) {
  67602. var alphaTexture = material.getAlphaTestTexture();
  67603. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67604. if (alphaTexture) {
  67605. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67606. }
  67607. }
  67608. // Bones
  67609. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67610. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67611. }
  67612. }
  67613. // Draw
  67614. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67615. }
  67616. };
  67617. // Render target texture callbacks
  67618. var savedSceneClearColor;
  67619. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67620. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67621. savedSceneClearColor = scene.clearColor;
  67622. scene.clearColor = sceneClearColor;
  67623. });
  67624. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67625. scene.clearColor = savedSceneClearColor;
  67626. });
  67627. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67628. var engine = scene.getEngine();
  67629. var index;
  67630. if (depthOnlySubMeshes.length) {
  67631. engine.setColorWrite(false);
  67632. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67633. renderSubMesh(depthOnlySubMeshes.data[index]);
  67634. }
  67635. engine.setColorWrite(true);
  67636. }
  67637. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67638. renderSubMesh(opaqueSubMeshes.data[index]);
  67639. }
  67640. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67641. renderSubMesh(alphaTestSubMeshes.data[index]);
  67642. }
  67643. if (transparentSubMeshes.length) {
  67644. // Sort sub meshes
  67645. for (index = 0; index < transparentSubMeshes.length; index++) {
  67646. var submesh = transparentSubMeshes.data[index];
  67647. var boundingInfo = submesh.getBoundingInfo();
  67648. if (boundingInfo && scene.activeCamera) {
  67649. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67650. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67651. }
  67652. }
  67653. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67654. sortedArray.sort(function (a, b) {
  67655. // Alpha index first
  67656. if (a._alphaIndex > b._alphaIndex) {
  67657. return 1;
  67658. }
  67659. if (a._alphaIndex < b._alphaIndex) {
  67660. return -1;
  67661. }
  67662. // Then distance to camera
  67663. if (a._distanceToCamera < b._distanceToCamera) {
  67664. return 1;
  67665. }
  67666. if (a._distanceToCamera > b._distanceToCamera) {
  67667. return -1;
  67668. }
  67669. return 0;
  67670. });
  67671. // Render sub meshes
  67672. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67673. for (index = 0; index < sortedArray.length; index++) {
  67674. renderSubMesh(sortedArray[index]);
  67675. }
  67676. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67677. }
  67678. };
  67679. };
  67680. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67681. var transform = scene.getTransformMatrix();
  67682. var meshPosition;
  67683. if (this.useCustomMeshPosition) {
  67684. meshPosition = this.customMeshPosition;
  67685. }
  67686. else if (this.attachedNode) {
  67687. meshPosition = this.attachedNode.position;
  67688. }
  67689. else {
  67690. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67691. }
  67692. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67693. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67694. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67695. if (this.invert)
  67696. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67697. };
  67698. // Static methods
  67699. /**
  67700. * Creates a default mesh for the Volumeric Light Scattering post-process
  67701. * @param {string} The mesh name
  67702. * @param {BABYLON.Scene} The scene where to create the mesh
  67703. * @return {BABYLON.Mesh} the default mesh
  67704. */
  67705. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67706. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67707. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67708. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67709. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67710. mesh.material = material;
  67711. return mesh;
  67712. };
  67713. __decorate([
  67714. BABYLON.serializeAsVector3()
  67715. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67716. __decorate([
  67717. BABYLON.serialize()
  67718. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67719. __decorate([
  67720. BABYLON.serialize()
  67721. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67722. __decorate([
  67723. BABYLON.serializeAsMeshReference()
  67724. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67725. __decorate([
  67726. BABYLON.serialize()
  67727. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67728. __decorate([
  67729. BABYLON.serialize()
  67730. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67731. __decorate([
  67732. BABYLON.serialize()
  67733. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67734. __decorate([
  67735. BABYLON.serialize()
  67736. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67737. __decorate([
  67738. BABYLON.serialize()
  67739. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67740. return VolumetricLightScatteringPostProcess;
  67741. }(BABYLON.PostProcess));
  67742. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67743. })(BABYLON || (BABYLON = {}));
  67744. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67745. //
  67746. // This post-process allows the modification of rendered colors by using
  67747. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67748. //
  67749. // The object needs to be provided an url to a texture containing the color
  67750. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67751. // Use an image editing software to tweak the LUT to match your needs.
  67752. //
  67753. // For an example of a color LUT, see here:
  67754. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67755. // For explanations on color grading, see here:
  67756. // http://udn.epicgames.com/Three/ColorGrading.html
  67757. //
  67758. var BABYLON;
  67759. (function (BABYLON) {
  67760. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67761. __extends(ColorCorrectionPostProcess, _super);
  67762. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67763. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67764. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67765. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67766. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67767. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67768. _this.onApply = function (effect) {
  67769. effect.setTexture("colorTable", _this._colorTableTexture);
  67770. };
  67771. return _this;
  67772. }
  67773. return ColorCorrectionPostProcess;
  67774. }(BABYLON.PostProcess));
  67775. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67776. })(BABYLON || (BABYLON = {}));
  67777. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67778. var BABYLON;
  67779. (function (BABYLON) {
  67780. var TonemappingOperator;
  67781. (function (TonemappingOperator) {
  67782. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67783. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67784. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67785. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67786. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67787. ;
  67788. var TonemapPostProcess = /** @class */ (function (_super) {
  67789. __extends(TonemapPostProcess, _super);
  67790. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67791. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67792. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67793. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67794. _this._operator = _operator;
  67795. _this.exposureAdjustment = exposureAdjustment;
  67796. var defines = "#define ";
  67797. if (_this._operator === TonemappingOperator.Hable)
  67798. defines += "HABLE_TONEMAPPING";
  67799. else if (_this._operator === TonemappingOperator.Reinhard)
  67800. defines += "REINHARD_TONEMAPPING";
  67801. else if (_this._operator === TonemappingOperator.HejiDawson)
  67802. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67803. else if (_this._operator === TonemappingOperator.Photographic)
  67804. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67805. //sadly a second call to create the effect.
  67806. _this.updateEffect(defines);
  67807. _this.onApply = function (effect) {
  67808. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67809. };
  67810. return _this;
  67811. }
  67812. return TonemapPostProcess;
  67813. }(BABYLON.PostProcess));
  67814. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67815. })(BABYLON || (BABYLON = {}));
  67816. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67817. var BABYLON;
  67818. (function (BABYLON) {
  67819. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67820. __extends(DisplayPassPostProcess, _super);
  67821. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67822. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67823. }
  67824. return DisplayPassPostProcess;
  67825. }(BABYLON.PostProcess));
  67826. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67827. })(BABYLON || (BABYLON = {}));
  67828. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67829. var BABYLON;
  67830. (function (BABYLON) {
  67831. var HighlightsPostProcess = /** @class */ (function (_super) {
  67832. __extends(HighlightsPostProcess, _super);
  67833. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67834. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67835. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67836. }
  67837. return HighlightsPostProcess;
  67838. }(BABYLON.PostProcess));
  67839. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67840. })(BABYLON || (BABYLON = {}));
  67841. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67842. var BABYLON;
  67843. (function (BABYLON) {
  67844. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67845. __extends(ImageProcessingPostProcess, _super);
  67846. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67847. if (camera === void 0) { camera = null; }
  67848. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67849. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67850. _this._fromLinearSpace = true;
  67851. /**
  67852. * Defines cache preventing GC.
  67853. */
  67854. _this._defines = {
  67855. IMAGEPROCESSING: false,
  67856. VIGNETTE: false,
  67857. VIGNETTEBLENDMODEMULTIPLY: false,
  67858. VIGNETTEBLENDMODEOPAQUE: false,
  67859. TONEMAPPING: false,
  67860. CONTRAST: false,
  67861. COLORCURVES: false,
  67862. COLORGRADING: false,
  67863. COLORGRADING3D: false,
  67864. FROMLINEARSPACE: false,
  67865. SAMPLER3DGREENDEPTH: false,
  67866. SAMPLER3DBGRMAP: false,
  67867. IMAGEPROCESSINGPOSTPROCESS: false,
  67868. EXPOSURE: false,
  67869. };
  67870. // Setup the configuration as forced by the constructor. This would then not force the
  67871. // scene materials output in linear space and let untouched the default forward pass.
  67872. if (imageProcessingConfiguration) {
  67873. imageProcessingConfiguration.applyByPostProcess = true;
  67874. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67875. // This will cause the shader to be compiled
  67876. _this.fromLinearSpace = false;
  67877. }
  67878. else {
  67879. _this._attachImageProcessingConfiguration(null, true);
  67880. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67881. }
  67882. _this.onApply = function (effect) {
  67883. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67884. };
  67885. return _this;
  67886. }
  67887. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67888. /**
  67889. * Gets the image processing configuration used either in this material.
  67890. */
  67891. get: function () {
  67892. return this._imageProcessingConfiguration;
  67893. },
  67894. /**
  67895. * Sets the Default image processing configuration used either in the this material.
  67896. *
  67897. * If sets to null, the scene one is in use.
  67898. */
  67899. set: function (value) {
  67900. this._attachImageProcessingConfiguration(value);
  67901. },
  67902. enumerable: true,
  67903. configurable: true
  67904. });
  67905. /**
  67906. * Attaches a new image processing configuration to the PBR Material.
  67907. * @param configuration
  67908. */
  67909. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67910. var _this = this;
  67911. if (doNotBuild === void 0) { doNotBuild = false; }
  67912. if (configuration === this._imageProcessingConfiguration) {
  67913. return;
  67914. }
  67915. // Detaches observer.
  67916. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67917. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67918. }
  67919. // Pick the scene configuration if needed.
  67920. if (!configuration) {
  67921. var scene = null;
  67922. var engine = this.getEngine();
  67923. var camera = this.getCamera();
  67924. if (camera) {
  67925. scene = camera.getScene();
  67926. }
  67927. else if (engine && engine.scenes) {
  67928. var scenes = engine.scenes;
  67929. scene = scenes[scenes.length - 1];
  67930. }
  67931. else {
  67932. scene = BABYLON.Engine.LastCreatedScene;
  67933. }
  67934. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67935. }
  67936. else {
  67937. this._imageProcessingConfiguration = configuration;
  67938. }
  67939. // Attaches observer.
  67940. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  67941. _this._updateParameters();
  67942. });
  67943. // Ensure the effect will be rebuilt.
  67944. if (!doNotBuild) {
  67945. this._updateParameters();
  67946. }
  67947. };
  67948. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  67949. /**
  67950. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67951. */
  67952. get: function () {
  67953. return this.imageProcessingConfiguration.colorCurves;
  67954. },
  67955. /**
  67956. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67957. */
  67958. set: function (value) {
  67959. this.imageProcessingConfiguration.colorCurves = value;
  67960. },
  67961. enumerable: true,
  67962. configurable: true
  67963. });
  67964. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  67965. /**
  67966. * Gets wether the color curves effect is enabled.
  67967. */
  67968. get: function () {
  67969. return this.imageProcessingConfiguration.colorCurvesEnabled;
  67970. },
  67971. /**
  67972. * Sets wether the color curves effect is enabled.
  67973. */
  67974. set: function (value) {
  67975. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  67976. },
  67977. enumerable: true,
  67978. configurable: true
  67979. });
  67980. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  67981. /**
  67982. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67983. */
  67984. get: function () {
  67985. return this.imageProcessingConfiguration.colorGradingTexture;
  67986. },
  67987. /**
  67988. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67989. */
  67990. set: function (value) {
  67991. this.imageProcessingConfiguration.colorGradingTexture = value;
  67992. },
  67993. enumerable: true,
  67994. configurable: true
  67995. });
  67996. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  67997. /**
  67998. * Gets wether the color grading effect is enabled.
  67999. */
  68000. get: function () {
  68001. return this.imageProcessingConfiguration.colorGradingEnabled;
  68002. },
  68003. /**
  68004. * Gets wether the color grading effect is enabled.
  68005. */
  68006. set: function (value) {
  68007. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68008. },
  68009. enumerable: true,
  68010. configurable: true
  68011. });
  68012. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  68013. /**
  68014. * Gets exposure used in the effect.
  68015. */
  68016. get: function () {
  68017. return this.imageProcessingConfiguration.exposure;
  68018. },
  68019. /**
  68020. * Sets exposure used in the effect.
  68021. */
  68022. set: function (value) {
  68023. this.imageProcessingConfiguration.exposure = value;
  68024. },
  68025. enumerable: true,
  68026. configurable: true
  68027. });
  68028. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  68029. /**
  68030. * Gets wether tonemapping is enabled or not.
  68031. */
  68032. get: function () {
  68033. return this._imageProcessingConfiguration.toneMappingEnabled;
  68034. },
  68035. /**
  68036. * Sets wether tonemapping is enabled or not
  68037. */
  68038. set: function (value) {
  68039. this._imageProcessingConfiguration.toneMappingEnabled = value;
  68040. },
  68041. enumerable: true,
  68042. configurable: true
  68043. });
  68044. ;
  68045. ;
  68046. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  68047. /**
  68048. * Gets contrast used in the effect.
  68049. */
  68050. get: function () {
  68051. return this.imageProcessingConfiguration.contrast;
  68052. },
  68053. /**
  68054. * Sets contrast used in the effect.
  68055. */
  68056. set: function (value) {
  68057. this.imageProcessingConfiguration.contrast = value;
  68058. },
  68059. enumerable: true,
  68060. configurable: true
  68061. });
  68062. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  68063. /**
  68064. * Gets Vignette stretch size.
  68065. */
  68066. get: function () {
  68067. return this.imageProcessingConfiguration.vignetteStretch;
  68068. },
  68069. /**
  68070. * Sets Vignette stretch size.
  68071. */
  68072. set: function (value) {
  68073. this.imageProcessingConfiguration.vignetteStretch = value;
  68074. },
  68075. enumerable: true,
  68076. configurable: true
  68077. });
  68078. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68079. /**
  68080. * Gets Vignette centre X Offset.
  68081. */
  68082. get: function () {
  68083. return this.imageProcessingConfiguration.vignetteCentreX;
  68084. },
  68085. /**
  68086. * Sets Vignette centre X Offset.
  68087. */
  68088. set: function (value) {
  68089. this.imageProcessingConfiguration.vignetteCentreX = value;
  68090. },
  68091. enumerable: true,
  68092. configurable: true
  68093. });
  68094. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68095. /**
  68096. * Gets Vignette centre Y Offset.
  68097. */
  68098. get: function () {
  68099. return this.imageProcessingConfiguration.vignetteCentreY;
  68100. },
  68101. /**
  68102. * Sets Vignette centre Y Offset.
  68103. */
  68104. set: function (value) {
  68105. this.imageProcessingConfiguration.vignetteCentreY = value;
  68106. },
  68107. enumerable: true,
  68108. configurable: true
  68109. });
  68110. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68111. /**
  68112. * Gets Vignette weight or intensity of the vignette effect.
  68113. */
  68114. get: function () {
  68115. return this.imageProcessingConfiguration.vignetteWeight;
  68116. },
  68117. /**
  68118. * Sets Vignette weight or intensity of the vignette effect.
  68119. */
  68120. set: function (value) {
  68121. this.imageProcessingConfiguration.vignetteWeight = value;
  68122. },
  68123. enumerable: true,
  68124. configurable: true
  68125. });
  68126. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68127. /**
  68128. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68129. * if vignetteEnabled is set to true.
  68130. */
  68131. get: function () {
  68132. return this.imageProcessingConfiguration.vignetteColor;
  68133. },
  68134. /**
  68135. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68136. * if vignetteEnabled is set to true.
  68137. */
  68138. set: function (value) {
  68139. this.imageProcessingConfiguration.vignetteColor = value;
  68140. },
  68141. enumerable: true,
  68142. configurable: true
  68143. });
  68144. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68145. /**
  68146. * Gets Camera field of view used by the Vignette effect.
  68147. */
  68148. get: function () {
  68149. return this.imageProcessingConfiguration.vignetteCameraFov;
  68150. },
  68151. /**
  68152. * Sets Camera field of view used by the Vignette effect.
  68153. */
  68154. set: function (value) {
  68155. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68156. },
  68157. enumerable: true,
  68158. configurable: true
  68159. });
  68160. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68161. /**
  68162. * Gets the vignette blend mode allowing different kind of effect.
  68163. */
  68164. get: function () {
  68165. return this.imageProcessingConfiguration.vignetteBlendMode;
  68166. },
  68167. /**
  68168. * Sets the vignette blend mode allowing different kind of effect.
  68169. */
  68170. set: function (value) {
  68171. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68172. },
  68173. enumerable: true,
  68174. configurable: true
  68175. });
  68176. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68177. /**
  68178. * Gets wether the vignette effect is enabled.
  68179. */
  68180. get: function () {
  68181. return this.imageProcessingConfiguration.vignetteEnabled;
  68182. },
  68183. /**
  68184. * Sets wether the vignette effect is enabled.
  68185. */
  68186. set: function (value) {
  68187. this.imageProcessingConfiguration.vignetteEnabled = value;
  68188. },
  68189. enumerable: true,
  68190. configurable: true
  68191. });
  68192. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68193. /**
  68194. * Gets wether the input of the processing is in Gamma or Linear Space.
  68195. */
  68196. get: function () {
  68197. return this._fromLinearSpace;
  68198. },
  68199. /**
  68200. * Sets wether the input of the processing is in Gamma or Linear Space.
  68201. */
  68202. set: function (value) {
  68203. if (this._fromLinearSpace === value) {
  68204. return;
  68205. }
  68206. this._fromLinearSpace = value;
  68207. this._updateParameters();
  68208. },
  68209. enumerable: true,
  68210. configurable: true
  68211. });
  68212. ImageProcessingPostProcess.prototype.getClassName = function () {
  68213. return "ImageProcessingPostProcess";
  68214. };
  68215. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68216. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68217. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68218. var defines = "";
  68219. for (var define in this._defines) {
  68220. if (this._defines[define]) {
  68221. defines += "#define " + define + ";\r\n";
  68222. }
  68223. }
  68224. var samplers = ["textureSampler"];
  68225. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68226. var uniforms = ["scale"];
  68227. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68228. this.updateEffect(defines, uniforms, samplers);
  68229. };
  68230. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68231. _super.prototype.dispose.call(this, camera);
  68232. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68233. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68234. }
  68235. this.imageProcessingConfiguration.applyByPostProcess = false;
  68236. };
  68237. __decorate([
  68238. BABYLON.serialize()
  68239. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68240. return ImageProcessingPostProcess;
  68241. }(BABYLON.PostProcess));
  68242. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68243. })(BABYLON || (BABYLON = {}));
  68244. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68245. var BABYLON;
  68246. (function (BABYLON) {
  68247. /**
  68248. * The Blur Post Process which blurs an image based on a kernel and direction.
  68249. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68250. */
  68251. var BlurPostProcess = /** @class */ (function (_super) {
  68252. __extends(BlurPostProcess, _super);
  68253. /**
  68254. * Creates a new instance of @see BlurPostProcess
  68255. * @param name The name of the effect.
  68256. * @param direction The direction in which to blur the image.
  68257. * @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.
  68258. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68259. * @param camera The camera to apply the render pass to.
  68260. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68261. * @param engine The engine which the post process will be applied. (default: current engine)
  68262. * @param reusable If the post process can be reused on the same frame. (default: false)
  68263. * @param textureType Type of textures used when performing the post process. (default: 0)
  68264. */
  68265. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68267. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68268. if (defines === void 0) { defines = ""; }
  68269. 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;
  68270. _this.direction = direction;
  68271. _this._packedFloat = false;
  68272. _this._staticDefines = "";
  68273. _this._staticDefines = defines;
  68274. _this.onApplyObservable.add(function (effect) {
  68275. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68276. });
  68277. _this.kernel = kernel;
  68278. return _this;
  68279. }
  68280. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68281. /**
  68282. * Gets the length in pixels of the blur sample region
  68283. */
  68284. get: function () {
  68285. return this._idealKernel;
  68286. },
  68287. /**
  68288. * Sets the length in pixels of the blur sample region
  68289. */
  68290. set: function (v) {
  68291. if (this._idealKernel === v) {
  68292. return;
  68293. }
  68294. v = Math.max(v, 1);
  68295. this._idealKernel = v;
  68296. this._kernel = this._nearestBestKernel(v);
  68297. this._updateParameters();
  68298. },
  68299. enumerable: true,
  68300. configurable: true
  68301. });
  68302. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68303. /**
  68304. * Gets wether or not the blur is unpacking/repacking floats
  68305. */
  68306. get: function () {
  68307. return this._packedFloat;
  68308. },
  68309. /**
  68310. * Sets wether or not the blur needs to unpack/repack floats
  68311. */
  68312. set: function (v) {
  68313. if (this._packedFloat === v) {
  68314. return;
  68315. }
  68316. this._packedFloat = v;
  68317. this._updateParameters();
  68318. },
  68319. enumerable: true,
  68320. configurable: true
  68321. });
  68322. BlurPostProcess.prototype._updateParameters = function () {
  68323. // Generate sampling offsets and weights
  68324. var N = this._kernel;
  68325. var centerIndex = (N - 1) / 2;
  68326. // Generate Gaussian sampling weights over kernel
  68327. var offsets = [];
  68328. var weights = [];
  68329. var totalWeight = 0;
  68330. for (var i = 0; i < N; i++) {
  68331. var u = i / (N - 1);
  68332. var w = this._gaussianWeight(u * 2.0 - 1);
  68333. offsets[i] = (i - centerIndex);
  68334. weights[i] = w;
  68335. totalWeight += w;
  68336. }
  68337. // Normalize weights
  68338. for (var i = 0; i < weights.length; i++) {
  68339. weights[i] /= totalWeight;
  68340. }
  68341. // Optimize: combine samples to take advantage of hardware linear sampling
  68342. // Walk from left to center, combining pairs (symmetrically)
  68343. var linearSamplingWeights = [];
  68344. var linearSamplingOffsets = [];
  68345. var linearSamplingMap = [];
  68346. for (var i = 0; i <= centerIndex; i += 2) {
  68347. var j = Math.min(i + 1, Math.floor(centerIndex));
  68348. var singleCenterSample = i === j;
  68349. if (singleCenterSample) {
  68350. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68351. }
  68352. else {
  68353. var sharedCell = j === centerIndex;
  68354. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68355. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68356. if (offsetLinear === 0) {
  68357. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68358. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68359. }
  68360. else {
  68361. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68362. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68363. }
  68364. }
  68365. }
  68366. for (var i = 0; i < linearSamplingMap.length; i++) {
  68367. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68368. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68369. }
  68370. // Replace with optimized
  68371. offsets = linearSamplingOffsets;
  68372. weights = linearSamplingWeights;
  68373. // Generate shaders
  68374. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68375. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68376. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68377. var defines = "";
  68378. defines += this._staticDefines;
  68379. for (var i = 0; i < varyingCount; i++) {
  68380. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68381. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68382. }
  68383. var depCount = 0;
  68384. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68385. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68386. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68387. depCount++;
  68388. }
  68389. if (this.packedFloat) {
  68390. defines += "#define PACKEDFLOAT 1";
  68391. }
  68392. this.updateEffect(defines, null, null, {
  68393. varyingCount: varyingCount,
  68394. depCount: depCount
  68395. });
  68396. };
  68397. /**
  68398. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68399. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68400. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68401. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68402. * The gaps between physical kernels are compensated for in the weighting of the samples
  68403. * @param idealKernel Ideal blur kernel.
  68404. * @return Nearest best kernel.
  68405. */
  68406. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68407. var v = Math.round(idealKernel);
  68408. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68409. var k = _a[_i];
  68410. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68411. return Math.max(k, 3);
  68412. }
  68413. }
  68414. return Math.max(v, 3);
  68415. };
  68416. /**
  68417. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68418. * @param x The point on the Gaussian distribution to sample.
  68419. * @return the value of the Gaussian function at x.
  68420. */
  68421. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68422. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68423. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68424. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68425. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68426. // truncated at around 1.3% of peak strength.
  68427. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68428. var sigma = (1 / 3);
  68429. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68430. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68431. var weight = (1.0 / denominator) * Math.exp(exponent);
  68432. return weight;
  68433. };
  68434. /**
  68435. * Generates a string that can be used as a floating point number in GLSL.
  68436. * @param x Value to print.
  68437. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68438. * @return GLSL float string.
  68439. */
  68440. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68441. if (decimalFigures === void 0) { decimalFigures = 8; }
  68442. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68443. };
  68444. return BlurPostProcess;
  68445. }(BABYLON.PostProcess));
  68446. BABYLON.BlurPostProcess = BlurPostProcess;
  68447. })(BABYLON || (BABYLON = {}));
  68448. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68449. var BABYLON;
  68450. (function (BABYLON) {
  68451. var Bone = /** @class */ (function (_super) {
  68452. __extends(Bone, _super);
  68453. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68454. if (parentBone === void 0) { parentBone = null; }
  68455. if (localMatrix === void 0) { localMatrix = null; }
  68456. if (restPose === void 0) { restPose = null; }
  68457. if (baseMatrix === void 0) { baseMatrix = null; }
  68458. if (index === void 0) { index = null; }
  68459. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68460. _this.name = name;
  68461. _this.children = new Array();
  68462. _this.animations = new Array();
  68463. // Set this value to map this bone to a different index in the transform matrices.
  68464. // Set this value to -1 to exclude the bone from the transform matrices.
  68465. _this._index = null;
  68466. _this._worldTransform = new BABYLON.Matrix();
  68467. _this._absoluteTransform = new BABYLON.Matrix();
  68468. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68469. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68470. _this._scaleVector = BABYLON.Vector3.One();
  68471. _this._negateScaleChildren = BABYLON.Vector3.One();
  68472. _this._scalingDeterminant = 1;
  68473. _this._skeleton = skeleton;
  68474. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68475. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68476. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68477. _this._index = index;
  68478. skeleton.bones.push(_this);
  68479. _this.setParent(parentBone, false);
  68480. _this._updateDifferenceMatrix();
  68481. return _this;
  68482. }
  68483. Object.defineProperty(Bone.prototype, "_matrix", {
  68484. get: function () {
  68485. return this._localMatrix;
  68486. },
  68487. set: function (val) {
  68488. if (this._localMatrix) {
  68489. this._localMatrix.copyFrom(val);
  68490. }
  68491. else {
  68492. this._localMatrix = val;
  68493. }
  68494. },
  68495. enumerable: true,
  68496. configurable: true
  68497. });
  68498. // Members
  68499. Bone.prototype.getSkeleton = function () {
  68500. return this._skeleton;
  68501. };
  68502. Bone.prototype.getParent = function () {
  68503. return this._parent;
  68504. };
  68505. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68506. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68507. if (this._parent === parent) {
  68508. return;
  68509. }
  68510. if (this._parent) {
  68511. var index = this._parent.children.indexOf(this);
  68512. if (index !== -1) {
  68513. this._parent.children.splice(index, 1);
  68514. }
  68515. }
  68516. this._parent = parent;
  68517. if (this._parent) {
  68518. this._parent.children.push(this);
  68519. }
  68520. if (updateDifferenceMatrix) {
  68521. this._updateDifferenceMatrix();
  68522. }
  68523. };
  68524. Bone.prototype.getLocalMatrix = function () {
  68525. return this._localMatrix;
  68526. };
  68527. Bone.prototype.getBaseMatrix = function () {
  68528. return this._baseMatrix;
  68529. };
  68530. Bone.prototype.getRestPose = function () {
  68531. return this._restPose;
  68532. };
  68533. Bone.prototype.returnToRest = function () {
  68534. this.updateMatrix(this._restPose.clone());
  68535. };
  68536. Bone.prototype.getWorldMatrix = function () {
  68537. return this._worldTransform;
  68538. };
  68539. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68540. return this._invertedAbsoluteTransform;
  68541. };
  68542. Bone.prototype.getAbsoluteTransform = function () {
  68543. return this._absoluteTransform;
  68544. };
  68545. Object.defineProperty(Bone.prototype, "position", {
  68546. // Properties (matches AbstractMesh properties)
  68547. get: function () {
  68548. return this.getPosition();
  68549. },
  68550. set: function (newPosition) {
  68551. this.setPosition(newPosition);
  68552. },
  68553. enumerable: true,
  68554. configurable: true
  68555. });
  68556. Object.defineProperty(Bone.prototype, "rotation", {
  68557. get: function () {
  68558. return this.getRotation();
  68559. },
  68560. set: function (newRotation) {
  68561. this.setRotation(newRotation);
  68562. },
  68563. enumerable: true,
  68564. configurable: true
  68565. });
  68566. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68567. get: function () {
  68568. return this.getRotationQuaternion();
  68569. },
  68570. set: function (newRotation) {
  68571. this.setRotationQuaternion(newRotation);
  68572. },
  68573. enumerable: true,
  68574. configurable: true
  68575. });
  68576. Object.defineProperty(Bone.prototype, "scaling", {
  68577. get: function () {
  68578. return this.getScale();
  68579. },
  68580. set: function (newScaling) {
  68581. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68582. },
  68583. enumerable: true,
  68584. configurable: true
  68585. });
  68586. // Methods
  68587. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68588. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68589. this._baseMatrix = matrix.clone();
  68590. this._localMatrix = matrix.clone();
  68591. this._skeleton._markAsDirty();
  68592. if (updateDifferenceMatrix) {
  68593. this._updateDifferenceMatrix();
  68594. }
  68595. };
  68596. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68597. if (!rootMatrix) {
  68598. rootMatrix = this._baseMatrix;
  68599. }
  68600. if (this._parent) {
  68601. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68602. }
  68603. else {
  68604. this._absoluteTransform.copyFrom(rootMatrix);
  68605. }
  68606. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68607. for (var index = 0; index < this.children.length; index++) {
  68608. this.children[index]._updateDifferenceMatrix();
  68609. }
  68610. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68611. };
  68612. Bone.prototype.markAsDirty = function () {
  68613. this._currentRenderId++;
  68614. this._skeleton._markAsDirty();
  68615. };
  68616. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68617. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68618. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68619. // all animation may be coming from a library skeleton, so may need to create animation
  68620. if (this.animations.length === 0) {
  68621. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68622. this.animations[0].setKeys([]);
  68623. }
  68624. // get animation info / verify there is such a range from the source bone
  68625. var sourceRange = source.animations[0].getRange(rangeName);
  68626. if (!sourceRange) {
  68627. return false;
  68628. }
  68629. var from = sourceRange.from;
  68630. var to = sourceRange.to;
  68631. var sourceKeys = source.animations[0].getKeys();
  68632. // rescaling prep
  68633. var sourceBoneLength = source.length;
  68634. var sourceParent = source.getParent();
  68635. var parent = this.getParent();
  68636. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68637. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68638. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68639. var destKeys = this.animations[0].getKeys();
  68640. // loop vars declaration
  68641. var orig;
  68642. var origTranslation;
  68643. var mat;
  68644. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68645. orig = sourceKeys[key];
  68646. if (orig.frame >= from && orig.frame <= to) {
  68647. if (rescaleAsRequired) {
  68648. mat = orig.value.clone();
  68649. // scale based on parent ratio, when bone has parent
  68650. if (parentScalingReqd) {
  68651. origTranslation = mat.getTranslation();
  68652. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68653. // scale based on skeleton dimension ratio when root bone, and value is passed
  68654. }
  68655. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68656. origTranslation = mat.getTranslation();
  68657. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68658. // use original when root bone, and no data for skelDimensionsRatio
  68659. }
  68660. else {
  68661. mat = orig.value;
  68662. }
  68663. }
  68664. else {
  68665. mat = orig.value;
  68666. }
  68667. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68668. }
  68669. }
  68670. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68671. return true;
  68672. };
  68673. /**
  68674. * Translate the bone in local or world space.
  68675. * @param vec The amount to translate the bone.
  68676. * @param space The space that the translation is in.
  68677. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68678. */
  68679. Bone.prototype.translate = function (vec, space, mesh) {
  68680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68681. var lm = this.getLocalMatrix();
  68682. if (space == BABYLON.Space.LOCAL) {
  68683. lm.m[12] += vec.x;
  68684. lm.m[13] += vec.y;
  68685. lm.m[14] += vec.z;
  68686. }
  68687. else {
  68688. var wm = null;
  68689. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68690. if (mesh) {
  68691. wm = mesh.getWorldMatrix();
  68692. }
  68693. this._skeleton.computeAbsoluteTransforms();
  68694. var tmat = Bone._tmpMats[0];
  68695. var tvec = Bone._tmpVecs[0];
  68696. if (this._parent) {
  68697. if (mesh && wm) {
  68698. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68699. tmat.multiplyToRef(wm, tmat);
  68700. }
  68701. else {
  68702. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68703. }
  68704. }
  68705. tmat.m[12] = 0;
  68706. tmat.m[13] = 0;
  68707. tmat.m[14] = 0;
  68708. tmat.invert();
  68709. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68710. lm.m[12] += tvec.x;
  68711. lm.m[13] += tvec.y;
  68712. lm.m[14] += tvec.z;
  68713. }
  68714. this.markAsDirty();
  68715. };
  68716. /**
  68717. * Set the postion of the bone in local or world space.
  68718. * @param position The position to set the bone.
  68719. * @param space The space that the position is in.
  68720. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68721. */
  68722. Bone.prototype.setPosition = function (position, space, mesh) {
  68723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68724. var lm = this.getLocalMatrix();
  68725. if (space == BABYLON.Space.LOCAL) {
  68726. lm.m[12] = position.x;
  68727. lm.m[13] = position.y;
  68728. lm.m[14] = position.z;
  68729. }
  68730. else {
  68731. var wm = null;
  68732. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68733. if (mesh) {
  68734. wm = mesh.getWorldMatrix();
  68735. }
  68736. this._skeleton.computeAbsoluteTransforms();
  68737. var tmat = Bone._tmpMats[0];
  68738. var vec = Bone._tmpVecs[0];
  68739. if (this._parent) {
  68740. if (mesh && wm) {
  68741. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68742. tmat.multiplyToRef(wm, tmat);
  68743. }
  68744. else {
  68745. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68746. }
  68747. }
  68748. tmat.invert();
  68749. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68750. lm.m[12] = vec.x;
  68751. lm.m[13] = vec.y;
  68752. lm.m[14] = vec.z;
  68753. }
  68754. this.markAsDirty();
  68755. };
  68756. /**
  68757. * Set the absolute postion of the bone (world space).
  68758. * @param position The position to set the bone.
  68759. * @param mesh The mesh that this bone is attached to.
  68760. */
  68761. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68762. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68763. };
  68764. /**
  68765. * Set the scale of the bone on the x, y and z axes.
  68766. * @param x The scale of the bone on the x axis.
  68767. * @param x The scale of the bone on the y axis.
  68768. * @param z The scale of the bone on the z axis.
  68769. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68770. */
  68771. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68772. if (scaleChildren === void 0) { scaleChildren = false; }
  68773. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68774. if (!scaleChildren) {
  68775. this._negateScaleChildren.x = 1 / x;
  68776. this._negateScaleChildren.y = 1 / y;
  68777. this._negateScaleChildren.z = 1 / z;
  68778. }
  68779. this._syncScaleVector();
  68780. }
  68781. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68782. };
  68783. /**
  68784. * Scale the bone on the x, y and z axes.
  68785. * @param x The amount to scale the bone on the x axis.
  68786. * @param x The amount to scale the bone on the y axis.
  68787. * @param z The amount to scale the bone on the z axis.
  68788. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68789. */
  68790. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68791. if (scaleChildren === void 0) { scaleChildren = false; }
  68792. var locMat = this.getLocalMatrix();
  68793. var origLocMat = Bone._tmpMats[0];
  68794. origLocMat.copyFrom(locMat);
  68795. var origLocMatInv = Bone._tmpMats[1];
  68796. origLocMatInv.copyFrom(origLocMat);
  68797. origLocMatInv.invert();
  68798. var scaleMat = Bone._tmpMats[2];
  68799. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68800. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68801. this._scaleVector.x *= x;
  68802. this._scaleVector.y *= y;
  68803. this._scaleVector.z *= z;
  68804. locMat.multiplyToRef(origLocMatInv, locMat);
  68805. locMat.multiplyToRef(scaleMat, locMat);
  68806. locMat.multiplyToRef(origLocMat, locMat);
  68807. var parent = this.getParent();
  68808. if (parent) {
  68809. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68810. }
  68811. else {
  68812. this.getAbsoluteTransform().copyFrom(locMat);
  68813. }
  68814. var len = this.children.length;
  68815. scaleMat.invert();
  68816. for (var i = 0; i < len; i++) {
  68817. var child = this.children[i];
  68818. var cm = child.getLocalMatrix();
  68819. cm.multiplyToRef(scaleMat, cm);
  68820. var lm = child.getLocalMatrix();
  68821. lm.m[12] *= x;
  68822. lm.m[13] *= y;
  68823. lm.m[14] *= z;
  68824. }
  68825. this.computeAbsoluteTransforms();
  68826. if (scaleChildren) {
  68827. for (var i = 0; i < len; i++) {
  68828. this.children[i].scale(x, y, z, scaleChildren);
  68829. }
  68830. }
  68831. this.markAsDirty();
  68832. };
  68833. /**
  68834. * Set the yaw, pitch, and roll of the bone in local or world space.
  68835. * @param yaw The rotation of the bone on the y axis.
  68836. * @param pitch The rotation of the bone on the x axis.
  68837. * @param roll The rotation of the bone on the z axis.
  68838. * @param space The space that the axes of rotation are in.
  68839. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68840. */
  68841. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68842. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68843. var rotMat = Bone._tmpMats[0];
  68844. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68845. var rotMatInv = Bone._tmpMats[1];
  68846. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68847. rotMatInv.multiplyToRef(rotMat, rotMat);
  68848. this._rotateWithMatrix(rotMat, space, mesh);
  68849. };
  68850. /**
  68851. * Rotate the bone on an axis in local or world space.
  68852. * @param axis The axis to rotate the bone on.
  68853. * @param amount The amount to rotate the bone.
  68854. * @param space The space that the axis is in.
  68855. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68856. */
  68857. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68859. var rmat = Bone._tmpMats[0];
  68860. rmat.m[12] = 0;
  68861. rmat.m[13] = 0;
  68862. rmat.m[14] = 0;
  68863. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68864. this._rotateWithMatrix(rmat, space, mesh);
  68865. };
  68866. /**
  68867. * Set the rotation of the bone to a particular axis angle in local or world space.
  68868. * @param axis The axis to rotate the bone on.
  68869. * @param angle The angle that the bone should be rotated to.
  68870. * @param space The space that the axis is in.
  68871. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68872. */
  68873. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68874. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68875. var rotMat = Bone._tmpMats[0];
  68876. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68877. var rotMatInv = Bone._tmpMats[1];
  68878. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68879. rotMatInv.multiplyToRef(rotMat, rotMat);
  68880. this._rotateWithMatrix(rotMat, space, mesh);
  68881. };
  68882. /**
  68883. * Set the euler rotation of the bone in local of world space.
  68884. * @param rotation The euler rotation that the bone should be set to.
  68885. * @param space The space that the rotation is in.
  68886. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68887. */
  68888. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68889. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68890. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68891. };
  68892. /**
  68893. * Set the quaternion rotation of the bone in local of world space.
  68894. * @param quat The quaternion rotation that the bone should be set to.
  68895. * @param space The space that the rotation is in.
  68896. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68897. */
  68898. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68899. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68900. var rotMatInv = Bone._tmpMats[0];
  68901. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68902. var rotMat = Bone._tmpMats[1];
  68903. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68904. rotMatInv.multiplyToRef(rotMat, rotMat);
  68905. this._rotateWithMatrix(rotMat, space, mesh);
  68906. };
  68907. /**
  68908. * Set the rotation matrix of the bone in local of world space.
  68909. * @param rotMat The rotation matrix that the bone should be set to.
  68910. * @param space The space that the rotation is in.
  68911. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68912. */
  68913. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  68914. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68915. var rotMatInv = Bone._tmpMats[0];
  68916. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68917. var rotMat2 = Bone._tmpMats[1];
  68918. rotMat2.copyFrom(rotMat);
  68919. rotMatInv.multiplyToRef(rotMat, rotMat2);
  68920. this._rotateWithMatrix(rotMat2, space, mesh);
  68921. };
  68922. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  68923. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68924. var lmat = this.getLocalMatrix();
  68925. var lx = lmat.m[12];
  68926. var ly = lmat.m[13];
  68927. var lz = lmat.m[14];
  68928. var parent = this.getParent();
  68929. var parentScale = Bone._tmpMats[3];
  68930. var parentScaleInv = Bone._tmpMats[4];
  68931. if (parent) {
  68932. if (space == BABYLON.Space.WORLD) {
  68933. if (mesh) {
  68934. parentScale.copyFrom(mesh.getWorldMatrix());
  68935. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  68936. }
  68937. else {
  68938. parentScale.copyFrom(parent.getAbsoluteTransform());
  68939. }
  68940. }
  68941. else {
  68942. parentScale = parent._scaleMatrix;
  68943. }
  68944. parentScaleInv.copyFrom(parentScale);
  68945. parentScaleInv.invert();
  68946. lmat.multiplyToRef(parentScale, lmat);
  68947. lmat.multiplyToRef(rmat, lmat);
  68948. lmat.multiplyToRef(parentScaleInv, lmat);
  68949. }
  68950. else {
  68951. if (space == BABYLON.Space.WORLD && mesh) {
  68952. parentScale.copyFrom(mesh.getWorldMatrix());
  68953. parentScaleInv.copyFrom(parentScale);
  68954. parentScaleInv.invert();
  68955. lmat.multiplyToRef(parentScale, lmat);
  68956. lmat.multiplyToRef(rmat, lmat);
  68957. lmat.multiplyToRef(parentScaleInv, lmat);
  68958. }
  68959. else {
  68960. lmat.multiplyToRef(rmat, lmat);
  68961. }
  68962. }
  68963. lmat.m[12] = lx;
  68964. lmat.m[13] = ly;
  68965. lmat.m[14] = lz;
  68966. this.computeAbsoluteTransforms();
  68967. this.markAsDirty();
  68968. };
  68969. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  68970. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68971. if (space == BABYLON.Space.WORLD) {
  68972. var scaleMatrix = Bone._tmpMats[2];
  68973. scaleMatrix.copyFrom(this._scaleMatrix);
  68974. rotMatInv.copyFrom(this.getAbsoluteTransform());
  68975. if (mesh) {
  68976. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  68977. var meshScale = Bone._tmpMats[3];
  68978. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  68979. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  68980. }
  68981. rotMatInv.invert();
  68982. scaleMatrix.m[0] *= this._scalingDeterminant;
  68983. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68984. }
  68985. else {
  68986. rotMatInv.copyFrom(this.getLocalMatrix());
  68987. rotMatInv.invert();
  68988. var scaleMatrix = Bone._tmpMats[2];
  68989. scaleMatrix.copyFrom(this._scaleMatrix);
  68990. if (this._parent) {
  68991. var pscaleMatrix = Bone._tmpMats[3];
  68992. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  68993. pscaleMatrix.invert();
  68994. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  68995. }
  68996. else {
  68997. scaleMatrix.m[0] *= this._scalingDeterminant;
  68998. }
  68999. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69000. }
  69001. };
  69002. /**
  69003. * Get the scale of the bone
  69004. * @returns the scale of the bone
  69005. */
  69006. Bone.prototype.getScale = function () {
  69007. return this._scaleVector.clone();
  69008. };
  69009. /**
  69010. * Copy the scale of the bone to a vector3.
  69011. * @param result The vector3 to copy the scale to
  69012. */
  69013. Bone.prototype.getScaleToRef = function (result) {
  69014. result.copyFrom(this._scaleVector);
  69015. };
  69016. /**
  69017. * Get the position of the bone in local or world space.
  69018. * @param space The space that the returned position is in.
  69019. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69020. * @returns The position of the bone
  69021. */
  69022. Bone.prototype.getPosition = function (space, mesh) {
  69023. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69024. if (mesh === void 0) { mesh = null; }
  69025. var pos = BABYLON.Vector3.Zero();
  69026. this.getPositionToRef(space, mesh, pos);
  69027. return pos;
  69028. };
  69029. /**
  69030. * Copy the position of the bone to a vector3 in local or world space.
  69031. * @param space The space that the returned position is in.
  69032. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69033. * @param result The vector3 to copy the position to.
  69034. */
  69035. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  69036. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69037. if (space == BABYLON.Space.LOCAL) {
  69038. var lm = this.getLocalMatrix();
  69039. result.x = lm.m[12];
  69040. result.y = lm.m[13];
  69041. result.z = lm.m[14];
  69042. }
  69043. else {
  69044. var wm = null;
  69045. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69046. if (mesh) {
  69047. wm = mesh.getWorldMatrix();
  69048. }
  69049. this._skeleton.computeAbsoluteTransforms();
  69050. var tmat = Bone._tmpMats[0];
  69051. if (mesh && wm) {
  69052. tmat.copyFrom(this.getAbsoluteTransform());
  69053. tmat.multiplyToRef(wm, tmat);
  69054. }
  69055. else {
  69056. tmat = this.getAbsoluteTransform();
  69057. }
  69058. result.x = tmat.m[12];
  69059. result.y = tmat.m[13];
  69060. result.z = tmat.m[14];
  69061. }
  69062. };
  69063. /**
  69064. * Get the absolute position of the bone (world space).
  69065. * @param mesh The mesh that this bone is attached to.
  69066. * @returns The absolute position of the bone
  69067. */
  69068. Bone.prototype.getAbsolutePosition = function (mesh) {
  69069. if (mesh === void 0) { mesh = null; }
  69070. var pos = BABYLON.Vector3.Zero();
  69071. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69072. return pos;
  69073. };
  69074. /**
  69075. * Copy the absolute position of the bone (world space) to the result param.
  69076. * @param mesh The mesh that this bone is attached to.
  69077. * @param result The vector3 to copy the absolute position to.
  69078. */
  69079. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69080. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69081. };
  69082. /**
  69083. * Compute the absolute transforms of this bone and its children.
  69084. */
  69085. Bone.prototype.computeAbsoluteTransforms = function () {
  69086. if (this._parent) {
  69087. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69088. }
  69089. else {
  69090. this._absoluteTransform.copyFrom(this._localMatrix);
  69091. var poseMatrix = this._skeleton.getPoseMatrix();
  69092. if (poseMatrix) {
  69093. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69094. }
  69095. }
  69096. var children = this.children;
  69097. var len = children.length;
  69098. for (var i = 0; i < len; i++) {
  69099. children[i].computeAbsoluteTransforms();
  69100. }
  69101. };
  69102. Bone.prototype._syncScaleVector = function () {
  69103. var lm = this.getLocalMatrix();
  69104. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69105. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69106. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69107. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69108. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69109. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69110. this._scaleVector.x = xs * Math.sqrt(xsq);
  69111. this._scaleVector.y = ys * Math.sqrt(ysq);
  69112. this._scaleVector.z = zs * Math.sqrt(zsq);
  69113. if (this._parent) {
  69114. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69115. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69116. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69117. }
  69118. 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);
  69119. };
  69120. /**
  69121. * Get the world direction from an axis that is in the local space of the bone.
  69122. * @param localAxis The local direction that is used to compute the world direction.
  69123. * @param mesh The mesh that this bone is attached to.
  69124. * @returns The world direction
  69125. */
  69126. Bone.prototype.getDirection = function (localAxis, mesh) {
  69127. if (mesh === void 0) { mesh = null; }
  69128. var result = BABYLON.Vector3.Zero();
  69129. this.getDirectionToRef(localAxis, mesh, result);
  69130. return result;
  69131. };
  69132. /**
  69133. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69134. * @param localAxis The local direction that is used to compute the world direction.
  69135. * @param mesh The mesh that this bone is attached to.
  69136. * @param result The vector3 that the world direction will be copied to.
  69137. */
  69138. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69139. if (mesh === void 0) { mesh = null; }
  69140. var wm = null;
  69141. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69142. if (mesh) {
  69143. wm = mesh.getWorldMatrix();
  69144. }
  69145. this._skeleton.computeAbsoluteTransforms();
  69146. var mat = Bone._tmpMats[0];
  69147. mat.copyFrom(this.getAbsoluteTransform());
  69148. if (mesh && wm) {
  69149. mat.multiplyToRef(wm, mat);
  69150. }
  69151. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69152. result.normalize();
  69153. };
  69154. /**
  69155. * Get the euler rotation of the bone in local or world space.
  69156. * @param space The space that the rotation should be in.
  69157. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69158. * @returns The euler rotation
  69159. */
  69160. Bone.prototype.getRotation = function (space, mesh) {
  69161. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69162. if (mesh === void 0) { mesh = null; }
  69163. var result = BABYLON.Vector3.Zero();
  69164. this.getRotationToRef(space, mesh, result);
  69165. return result;
  69166. };
  69167. /**
  69168. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69169. * @param space The space that the rotation should be in.
  69170. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69171. * @param result The vector3 that the rotation should be copied to.
  69172. */
  69173. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69174. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69175. if (mesh === void 0) { mesh = null; }
  69176. var quat = Bone._tmpQuat;
  69177. this.getRotationQuaternionToRef(space, mesh, quat);
  69178. quat.toEulerAnglesToRef(result);
  69179. };
  69180. /**
  69181. * Get the quaternion rotation of the bone in either local or world space.
  69182. * @param space The space that the rotation should be in.
  69183. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69184. * @returns The quaternion rotation
  69185. */
  69186. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69188. if (mesh === void 0) { mesh = null; }
  69189. var result = BABYLON.Quaternion.Identity();
  69190. this.getRotationQuaternionToRef(space, mesh, result);
  69191. return result;
  69192. };
  69193. /**
  69194. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69195. * @param space The space that the rotation should be in.
  69196. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69197. * @param result The quaternion that the rotation should be copied to.
  69198. */
  69199. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69200. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69201. if (mesh === void 0) { mesh = null; }
  69202. if (space == BABYLON.Space.LOCAL) {
  69203. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69204. }
  69205. else {
  69206. var mat = Bone._tmpMats[0];
  69207. var amat = this.getAbsoluteTransform();
  69208. if (mesh) {
  69209. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69210. }
  69211. else {
  69212. mat.copyFrom(amat);
  69213. }
  69214. mat.m[0] *= this._scalingDeterminant;
  69215. mat.m[1] *= this._scalingDeterminant;
  69216. mat.m[2] *= this._scalingDeterminant;
  69217. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69218. }
  69219. };
  69220. /**
  69221. * Get the rotation matrix of the bone in local or world space.
  69222. * @param space The space that the rotation should be in.
  69223. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69224. * @returns The rotation matrix
  69225. */
  69226. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69227. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69228. var result = BABYLON.Matrix.Identity();
  69229. this.getRotationMatrixToRef(space, mesh, result);
  69230. return result;
  69231. };
  69232. /**
  69233. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69234. * @param space The space that the rotation should be in.
  69235. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69236. * @param result The quaternion that the rotation should be copied to.
  69237. */
  69238. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69239. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69240. if (space == BABYLON.Space.LOCAL) {
  69241. this.getLocalMatrix().getRotationMatrixToRef(result);
  69242. }
  69243. else {
  69244. var mat = Bone._tmpMats[0];
  69245. var amat = this.getAbsoluteTransform();
  69246. if (mesh) {
  69247. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69248. }
  69249. else {
  69250. mat.copyFrom(amat);
  69251. }
  69252. mat.m[0] *= this._scalingDeterminant;
  69253. mat.m[1] *= this._scalingDeterminant;
  69254. mat.m[2] *= this._scalingDeterminant;
  69255. mat.getRotationMatrixToRef(result);
  69256. }
  69257. };
  69258. /**
  69259. * Get the world position of a point that is in the local space of the bone.
  69260. * @param position The local position
  69261. * @param mesh The mesh that this bone is attached to.
  69262. * @returns The world position
  69263. */
  69264. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69265. if (mesh === void 0) { mesh = null; }
  69266. var result = BABYLON.Vector3.Zero();
  69267. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69268. return result;
  69269. };
  69270. /**
  69271. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69272. * @param position The local position
  69273. * @param mesh The mesh that this bone is attached to.
  69274. * @param result The vector3 that the world position should be copied to.
  69275. */
  69276. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69277. if (mesh === void 0) { mesh = null; }
  69278. var wm = null;
  69279. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69280. if (mesh) {
  69281. wm = mesh.getWorldMatrix();
  69282. }
  69283. this._skeleton.computeAbsoluteTransforms();
  69284. var tmat = Bone._tmpMats[0];
  69285. if (mesh && wm) {
  69286. tmat.copyFrom(this.getAbsoluteTransform());
  69287. tmat.multiplyToRef(wm, tmat);
  69288. }
  69289. else {
  69290. tmat = this.getAbsoluteTransform();
  69291. }
  69292. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69293. };
  69294. /**
  69295. * Get the local position of a point that is in world space.
  69296. * @param position The world position
  69297. * @param mesh The mesh that this bone is attached to.
  69298. * @returns The local position
  69299. */
  69300. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69301. if (mesh === void 0) { mesh = null; }
  69302. var result = BABYLON.Vector3.Zero();
  69303. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69304. return result;
  69305. };
  69306. /**
  69307. * Get the local position of a point that is in world space and copy it to the result param.
  69308. * @param position The world position
  69309. * @param mesh The mesh that this bone is attached to.
  69310. * @param result The vector3 that the local position should be copied to.
  69311. */
  69312. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69313. if (mesh === void 0) { mesh = null; }
  69314. var wm = null;
  69315. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69316. if (mesh) {
  69317. wm = mesh.getWorldMatrix();
  69318. }
  69319. this._skeleton.computeAbsoluteTransforms();
  69320. var tmat = Bone._tmpMats[0];
  69321. tmat.copyFrom(this.getAbsoluteTransform());
  69322. if (mesh && wm) {
  69323. tmat.multiplyToRef(wm, tmat);
  69324. }
  69325. tmat.invert();
  69326. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69327. };
  69328. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69329. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69330. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69331. return Bone;
  69332. }(BABYLON.Node));
  69333. BABYLON.Bone = Bone;
  69334. })(BABYLON || (BABYLON = {}));
  69335. //# sourceMappingURL=babylon.bone.js.map
  69336. var BABYLON;
  69337. (function (BABYLON) {
  69338. var BoneIKController = /** @class */ (function () {
  69339. function BoneIKController(mesh, bone, options) {
  69340. this.targetPosition = BABYLON.Vector3.Zero();
  69341. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69342. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69343. this.poleAngle = 0;
  69344. this.slerpAmount = 1;
  69345. this._bone1Quat = BABYLON.Quaternion.Identity();
  69346. this._bone1Mat = BABYLON.Matrix.Identity();
  69347. this._bone2Ang = Math.PI;
  69348. this._maxAngle = Math.PI;
  69349. this._rightHandedSystem = false;
  69350. this._bendAxis = BABYLON.Vector3.Right();
  69351. this._slerping = false;
  69352. this._adjustRoll = 0;
  69353. this._bone2 = bone;
  69354. this._bone1 = bone.getParent();
  69355. if (!this._bone1) {
  69356. return;
  69357. }
  69358. this.mesh = mesh;
  69359. var bonePos = bone.getPosition();
  69360. if (bone.getAbsoluteTransform().determinant() > 0) {
  69361. this._rightHandedSystem = true;
  69362. this._bendAxis.x = 0;
  69363. this._bendAxis.y = 0;
  69364. this._bendAxis.z = -1;
  69365. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69366. this._adjustRoll = Math.PI * .5;
  69367. this._bendAxis.z = 1;
  69368. }
  69369. }
  69370. if (this._bone1.length) {
  69371. var boneScale1 = this._bone1.getScale();
  69372. var boneScale2 = this._bone2.getScale();
  69373. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69374. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69375. }
  69376. else if (this._bone1.children[0]) {
  69377. mesh.computeWorldMatrix(true);
  69378. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69379. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69380. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69381. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69382. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69383. }
  69384. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69385. this.maxAngle = Math.PI;
  69386. if (options) {
  69387. if (options.targetMesh) {
  69388. this.targetMesh = options.targetMesh;
  69389. this.targetMesh.computeWorldMatrix(true);
  69390. }
  69391. if (options.poleTargetMesh) {
  69392. this.poleTargetMesh = options.poleTargetMesh;
  69393. this.poleTargetMesh.computeWorldMatrix(true);
  69394. }
  69395. else if (options.poleTargetBone) {
  69396. this.poleTargetBone = options.poleTargetBone;
  69397. }
  69398. else if (this._bone1.getParent()) {
  69399. this.poleTargetBone = this._bone1.getParent();
  69400. }
  69401. if (options.poleTargetLocalOffset) {
  69402. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69403. }
  69404. if (options.poleAngle) {
  69405. this.poleAngle = options.poleAngle;
  69406. }
  69407. if (options.bendAxis) {
  69408. this._bendAxis.copyFrom(options.bendAxis);
  69409. }
  69410. if (options.maxAngle) {
  69411. this.maxAngle = options.maxAngle;
  69412. }
  69413. if (options.slerpAmount) {
  69414. this.slerpAmount = options.slerpAmount;
  69415. }
  69416. }
  69417. }
  69418. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69419. get: function () {
  69420. return this._maxAngle;
  69421. },
  69422. set: function (value) {
  69423. this._setMaxAngle(value);
  69424. },
  69425. enumerable: true,
  69426. configurable: true
  69427. });
  69428. BoneIKController.prototype._setMaxAngle = function (ang) {
  69429. if (ang < 0) {
  69430. ang = 0;
  69431. }
  69432. if (ang > Math.PI || ang == undefined) {
  69433. ang = Math.PI;
  69434. }
  69435. this._maxAngle = ang;
  69436. var a = this._bone1Length;
  69437. var b = this._bone2Length;
  69438. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69439. };
  69440. BoneIKController.prototype.update = function () {
  69441. var bone1 = this._bone1;
  69442. if (!bone1) {
  69443. return;
  69444. }
  69445. var target = this.targetPosition;
  69446. var poleTarget = this.poleTargetPosition;
  69447. var mat1 = BoneIKController._tmpMats[0];
  69448. var mat2 = BoneIKController._tmpMats[1];
  69449. if (this.targetMesh) {
  69450. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69451. }
  69452. if (this.poleTargetBone) {
  69453. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69454. }
  69455. else if (this.poleTargetMesh) {
  69456. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69457. }
  69458. var bonePos = BoneIKController._tmpVecs[0];
  69459. var zaxis = BoneIKController._tmpVecs[1];
  69460. var xaxis = BoneIKController._tmpVecs[2];
  69461. var yaxis = BoneIKController._tmpVecs[3];
  69462. var upAxis = BoneIKController._tmpVecs[4];
  69463. var _tmpQuat = BoneIKController._tmpQuat;
  69464. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69465. poleTarget.subtractToRef(bonePos, upAxis);
  69466. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69467. upAxis.y = 1;
  69468. }
  69469. else {
  69470. upAxis.normalize();
  69471. }
  69472. target.subtractToRef(bonePos, yaxis);
  69473. yaxis.normalize();
  69474. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69475. zaxis.normalize();
  69476. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69477. xaxis.normalize();
  69478. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69479. var a = this._bone1Length;
  69480. var b = this._bone2Length;
  69481. var c = BABYLON.Vector3.Distance(bonePos, target);
  69482. if (this._maxReach > 0) {
  69483. c = Math.min(this._maxReach, c);
  69484. }
  69485. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69486. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69487. if (acosa > 1) {
  69488. acosa = 1;
  69489. }
  69490. if (acosb > 1) {
  69491. acosb = 1;
  69492. }
  69493. if (acosa < -1) {
  69494. acosa = -1;
  69495. }
  69496. if (acosb < -1) {
  69497. acosb = -1;
  69498. }
  69499. var angA = Math.acos(acosa);
  69500. var angB = Math.acos(acosb);
  69501. var angC = -angA - angB;
  69502. if (this._rightHandedSystem) {
  69503. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69504. mat2.multiplyToRef(mat1, mat1);
  69505. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69506. mat2.multiplyToRef(mat1, mat1);
  69507. }
  69508. else {
  69509. var _tmpVec = BoneIKController._tmpVecs[5];
  69510. _tmpVec.copyFrom(this._bendAxis);
  69511. _tmpVec.x *= -1;
  69512. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69513. mat2.multiplyToRef(mat1, mat1);
  69514. }
  69515. if (this.poleAngle) {
  69516. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69517. mat1.multiplyToRef(mat2, mat1);
  69518. }
  69519. if (this._bone1) {
  69520. if (this.slerpAmount < 1) {
  69521. if (!this._slerping) {
  69522. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69523. }
  69524. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69525. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69526. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69527. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69528. this._slerping = true;
  69529. }
  69530. else {
  69531. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69532. this._bone1Mat.copyFrom(mat1);
  69533. this._slerping = false;
  69534. }
  69535. }
  69536. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69537. this._bone2Ang = angC;
  69538. };
  69539. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69540. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69541. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69542. return BoneIKController;
  69543. }());
  69544. BABYLON.BoneIKController = BoneIKController;
  69545. })(BABYLON || (BABYLON = {}));
  69546. //# sourceMappingURL=babylon.boneIKController.js.map
  69547. var BABYLON;
  69548. (function (BABYLON) {
  69549. var BoneLookController = /** @class */ (function () {
  69550. /**
  69551. * Create a BoneLookController
  69552. * @param mesh the mesh that the bone belongs to
  69553. * @param bone the bone that will be looking to the target
  69554. * @param target the target Vector3 to look at
  69555. * @param settings optional settings:
  69556. * - maxYaw: the maximum angle the bone will yaw to
  69557. * - minYaw: the minimum angle the bone will yaw to
  69558. * - maxPitch: the maximum angle the bone will pitch to
  69559. * - minPitch: the minimum angle the bone will yaw to
  69560. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69561. * - upAxis: the up axis of the coordinate system
  69562. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69563. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69564. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69565. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69566. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69567. * - adjustRoll: used to make an adjustment to the roll of the bone
  69568. **/
  69569. function BoneLookController(mesh, bone, target, options) {
  69570. /**
  69571. * The up axis of the coordinate system that is used when the bone is rotated.
  69572. */
  69573. this.upAxis = BABYLON.Vector3.Up();
  69574. /**
  69575. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69576. */
  69577. this.upAxisSpace = BABYLON.Space.LOCAL;
  69578. /**
  69579. * Used to make an adjustment to the yaw of the bone.
  69580. */
  69581. this.adjustYaw = 0;
  69582. /**
  69583. * Used to make an adjustment to the pitch of the bone.
  69584. */
  69585. this.adjustPitch = 0;
  69586. /**
  69587. * Used to make an adjustment to the roll of the bone.
  69588. */
  69589. this.adjustRoll = 0;
  69590. /**
  69591. * 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).
  69592. */
  69593. this.slerpAmount = 1;
  69594. this._boneQuat = BABYLON.Quaternion.Identity();
  69595. this._slerping = false;
  69596. this._firstFrameSkipped = false;
  69597. this._fowardAxis = BABYLON.Vector3.Forward();
  69598. this.mesh = mesh;
  69599. this.bone = bone;
  69600. this.target = target;
  69601. if (options) {
  69602. if (options.adjustYaw) {
  69603. this.adjustYaw = options.adjustYaw;
  69604. }
  69605. if (options.adjustPitch) {
  69606. this.adjustPitch = options.adjustPitch;
  69607. }
  69608. if (options.adjustRoll) {
  69609. this.adjustRoll = options.adjustRoll;
  69610. }
  69611. if (options.maxYaw != null) {
  69612. this.maxYaw = options.maxYaw;
  69613. }
  69614. else {
  69615. this.maxYaw = Math.PI;
  69616. }
  69617. if (options.minYaw != null) {
  69618. this.minYaw = options.minYaw;
  69619. }
  69620. else {
  69621. this.minYaw = -Math.PI;
  69622. }
  69623. if (options.maxPitch != null) {
  69624. this.maxPitch = options.maxPitch;
  69625. }
  69626. else {
  69627. this.maxPitch = Math.PI;
  69628. }
  69629. if (options.minPitch != null) {
  69630. this.minPitch = options.minPitch;
  69631. }
  69632. else {
  69633. this.minPitch = -Math.PI;
  69634. }
  69635. if (options.slerpAmount != null) {
  69636. this.slerpAmount = options.slerpAmount;
  69637. }
  69638. if (options.upAxis != null) {
  69639. this.upAxis = options.upAxis;
  69640. }
  69641. if (options.upAxisSpace != null) {
  69642. this.upAxisSpace = options.upAxisSpace;
  69643. }
  69644. if (options.yawAxis != null || options.pitchAxis != null) {
  69645. var newYawAxis = BABYLON.Axis.Y;
  69646. var newPitchAxis = BABYLON.Axis.X;
  69647. if (options.yawAxis != null) {
  69648. newYawAxis = options.yawAxis.clone();
  69649. newYawAxis.normalize();
  69650. }
  69651. if (options.pitchAxis != null) {
  69652. newPitchAxis = options.pitchAxis.clone();
  69653. newPitchAxis.normalize();
  69654. }
  69655. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69656. this._transformYawPitch = BABYLON.Matrix.Identity();
  69657. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69658. this._transformYawPitchInv = this._transformYawPitch.clone();
  69659. this._transformYawPitch.invert();
  69660. }
  69661. }
  69662. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69663. this.upAxisSpace = BABYLON.Space.LOCAL;
  69664. }
  69665. }
  69666. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69667. /**
  69668. * Get/set the minimum yaw angle that the bone can look to.
  69669. */
  69670. get: function () {
  69671. return this._minYaw;
  69672. },
  69673. set: function (value) {
  69674. this._minYaw = value;
  69675. this._minYawSin = Math.sin(value);
  69676. this._minYawCos = Math.cos(value);
  69677. if (this._maxYaw != null) {
  69678. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69679. this._yawRange = this._maxYaw - this._minYaw;
  69680. }
  69681. },
  69682. enumerable: true,
  69683. configurable: true
  69684. });
  69685. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69686. /**
  69687. * Get/set the maximum yaw angle that the bone can look to.
  69688. */
  69689. get: function () {
  69690. return this._maxYaw;
  69691. },
  69692. set: function (value) {
  69693. this._maxYaw = value;
  69694. this._maxYawSin = Math.sin(value);
  69695. this._maxYawCos = Math.cos(value);
  69696. if (this._minYaw != null) {
  69697. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69698. this._yawRange = this._maxYaw - this._minYaw;
  69699. }
  69700. },
  69701. enumerable: true,
  69702. configurable: true
  69703. });
  69704. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69705. /**
  69706. * Get/set the minimum pitch angle that the bone can look to.
  69707. */
  69708. get: function () {
  69709. return this._minPitch;
  69710. },
  69711. set: function (value) {
  69712. this._minPitch = value;
  69713. this._minPitchTan = Math.tan(value);
  69714. },
  69715. enumerable: true,
  69716. configurable: true
  69717. });
  69718. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69719. /**
  69720. * Get/set the maximum pitch angle that the bone can look to.
  69721. */
  69722. get: function () {
  69723. return this._maxPitch;
  69724. },
  69725. set: function (value) {
  69726. this._maxPitch = value;
  69727. this._maxPitchTan = Math.tan(value);
  69728. },
  69729. enumerable: true,
  69730. configurable: true
  69731. });
  69732. /**
  69733. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69734. */
  69735. BoneLookController.prototype.update = function () {
  69736. //skip the first frame when slerping so that the mesh rotation is correct
  69737. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69738. this._firstFrameSkipped = true;
  69739. return;
  69740. }
  69741. var bone = this.bone;
  69742. var bonePos = BoneLookController._tmpVecs[0];
  69743. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69744. var target = this.target;
  69745. var _tmpMat1 = BoneLookController._tmpMats[0];
  69746. var _tmpMat2 = BoneLookController._tmpMats[1];
  69747. var mesh = this.mesh;
  69748. var parentBone = bone.getParent();
  69749. var upAxis = BoneLookController._tmpVecs[1];
  69750. upAxis.copyFrom(this.upAxis);
  69751. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69752. if (this._transformYawPitch) {
  69753. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69754. }
  69755. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69756. }
  69757. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69758. mesh.getDirectionToRef(upAxis, upAxis);
  69759. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69760. upAxis.normalize();
  69761. }
  69762. }
  69763. var checkYaw = false;
  69764. var checkPitch = false;
  69765. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69766. checkYaw = true;
  69767. }
  69768. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69769. checkPitch = true;
  69770. }
  69771. if (checkYaw || checkPitch) {
  69772. var spaceMat = BoneLookController._tmpMats[2];
  69773. var spaceMatInv = BoneLookController._tmpMats[3];
  69774. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69775. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69776. }
  69777. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69778. spaceMat.copyFrom(mesh.getWorldMatrix());
  69779. }
  69780. else {
  69781. var forwardAxis = BoneLookController._tmpVecs[2];
  69782. forwardAxis.copyFrom(this._fowardAxis);
  69783. if (this._transformYawPitch) {
  69784. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69785. }
  69786. if (parentBone) {
  69787. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69788. }
  69789. else {
  69790. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69791. }
  69792. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69793. rightAxis.normalize();
  69794. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69795. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69796. }
  69797. spaceMat.invertToRef(spaceMatInv);
  69798. var xzlen = null;
  69799. if (checkPitch) {
  69800. var localTarget = BoneLookController._tmpVecs[3];
  69801. target.subtractToRef(bonePos, localTarget);
  69802. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69803. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69804. var pitch = Math.atan2(localTarget.y, xzlen);
  69805. var newPitch = pitch;
  69806. if (pitch > this._maxPitch) {
  69807. localTarget.y = this._maxPitchTan * xzlen;
  69808. newPitch = this._maxPitch;
  69809. }
  69810. else if (pitch < this._minPitch) {
  69811. localTarget.y = this._minPitchTan * xzlen;
  69812. newPitch = this._minPitch;
  69813. }
  69814. if (pitch != newPitch) {
  69815. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69816. localTarget.addInPlace(bonePos);
  69817. target = localTarget;
  69818. }
  69819. }
  69820. if (checkYaw) {
  69821. var localTarget = BoneLookController._tmpVecs[4];
  69822. target.subtractToRef(bonePos, localTarget);
  69823. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69824. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69825. var newYaw = yaw;
  69826. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69827. if (xzlen == null) {
  69828. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69829. }
  69830. if (this._yawRange > Math.PI) {
  69831. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69832. localTarget.z = this._maxYawCos * xzlen;
  69833. localTarget.x = this._maxYawSin * xzlen;
  69834. newYaw = this._maxYaw;
  69835. }
  69836. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69837. localTarget.z = this._minYawCos * xzlen;
  69838. localTarget.x = this._minYawSin * xzlen;
  69839. newYaw = this._minYaw;
  69840. }
  69841. }
  69842. else {
  69843. if (yaw > this._maxYaw) {
  69844. localTarget.z = this._maxYawCos * xzlen;
  69845. localTarget.x = this._maxYawSin * xzlen;
  69846. newYaw = this._maxYaw;
  69847. }
  69848. else if (yaw < this._minYaw) {
  69849. localTarget.z = this._minYawCos * xzlen;
  69850. localTarget.x = this._minYawSin * xzlen;
  69851. newYaw = this._minYaw;
  69852. }
  69853. }
  69854. }
  69855. if (this._slerping && this._yawRange > Math.PI) {
  69856. //are we going to be crossing into the min/max region?
  69857. var boneFwd = BoneLookController._tmpVecs[8];
  69858. boneFwd.copyFrom(BABYLON.Axis.Z);
  69859. if (this._transformYawPitch) {
  69860. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69861. }
  69862. var boneRotMat = BoneLookController._tmpMats[4];
  69863. this._boneQuat.toRotationMatrix(boneRotMat);
  69864. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69865. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69866. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69867. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69868. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69869. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69870. if (angBtwTar > angBtwMidYaw) {
  69871. if (xzlen == null) {
  69872. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69873. }
  69874. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69875. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69876. if (angBtwMin < angBtwMax) {
  69877. newYaw = boneYaw + Math.PI * .75;
  69878. localTarget.z = Math.cos(newYaw) * xzlen;
  69879. localTarget.x = Math.sin(newYaw) * xzlen;
  69880. }
  69881. else {
  69882. newYaw = boneYaw - Math.PI * .75;
  69883. localTarget.z = Math.cos(newYaw) * xzlen;
  69884. localTarget.x = Math.sin(newYaw) * xzlen;
  69885. }
  69886. }
  69887. }
  69888. if (yaw != newYaw) {
  69889. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69890. localTarget.addInPlace(bonePos);
  69891. target = localTarget;
  69892. }
  69893. }
  69894. }
  69895. var zaxis = BoneLookController._tmpVecs[5];
  69896. var xaxis = BoneLookController._tmpVecs[6];
  69897. var yaxis = BoneLookController._tmpVecs[7];
  69898. var _tmpQuat = BoneLookController._tmpQuat;
  69899. target.subtractToRef(bonePos, zaxis);
  69900. zaxis.normalize();
  69901. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69902. xaxis.normalize();
  69903. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69904. yaxis.normalize();
  69905. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69906. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69907. return;
  69908. }
  69909. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  69910. return;
  69911. }
  69912. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  69913. return;
  69914. }
  69915. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  69916. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  69917. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  69918. }
  69919. if (this.slerpAmount < 1) {
  69920. if (!this._slerping) {
  69921. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  69922. }
  69923. if (this._transformYawPitch) {
  69924. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69925. }
  69926. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  69927. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  69928. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  69929. this._slerping = true;
  69930. }
  69931. else {
  69932. if (this._transformYawPitch) {
  69933. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69934. }
  69935. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  69936. this._slerping = false;
  69937. }
  69938. };
  69939. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  69940. var angDiff = ang2 - ang1;
  69941. angDiff %= Math.PI * 2;
  69942. if (angDiff > Math.PI) {
  69943. angDiff -= Math.PI * 2;
  69944. }
  69945. else if (angDiff < -Math.PI) {
  69946. angDiff += Math.PI * 2;
  69947. }
  69948. return angDiff;
  69949. };
  69950. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  69951. ang1 %= (2 * Math.PI);
  69952. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69953. ang2 %= (2 * Math.PI);
  69954. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69955. var ab = 0;
  69956. if (ang1 < ang2) {
  69957. ab = ang2 - ang1;
  69958. }
  69959. else {
  69960. ab = ang1 - ang2;
  69961. }
  69962. if (ab > Math.PI) {
  69963. ab = Math.PI * 2 - ab;
  69964. }
  69965. return ab;
  69966. };
  69967. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  69968. ang %= (2 * Math.PI);
  69969. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  69970. ang1 %= (2 * Math.PI);
  69971. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69972. ang2 %= (2 * Math.PI);
  69973. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69974. if (ang1 < ang2) {
  69975. if (ang > ang1 && ang < ang2) {
  69976. return true;
  69977. }
  69978. }
  69979. else {
  69980. if (ang > ang2 && ang < ang1) {
  69981. return true;
  69982. }
  69983. }
  69984. return false;
  69985. };
  69986. 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()];
  69987. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  69988. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69989. return BoneLookController;
  69990. }());
  69991. BABYLON.BoneLookController = BoneLookController;
  69992. })(BABYLON || (BABYLON = {}));
  69993. //# sourceMappingURL=babylon.boneLookController.js.map
  69994. var BABYLON;
  69995. (function (BABYLON) {
  69996. var Skeleton = /** @class */ (function () {
  69997. function Skeleton(name, id, scene) {
  69998. this.name = name;
  69999. this.id = id;
  70000. this.bones = new Array();
  70001. this.needInitialSkinMatrix = false;
  70002. this._isDirty = true;
  70003. this._meshesWithPoseMatrix = new Array();
  70004. this._identity = BABYLON.Matrix.Identity();
  70005. this._ranges = {};
  70006. this._lastAbsoluteTransformsUpdateId = -1;
  70007. // Events
  70008. /**
  70009. * An event triggered before computing the skeleton's matrices
  70010. * @type {BABYLON.Observable}
  70011. */
  70012. this.onBeforeComputeObservable = new BABYLON.Observable();
  70013. this.bones = [];
  70014. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70015. scene.skeletons.push(this);
  70016. //make sure it will recalculate the matrix next time prepare is called.
  70017. this._isDirty = true;
  70018. }
  70019. // Members
  70020. Skeleton.prototype.getTransformMatrices = function (mesh) {
  70021. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  70022. return mesh._bonesTransformMatrices;
  70023. }
  70024. if (!this._transformMatrices) {
  70025. this.prepare();
  70026. }
  70027. return this._transformMatrices;
  70028. };
  70029. Skeleton.prototype.getScene = function () {
  70030. return this._scene;
  70031. };
  70032. // Methods
  70033. /**
  70034. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  70035. */
  70036. Skeleton.prototype.toString = function (fullDetails) {
  70037. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  70038. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  70039. if (fullDetails) {
  70040. ret += ", Ranges: {";
  70041. var first = true;
  70042. for (var name_1 in this._ranges) {
  70043. if (first) {
  70044. ret += ", ";
  70045. first = false;
  70046. }
  70047. ret += name_1;
  70048. }
  70049. ret += "}";
  70050. }
  70051. return ret;
  70052. };
  70053. /**
  70054. * Get bone's index searching by name
  70055. * @param {string} name is bone's name to search for
  70056. * @return {number} Indice of the bone. Returns -1 if not found
  70057. */
  70058. Skeleton.prototype.getBoneIndexByName = function (name) {
  70059. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  70060. if (this.bones[boneIndex].name === name) {
  70061. return boneIndex;
  70062. }
  70063. }
  70064. return -1;
  70065. };
  70066. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70067. // check name not already in use
  70068. if (!this._ranges[name]) {
  70069. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70070. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70071. if (this.bones[i].animations[0]) {
  70072. this.bones[i].animations[0].createRange(name, from, to);
  70073. }
  70074. }
  70075. }
  70076. };
  70077. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70078. if (deleteFrames === void 0) { deleteFrames = true; }
  70079. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70080. if (this.bones[i].animations[0]) {
  70081. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70082. }
  70083. }
  70084. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70085. };
  70086. Skeleton.prototype.getAnimationRange = function (name) {
  70087. return this._ranges[name];
  70088. };
  70089. /**
  70090. * Returns as an Array, all AnimationRanges defined on this skeleton
  70091. */
  70092. Skeleton.prototype.getAnimationRanges = function () {
  70093. var animationRanges = [];
  70094. var name;
  70095. var i = 0;
  70096. for (name in this._ranges) {
  70097. animationRanges[i] = this._ranges[name];
  70098. i++;
  70099. }
  70100. return animationRanges;
  70101. };
  70102. /**
  70103. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70104. */
  70105. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70106. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70107. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70108. return false;
  70109. }
  70110. var ret = true;
  70111. var frameOffset = this._getHighestAnimationFrame() + 1;
  70112. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70113. var boneDict = {};
  70114. var sourceBones = source.bones;
  70115. var nBones;
  70116. var i;
  70117. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70118. boneDict[sourceBones[i].name] = sourceBones[i];
  70119. }
  70120. if (this.bones.length !== sourceBones.length) {
  70121. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70122. ret = false;
  70123. }
  70124. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70125. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70126. var boneName = this.bones[i].name;
  70127. var sourceBone = boneDict[boneName];
  70128. if (sourceBone) {
  70129. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70130. }
  70131. else {
  70132. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70133. ret = false;
  70134. }
  70135. }
  70136. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70137. var range = source.getAnimationRange(name);
  70138. if (range) {
  70139. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70140. }
  70141. return ret;
  70142. };
  70143. Skeleton.prototype.returnToRest = function () {
  70144. for (var index = 0; index < this.bones.length; index++) {
  70145. this.bones[index].returnToRest();
  70146. }
  70147. };
  70148. Skeleton.prototype._getHighestAnimationFrame = function () {
  70149. var ret = 0;
  70150. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70151. if (this.bones[i].animations[0]) {
  70152. var highest = this.bones[i].animations[0].getHighestFrame();
  70153. if (ret < highest) {
  70154. ret = highest;
  70155. }
  70156. }
  70157. }
  70158. return ret;
  70159. };
  70160. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70161. var range = this.getAnimationRange(name);
  70162. if (!range) {
  70163. return null;
  70164. }
  70165. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70166. };
  70167. Skeleton.prototype._markAsDirty = function () {
  70168. this._isDirty = true;
  70169. };
  70170. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70171. this._meshesWithPoseMatrix.push(mesh);
  70172. };
  70173. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70174. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70175. if (index > -1) {
  70176. this._meshesWithPoseMatrix.splice(index, 1);
  70177. }
  70178. };
  70179. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70180. this.onBeforeComputeObservable.notifyObservers(this);
  70181. for (var index = 0; index < this.bones.length; index++) {
  70182. var bone = this.bones[index];
  70183. var parentBone = bone.getParent();
  70184. if (parentBone) {
  70185. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70186. }
  70187. else {
  70188. if (initialSkinMatrix) {
  70189. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70190. }
  70191. else {
  70192. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70193. }
  70194. }
  70195. if (bone._index !== -1) {
  70196. var mappedIndex = bone._index === null ? index : bone._index;
  70197. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70198. }
  70199. }
  70200. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70201. };
  70202. Skeleton.prototype.prepare = function () {
  70203. if (!this._isDirty) {
  70204. return;
  70205. }
  70206. if (this.needInitialSkinMatrix) {
  70207. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70208. var mesh = this._meshesWithPoseMatrix[index];
  70209. var poseMatrix = mesh.getPoseMatrix();
  70210. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70211. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70212. }
  70213. if (this._synchronizedWithMesh !== mesh) {
  70214. this._synchronizedWithMesh = mesh;
  70215. // Prepare bones
  70216. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70217. var bone = this.bones[boneIndex];
  70218. if (!bone.getParent()) {
  70219. var matrix = bone.getBaseMatrix();
  70220. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70221. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70222. }
  70223. }
  70224. }
  70225. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70226. }
  70227. }
  70228. else {
  70229. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70230. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70231. }
  70232. this._computeTransformMatrices(this._transformMatrices, null);
  70233. }
  70234. this._isDirty = false;
  70235. this._scene._activeBones.addCount(this.bones.length, false);
  70236. };
  70237. Skeleton.prototype.getAnimatables = function () {
  70238. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70239. this._animatables = [];
  70240. for (var index = 0; index < this.bones.length; index++) {
  70241. this._animatables.push(this.bones[index]);
  70242. }
  70243. }
  70244. return this._animatables;
  70245. };
  70246. Skeleton.prototype.clone = function (name, id) {
  70247. var result = new Skeleton(name, id || name, this._scene);
  70248. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70249. for (var index = 0; index < this.bones.length; index++) {
  70250. var source = this.bones[index];
  70251. var parentBone = null;
  70252. var parent_1 = source.getParent();
  70253. if (parent_1) {
  70254. var parentIndex = this.bones.indexOf(parent_1);
  70255. parentBone = result.bones[parentIndex];
  70256. }
  70257. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70258. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70259. }
  70260. if (this._ranges) {
  70261. result._ranges = {};
  70262. for (var rangeName in this._ranges) {
  70263. var range = this._ranges[rangeName];
  70264. if (range) {
  70265. result._ranges[rangeName] = range.clone();
  70266. }
  70267. }
  70268. }
  70269. this._isDirty = true;
  70270. return result;
  70271. };
  70272. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70273. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70274. this.bones.forEach(function (bone) {
  70275. bone.animations.forEach(function (animation) {
  70276. animation.enableBlending = true;
  70277. animation.blendingSpeed = blendingSpeed;
  70278. });
  70279. });
  70280. };
  70281. Skeleton.prototype.dispose = function () {
  70282. this._meshesWithPoseMatrix = [];
  70283. // Animations
  70284. this.getScene().stopAnimation(this);
  70285. // Remove from scene
  70286. this.getScene().removeSkeleton(this);
  70287. };
  70288. Skeleton.prototype.serialize = function () {
  70289. var serializationObject = {};
  70290. serializationObject.name = this.name;
  70291. serializationObject.id = this.id;
  70292. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70293. serializationObject.bones = [];
  70294. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70295. for (var index = 0; index < this.bones.length; index++) {
  70296. var bone = this.bones[index];
  70297. var parent_2 = bone.getParent();
  70298. var serializedBone = {
  70299. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70300. name: bone.name,
  70301. matrix: bone.getBaseMatrix().toArray(),
  70302. rest: bone.getRestPose().toArray()
  70303. };
  70304. serializationObject.bones.push(serializedBone);
  70305. if (bone.length) {
  70306. serializedBone.length = bone.length;
  70307. }
  70308. if (bone.animations && bone.animations.length > 0) {
  70309. serializedBone.animation = bone.animations[0].serialize();
  70310. }
  70311. serializationObject.ranges = [];
  70312. for (var name in this._ranges) {
  70313. var source = this._ranges[name];
  70314. if (!source) {
  70315. continue;
  70316. }
  70317. var range = {};
  70318. range.name = name;
  70319. range.from = source.from;
  70320. range.to = source.to;
  70321. serializationObject.ranges.push(range);
  70322. }
  70323. }
  70324. return serializationObject;
  70325. };
  70326. Skeleton.Parse = function (parsedSkeleton, scene) {
  70327. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70328. if (parsedSkeleton.dimensionsAtRest) {
  70329. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70330. }
  70331. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70332. var index;
  70333. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70334. var parsedBone = parsedSkeleton.bones[index];
  70335. var parentBone = null;
  70336. if (parsedBone.parentBoneIndex > -1) {
  70337. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70338. }
  70339. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70340. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70341. if (parsedBone.length) {
  70342. bone.length = parsedBone.length;
  70343. }
  70344. if (parsedBone.animation) {
  70345. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70346. }
  70347. }
  70348. // placed after bones, so createAnimationRange can cascade down
  70349. if (parsedSkeleton.ranges) {
  70350. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70351. var data = parsedSkeleton.ranges[index];
  70352. skeleton.createAnimationRange(data.name, data.from, data.to);
  70353. }
  70354. }
  70355. return skeleton;
  70356. };
  70357. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70358. if (forceUpdate === void 0) { forceUpdate = false; }
  70359. var renderId = this._scene.getRenderId();
  70360. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70361. this.bones[0].computeAbsoluteTransforms();
  70362. this._lastAbsoluteTransformsUpdateId = renderId;
  70363. }
  70364. };
  70365. Skeleton.prototype.getPoseMatrix = function () {
  70366. var poseMatrix = null;
  70367. if (this._meshesWithPoseMatrix.length > 0) {
  70368. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70369. }
  70370. return poseMatrix;
  70371. };
  70372. Skeleton.prototype.sortBones = function () {
  70373. var bones = new Array();
  70374. var visited = new Array(this.bones.length);
  70375. for (var index = 0; index < this.bones.length; index++) {
  70376. this._sortBones(index, bones, visited);
  70377. }
  70378. this.bones = bones;
  70379. };
  70380. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70381. if (visited[index]) {
  70382. return;
  70383. }
  70384. visited[index] = true;
  70385. var bone = this.bones[index];
  70386. if (bone._index === undefined) {
  70387. bone._index = index;
  70388. }
  70389. var parentBone = bone.getParent();
  70390. if (parentBone) {
  70391. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70392. }
  70393. bones.push(bone);
  70394. };
  70395. return Skeleton;
  70396. }());
  70397. BABYLON.Skeleton = Skeleton;
  70398. })(BABYLON || (BABYLON = {}));
  70399. //# sourceMappingURL=babylon.skeleton.js.map
  70400. var BABYLON;
  70401. (function (BABYLON) {
  70402. var SphericalPolynomial = /** @class */ (function () {
  70403. function SphericalPolynomial() {
  70404. this.x = BABYLON.Vector3.Zero();
  70405. this.y = BABYLON.Vector3.Zero();
  70406. this.z = BABYLON.Vector3.Zero();
  70407. this.xx = BABYLON.Vector3.Zero();
  70408. this.yy = BABYLON.Vector3.Zero();
  70409. this.zz = BABYLON.Vector3.Zero();
  70410. this.xy = BABYLON.Vector3.Zero();
  70411. this.yz = BABYLON.Vector3.Zero();
  70412. this.zx = BABYLON.Vector3.Zero();
  70413. }
  70414. SphericalPolynomial.prototype.addAmbient = function (color) {
  70415. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70416. this.xx = this.xx.add(colorVector);
  70417. this.yy = this.yy.add(colorVector);
  70418. this.zz = this.zz.add(colorVector);
  70419. };
  70420. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70421. var result = new SphericalPolynomial();
  70422. result.x = harmonics.L11.scale(1.02333);
  70423. result.y = harmonics.L1_1.scale(1.02333);
  70424. result.z = harmonics.L10.scale(1.02333);
  70425. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70426. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70427. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70428. result.yz = harmonics.L2_1.scale(0.858086);
  70429. result.zx = harmonics.L21.scale(0.858086);
  70430. result.xy = harmonics.L2_2.scale(0.858086);
  70431. result.scale(1.0 / Math.PI);
  70432. return result;
  70433. };
  70434. SphericalPolynomial.prototype.scale = function (scale) {
  70435. this.x = this.x.scale(scale);
  70436. this.y = this.y.scale(scale);
  70437. this.z = this.z.scale(scale);
  70438. this.xx = this.xx.scale(scale);
  70439. this.yy = this.yy.scale(scale);
  70440. this.zz = this.zz.scale(scale);
  70441. this.yz = this.yz.scale(scale);
  70442. this.zx = this.zx.scale(scale);
  70443. this.xy = this.xy.scale(scale);
  70444. };
  70445. return SphericalPolynomial;
  70446. }());
  70447. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70448. var SphericalHarmonics = /** @class */ (function () {
  70449. function SphericalHarmonics() {
  70450. this.L00 = BABYLON.Vector3.Zero();
  70451. this.L1_1 = BABYLON.Vector3.Zero();
  70452. this.L10 = BABYLON.Vector3.Zero();
  70453. this.L11 = BABYLON.Vector3.Zero();
  70454. this.L2_2 = BABYLON.Vector3.Zero();
  70455. this.L2_1 = BABYLON.Vector3.Zero();
  70456. this.L20 = BABYLON.Vector3.Zero();
  70457. this.L21 = BABYLON.Vector3.Zero();
  70458. this.L22 = BABYLON.Vector3.Zero();
  70459. }
  70460. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70461. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70462. var c = colorVector.scale(deltaSolidAngle);
  70463. this.L00 = this.L00.add(c.scale(0.282095));
  70464. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70465. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70466. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70467. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70468. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70469. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70470. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70471. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70472. };
  70473. SphericalHarmonics.prototype.scale = function (scale) {
  70474. this.L00 = this.L00.scale(scale);
  70475. this.L1_1 = this.L1_1.scale(scale);
  70476. this.L10 = this.L10.scale(scale);
  70477. this.L11 = this.L11.scale(scale);
  70478. this.L2_2 = this.L2_2.scale(scale);
  70479. this.L2_1 = this.L2_1.scale(scale);
  70480. this.L20 = this.L20.scale(scale);
  70481. this.L21 = this.L21.scale(scale);
  70482. this.L22 = this.L22.scale(scale);
  70483. };
  70484. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70485. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70486. //
  70487. // E_lm = A_l * L_lm
  70488. //
  70489. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70490. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70491. // the scaling factors are given in equation 9.
  70492. // Constant (Band 0)
  70493. this.L00 = this.L00.scale(3.141593);
  70494. // Linear (Band 1)
  70495. this.L1_1 = this.L1_1.scale(2.094395);
  70496. this.L10 = this.L10.scale(2.094395);
  70497. this.L11 = this.L11.scale(2.094395);
  70498. // Quadratic (Band 2)
  70499. this.L2_2 = this.L2_2.scale(0.785398);
  70500. this.L2_1 = this.L2_1.scale(0.785398);
  70501. this.L20 = this.L20.scale(0.785398);
  70502. this.L21 = this.L21.scale(0.785398);
  70503. this.L22 = this.L22.scale(0.785398);
  70504. };
  70505. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70506. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70507. // L = (1/pi) * E * rho
  70508. //
  70509. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70510. this.scale(1.0 / Math.PI);
  70511. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70512. // (The pixel shader must apply albedo after texture fetches, etc).
  70513. };
  70514. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70515. var result = new SphericalHarmonics();
  70516. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70517. result.L1_1 = polynomial.y.scale(0.977204);
  70518. result.L10 = polynomial.z.scale(0.977204);
  70519. result.L11 = polynomial.x.scale(0.977204);
  70520. result.L2_2 = polynomial.xy.scale(1.16538);
  70521. result.L2_1 = polynomial.yz.scale(1.16538);
  70522. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70523. result.L21 = polynomial.zx.scale(1.16538);
  70524. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70525. result.scale(Math.PI);
  70526. return result;
  70527. };
  70528. return SphericalHarmonics;
  70529. }());
  70530. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70531. })(BABYLON || (BABYLON = {}));
  70532. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70533. var BABYLON;
  70534. (function (BABYLON) {
  70535. var FileFaceOrientation = /** @class */ (function () {
  70536. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70537. this.name = name;
  70538. this.worldAxisForNormal = worldAxisForNormal;
  70539. this.worldAxisForFileX = worldAxisForFileX;
  70540. this.worldAxisForFileY = worldAxisForFileY;
  70541. }
  70542. return FileFaceOrientation;
  70543. }());
  70544. ;
  70545. /**
  70546. * Helper class dealing with the extraction of spherical polynomial dataArray
  70547. * from a cube map.
  70548. */
  70549. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70550. function CubeMapToSphericalPolynomialTools() {
  70551. }
  70552. /**
  70553. * Converts a texture to the according Spherical Polynomial data.
  70554. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70555. *
  70556. * @param texture The texture to extract the information from.
  70557. * @return The Spherical Polynomial data.
  70558. */
  70559. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70560. if (!texture.isCube) {
  70561. // Only supports cube Textures currently.
  70562. return null;
  70563. }
  70564. var size = texture.getSize().width;
  70565. var right = texture.readPixels(0);
  70566. var left = texture.readPixels(1);
  70567. var up;
  70568. var down;
  70569. if (texture.isRenderTarget) {
  70570. up = texture.readPixels(3);
  70571. down = texture.readPixels(2);
  70572. }
  70573. else {
  70574. up = texture.readPixels(2);
  70575. down = texture.readPixels(3);
  70576. }
  70577. var front = texture.readPixels(4);
  70578. var back = texture.readPixels(5);
  70579. var gammaSpace = texture.gammaSpace;
  70580. // Always read as RGBA.
  70581. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70582. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70583. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70584. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70585. }
  70586. var cubeInfo = {
  70587. size: size,
  70588. right: right,
  70589. left: left,
  70590. up: up,
  70591. down: down,
  70592. front: front,
  70593. back: back,
  70594. format: format,
  70595. type: type,
  70596. gammaSpace: gammaSpace,
  70597. };
  70598. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70599. };
  70600. /**
  70601. * Converts a cubemap to the according Spherical Polynomial data.
  70602. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70603. *
  70604. * @param cubeInfo The Cube map to extract the information from.
  70605. * @return The Spherical Polynomial data.
  70606. */
  70607. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70608. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70609. var totalSolidAngle = 0.0;
  70610. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70611. var du = 2.0 / cubeInfo.size;
  70612. var dv = du;
  70613. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70614. var minUV = du * 0.5 - 1.0;
  70615. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70616. var fileFace = this.FileFaces[faceIndex];
  70617. var dataArray = cubeInfo[fileFace.name];
  70618. var v = minUV;
  70619. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70620. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70621. // Because SP is still linear, so summation is fine in that basis.
  70622. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70623. for (var y = 0; y < cubeInfo.size; y++) {
  70624. var u = minUV;
  70625. for (var x = 0; x < cubeInfo.size; x++) {
  70626. // World direction (not normalised)
  70627. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70628. worldDirection.normalize();
  70629. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70630. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70631. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70632. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70633. // Handle Integer types.
  70634. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70635. r /= 255;
  70636. g /= 255;
  70637. b /= 255;
  70638. }
  70639. // Handle Gamma space textures.
  70640. if (cubeInfo.gammaSpace) {
  70641. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70642. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70643. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70644. }
  70645. var color = new BABYLON.Color3(r, g, b);
  70646. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70647. totalSolidAngle += deltaSolidAngle;
  70648. u += du;
  70649. }
  70650. v += dv;
  70651. }
  70652. }
  70653. // Solid angle for entire sphere is 4*pi
  70654. var sphereSolidAngle = 4.0 * Math.PI;
  70655. // Adjust the solid angle to allow for how many faces we processed.
  70656. var facesProcessed = 6.0;
  70657. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70658. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70659. // This is needed because the numerical integration over the cube uses a
  70660. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70661. // and also to compensate for accumulative error due to float precision in the summation.
  70662. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70663. sphericalHarmonics.scale(correctionFactor);
  70664. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70665. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70666. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70667. };
  70668. CubeMapToSphericalPolynomialTools.FileFaces = [
  70669. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70670. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70671. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70672. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70673. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70674. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70675. ];
  70676. return CubeMapToSphericalPolynomialTools;
  70677. }());
  70678. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70679. })(BABYLON || (BABYLON = {}));
  70680. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70681. var BABYLON;
  70682. (function (BABYLON) {
  70683. /**
  70684. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70685. */
  70686. var PanoramaToCubeMapTools = /** @class */ (function () {
  70687. function PanoramaToCubeMapTools() {
  70688. }
  70689. /**
  70690. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70691. *
  70692. * @param float32Array The source data.
  70693. * @param inputWidth The width of the input panorama.
  70694. * @param inputhHeight The height of the input panorama.
  70695. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70696. * @return The cubemap data
  70697. */
  70698. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70699. if (!float32Array) {
  70700. throw "ConvertPanoramaToCubemap: input cannot be null";
  70701. }
  70702. if (float32Array.length != inputWidth * inputHeight * 3) {
  70703. throw "ConvertPanoramaToCubemap: input size is wrong";
  70704. }
  70705. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70706. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70707. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70708. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70709. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70710. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70711. return {
  70712. front: textureFront,
  70713. back: textureBack,
  70714. left: textureLeft,
  70715. right: textureRight,
  70716. up: textureUp,
  70717. down: textureDown,
  70718. size: size,
  70719. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70720. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70721. gammaSpace: false,
  70722. };
  70723. };
  70724. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70725. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70726. var textureArray = new Float32Array(buffer);
  70727. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70728. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70729. var dy = 1 / texSize;
  70730. var fy = 0;
  70731. for (var y = 0; y < texSize; y++) {
  70732. var xv1 = faceData[0];
  70733. var xv2 = faceData[2];
  70734. for (var x = 0; x < texSize; x++) {
  70735. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70736. v.normalize();
  70737. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70738. // 3 channels per pixels
  70739. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70740. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70741. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70742. xv1 = xv1.add(rotDX1);
  70743. xv2 = xv2.add(rotDX2);
  70744. }
  70745. fy += dy;
  70746. }
  70747. return textureArray;
  70748. };
  70749. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70750. var theta = Math.atan2(vDir.z, vDir.x);
  70751. var phi = Math.acos(vDir.y);
  70752. while (theta < -Math.PI)
  70753. theta += 2 * Math.PI;
  70754. while (theta > Math.PI)
  70755. theta -= 2 * Math.PI;
  70756. var dx = theta / Math.PI;
  70757. var dy = phi / Math.PI;
  70758. // recenter.
  70759. dx = dx * 0.5 + 0.5;
  70760. var px = Math.round(dx * inputWidth);
  70761. if (px < 0)
  70762. px = 0;
  70763. else if (px >= inputWidth)
  70764. px = inputWidth - 1;
  70765. var py = Math.round(dy * inputHeight);
  70766. if (py < 0)
  70767. py = 0;
  70768. else if (py >= inputHeight)
  70769. py = inputHeight - 1;
  70770. var inputY = (inputHeight - py - 1);
  70771. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70772. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70773. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70774. return {
  70775. r: r,
  70776. g: g,
  70777. b: b
  70778. };
  70779. };
  70780. PanoramaToCubeMapTools.FACE_FRONT = [
  70781. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70782. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70783. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70784. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70785. ];
  70786. PanoramaToCubeMapTools.FACE_BACK = [
  70787. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70788. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70789. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70790. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70791. ];
  70792. PanoramaToCubeMapTools.FACE_RIGHT = [
  70793. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70794. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70795. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70796. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70797. ];
  70798. PanoramaToCubeMapTools.FACE_LEFT = [
  70799. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70800. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70801. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70802. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70803. ];
  70804. PanoramaToCubeMapTools.FACE_DOWN = [
  70805. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70806. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70807. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70808. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70809. ];
  70810. PanoramaToCubeMapTools.FACE_UP = [
  70811. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70812. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70813. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70814. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70815. ];
  70816. return PanoramaToCubeMapTools;
  70817. }());
  70818. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70819. })(BABYLON || (BABYLON = {}));
  70820. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70821. var BABYLON;
  70822. (function (BABYLON) {
  70823. ;
  70824. /**
  70825. * This groups tools to convert HDR texture to native colors array.
  70826. */
  70827. var HDRTools = /** @class */ (function () {
  70828. function HDRTools() {
  70829. }
  70830. HDRTools.Ldexp = function (mantissa, exponent) {
  70831. if (exponent > 1023) {
  70832. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70833. }
  70834. if (exponent < -1074) {
  70835. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70836. }
  70837. return mantissa * Math.pow(2, exponent);
  70838. };
  70839. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70840. if (exponent > 0) {
  70841. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70842. float32array[index + 0] = red * exponent;
  70843. float32array[index + 1] = green * exponent;
  70844. float32array[index + 2] = blue * exponent;
  70845. }
  70846. else {
  70847. float32array[index + 0] = 0;
  70848. float32array[index + 1] = 0;
  70849. float32array[index + 2] = 0;
  70850. }
  70851. };
  70852. HDRTools.readStringLine = function (uint8array, startIndex) {
  70853. var line = "";
  70854. var character = "";
  70855. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70856. character = String.fromCharCode(uint8array[i]);
  70857. if (character == "\n") {
  70858. break;
  70859. }
  70860. line += character;
  70861. }
  70862. return line;
  70863. };
  70864. /**
  70865. * Reads header information from an RGBE texture stored in a native array.
  70866. * More information on this format are available here:
  70867. * https://en.wikipedia.org/wiki/RGBE_image_format
  70868. *
  70869. * @param uint8array The binary file stored in native array.
  70870. * @return The header information.
  70871. */
  70872. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70873. var height = 0;
  70874. var width = 0;
  70875. var line = this.readStringLine(uint8array, 0);
  70876. if (line[0] != '#' || line[1] != '?') {
  70877. throw "Bad HDR Format.";
  70878. }
  70879. var endOfHeader = false;
  70880. var findFormat = false;
  70881. var lineIndex = 0;
  70882. do {
  70883. lineIndex += (line.length + 1);
  70884. line = this.readStringLine(uint8array, lineIndex);
  70885. if (line == "FORMAT=32-bit_rle_rgbe") {
  70886. findFormat = true;
  70887. }
  70888. else if (line.length == 0) {
  70889. endOfHeader = true;
  70890. }
  70891. } while (!endOfHeader);
  70892. if (!findFormat) {
  70893. throw "HDR Bad header format, unsupported FORMAT";
  70894. }
  70895. lineIndex += (line.length + 1);
  70896. line = this.readStringLine(uint8array, lineIndex);
  70897. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70898. var match = sizeRegexp.exec(line);
  70899. // TODO. Support +Y and -X if needed.
  70900. if (!match || match.length < 3) {
  70901. throw "HDR Bad header format, no size";
  70902. }
  70903. width = parseInt(match[2]);
  70904. height = parseInt(match[1]);
  70905. if (width < 8 || width > 0x7fff) {
  70906. throw "HDR Bad header format, unsupported size";
  70907. }
  70908. lineIndex += (line.length + 1);
  70909. return {
  70910. height: height,
  70911. width: width,
  70912. dataPosition: lineIndex
  70913. };
  70914. };
  70915. /**
  70916. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  70917. * This RGBE texture needs to store the information as a panorama.
  70918. *
  70919. * More information on this format are available here:
  70920. * https://en.wikipedia.org/wiki/RGBE_image_format
  70921. *
  70922. * @param buffer The binary file stored in an array buffer.
  70923. * @param size The expected size of the extracted cubemap.
  70924. * @return The Cube Map information.
  70925. */
  70926. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  70927. var uint8array = new Uint8Array(buffer);
  70928. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  70929. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70930. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  70931. return cubeMapData;
  70932. };
  70933. /**
  70934. * Returns the pixels data extracted from an RGBE texture.
  70935. * This pixels will be stored left to right up to down in the R G B order in one array.
  70936. *
  70937. * More information on this format are available here:
  70938. * https://en.wikipedia.org/wiki/RGBE_image_format
  70939. *
  70940. * @param uint8array The binary file stored in an array buffer.
  70941. * @param hdrInfo The header information of the file.
  70942. * @return The pixels data in RGB right to left up to down order.
  70943. */
  70944. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  70945. // Keep for multi format supports.
  70946. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70947. };
  70948. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  70949. var num_scanlines = hdrInfo.height;
  70950. var scanline_width = hdrInfo.width;
  70951. var a, b, c, d, count;
  70952. var dataIndex = hdrInfo.dataPosition;
  70953. var index = 0, endIndex = 0, i = 0;
  70954. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  70955. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  70956. // 3 channels of 4 bytes per pixel in float.
  70957. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  70958. var resultArray = new Float32Array(resultBuffer);
  70959. // read in each successive scanline
  70960. while (num_scanlines > 0) {
  70961. a = uint8array[dataIndex++];
  70962. b = uint8array[dataIndex++];
  70963. c = uint8array[dataIndex++];
  70964. d = uint8array[dataIndex++];
  70965. if (a != 2 || b != 2 || (c & 0x80)) {
  70966. // this file is not run length encoded
  70967. throw "HDR Bad header format, not RLE";
  70968. }
  70969. if (((c << 8) | d) != scanline_width) {
  70970. throw "HDR Bad header format, wrong scan line width";
  70971. }
  70972. index = 0;
  70973. // read each of the four channels for the scanline into the buffer
  70974. for (i = 0; i < 4; i++) {
  70975. endIndex = (i + 1) * scanline_width;
  70976. while (index < endIndex) {
  70977. a = uint8array[dataIndex++];
  70978. b = uint8array[dataIndex++];
  70979. if (a > 128) {
  70980. // a run of the same value
  70981. count = a - 128;
  70982. if ((count == 0) || (count > endIndex - index)) {
  70983. throw "HDR Bad Format, bad scanline data (run)";
  70984. }
  70985. while (count-- > 0) {
  70986. scanLineArray[index++] = b;
  70987. }
  70988. }
  70989. else {
  70990. // a non-run
  70991. count = a;
  70992. if ((count == 0) || (count > endIndex - index)) {
  70993. throw "HDR Bad Format, bad scanline data (non-run)";
  70994. }
  70995. scanLineArray[index++] = b;
  70996. if (--count > 0) {
  70997. for (var j = 0; j < count; j++) {
  70998. scanLineArray[index++] = uint8array[dataIndex++];
  70999. }
  71000. }
  71001. }
  71002. }
  71003. }
  71004. // now convert data from buffer into floats
  71005. for (i = 0; i < scanline_width; i++) {
  71006. a = scanLineArray[i];
  71007. b = scanLineArray[i + scanline_width];
  71008. c = scanLineArray[i + 2 * scanline_width];
  71009. d = scanLineArray[i + 3 * scanline_width];
  71010. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  71011. }
  71012. num_scanlines--;
  71013. }
  71014. return resultArray;
  71015. };
  71016. return HDRTools;
  71017. }());
  71018. BABYLON.HDRTools = HDRTools;
  71019. })(BABYLON || (BABYLON = {}));
  71020. //# sourceMappingURL=babylon.hdr.js.map
  71021. var BABYLON;
  71022. (function (BABYLON) {
  71023. /**
  71024. * This represents a texture coming from an HDR input.
  71025. *
  71026. * The only supported format is currently panorama picture stored in RGBE format.
  71027. * Example of such files can be found on HDRLib: http://hdrlib.com/
  71028. */
  71029. var HDRCubeTexture = /** @class */ (function (_super) {
  71030. __extends(HDRCubeTexture, _super);
  71031. /**
  71032. * Instantiates an HDRTexture from the following parameters.
  71033. *
  71034. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  71035. * @param scene The scene the texture will be used in
  71036. * @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.
  71037. * @param noMipmap Forces to not generate the mipmap if true
  71038. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  71039. * @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)
  71040. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  71041. */
  71042. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  71043. if (noMipmap === void 0) { noMipmap = false; }
  71044. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71045. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71046. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71047. if (onLoad === void 0) { onLoad = null; }
  71048. if (onError === void 0) { onError = null; }
  71049. var _this = _super.call(this, scene) || this;
  71050. _this._useInGammaSpace = false;
  71051. _this._generateHarmonics = true;
  71052. _this._isBABYLONPreprocessed = false;
  71053. _this._onLoad = null;
  71054. _this._onError = null;
  71055. /**
  71056. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  71057. */
  71058. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71059. /**
  71060. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  71061. * This is usefull at run time to apply the good shader.
  71062. */
  71063. _this.isPMREM = false;
  71064. _this._isBlocking = true;
  71065. if (!url) {
  71066. return _this;
  71067. }
  71068. _this.name = url;
  71069. _this.url = url;
  71070. _this.hasAlpha = false;
  71071. _this.isCube = true;
  71072. _this._textureMatrix = BABYLON.Matrix.Identity();
  71073. _this._onLoad = onLoad;
  71074. _this._onError = onError;
  71075. _this.gammaSpace = false;
  71076. var caps = scene.getEngine().getCaps();
  71077. if (size) {
  71078. _this._isBABYLONPreprocessed = false;
  71079. _this._noMipmap = noMipmap;
  71080. _this._size = size;
  71081. _this._useInGammaSpace = useInGammaSpace;
  71082. _this._usePMREMGenerator = usePMREMGenerator &&
  71083. caps.textureLOD &&
  71084. caps.textureFloat &&
  71085. !_this._useInGammaSpace;
  71086. }
  71087. else {
  71088. _this._isBABYLONPreprocessed = true;
  71089. _this._noMipmap = false;
  71090. _this._useInGammaSpace = false;
  71091. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71092. !_this._useInGammaSpace;
  71093. }
  71094. _this.isPMREM = _this._usePMREMGenerator;
  71095. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71096. if (!_this._texture) {
  71097. if (!scene.useDelayedTextureLoading) {
  71098. _this.loadTexture();
  71099. }
  71100. else {
  71101. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71102. }
  71103. }
  71104. return _this;
  71105. }
  71106. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71107. /**
  71108. * Gets wether or not the texture is blocking during loading.
  71109. */
  71110. get: function () {
  71111. return this._isBlocking;
  71112. },
  71113. /**
  71114. * Sets wether or not the texture is blocking during loading.
  71115. */
  71116. set: function (value) {
  71117. this._isBlocking = value;
  71118. },
  71119. enumerable: true,
  71120. configurable: true
  71121. });
  71122. /**
  71123. * Occurs when the file is a preprocessed .babylon.hdr file.
  71124. */
  71125. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71126. var _this = this;
  71127. var mipLevels = 0;
  71128. var floatArrayView = null;
  71129. var scene = this.getScene();
  71130. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71131. var mips = new Array();
  71132. if (!floatArrayView) {
  71133. return mips;
  71134. }
  71135. var startIndex = 30;
  71136. for (var level = 0; level < mipLevels; level++) {
  71137. mips.push([]);
  71138. // Fill each pixel of the mip level.
  71139. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71140. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71141. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71142. mips[level].push(faceData);
  71143. startIndex += faceSize;
  71144. }
  71145. }
  71146. return mips;
  71147. } : null;
  71148. var callback = function (buffer) {
  71149. var scene = _this.getScene();
  71150. if (!scene) {
  71151. return null;
  71152. }
  71153. // Create Native Array Views
  71154. var intArrayView = new Int32Array(buffer);
  71155. floatArrayView = new Float32Array(buffer);
  71156. // Fill header.
  71157. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71158. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71159. // Update Texture Information.
  71160. if (!_this._texture) {
  71161. return null;
  71162. }
  71163. _this._texture.updateSize(_this._size, _this._size);
  71164. // Fill polynomial information.
  71165. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71166. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71167. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71168. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71169. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71170. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71171. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71172. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71173. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71174. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71175. _this.sphericalPolynomial = sphericalPolynomial;
  71176. // Fill pixel data.
  71177. mipLevels = intArrayView[29]; // Number of mip levels.
  71178. var startIndex = 30;
  71179. var data = [];
  71180. var faceSize = Math.pow(_this._size, 2) * 3;
  71181. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71182. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71183. startIndex += faceSize;
  71184. }
  71185. var results = [];
  71186. var byteArray = null;
  71187. // Push each faces.
  71188. for (var k = 0; k < 6; k++) {
  71189. var dataFace = null;
  71190. // To be deprecated.
  71191. if (version === 1) {
  71192. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71193. dataFace = data[j];
  71194. }
  71195. // If special cases.
  71196. if (!mipmapGenerator && dataFace) {
  71197. if (!scene.getEngine().getCaps().textureFloat) {
  71198. // 3 channels of 1 bytes per pixel in bytes.
  71199. var byteBuffer = new ArrayBuffer(faceSize);
  71200. byteArray = new Uint8Array(byteBuffer);
  71201. }
  71202. for (var i = 0; i < _this._size * _this._size; i++) {
  71203. // Put in gamma space if requested.
  71204. if (_this._useInGammaSpace) {
  71205. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71206. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71207. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71208. }
  71209. // Convert to int texture for fallback.
  71210. if (byteArray) {
  71211. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71212. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71213. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71214. // May use luminance instead if the result is not accurate.
  71215. var max = Math.max(Math.max(r, g), b);
  71216. if (max > 255) {
  71217. var scale = 255 / max;
  71218. r *= scale;
  71219. g *= scale;
  71220. b *= scale;
  71221. }
  71222. byteArray[(i * 3) + 0] = r;
  71223. byteArray[(i * 3) + 1] = g;
  71224. byteArray[(i * 3) + 2] = b;
  71225. }
  71226. }
  71227. }
  71228. // Fill the array accordingly.
  71229. if (byteArray) {
  71230. results.push(byteArray);
  71231. }
  71232. else {
  71233. results.push(dataFace);
  71234. }
  71235. }
  71236. return results;
  71237. };
  71238. if (scene) {
  71239. 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);
  71240. }
  71241. };
  71242. /**
  71243. * Occurs when the file is raw .hdr file.
  71244. */
  71245. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71246. var _this = this;
  71247. var callback = function (buffer) {
  71248. var scene = _this.getScene();
  71249. if (!scene) {
  71250. return null;
  71251. }
  71252. // Extract the raw linear data.
  71253. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71254. // Generate harmonics if needed.
  71255. if (_this._generateHarmonics) {
  71256. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71257. _this.sphericalPolynomial = sphericalPolynomial;
  71258. }
  71259. var results = [];
  71260. var byteArray = null;
  71261. // Push each faces.
  71262. for (var j = 0; j < 6; j++) {
  71263. // Create uintarray fallback.
  71264. if (!scene.getEngine().getCaps().textureFloat) {
  71265. // 3 channels of 1 bytes per pixel in bytes.
  71266. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71267. byteArray = new Uint8Array(byteBuffer);
  71268. }
  71269. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71270. // If special cases.
  71271. if (_this._useInGammaSpace || byteArray) {
  71272. for (var i = 0; i < _this._size * _this._size; i++) {
  71273. // Put in gamma space if requested.
  71274. if (_this._useInGammaSpace) {
  71275. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71276. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71277. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71278. }
  71279. // Convert to int texture for fallback.
  71280. if (byteArray) {
  71281. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71282. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71283. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71284. // May use luminance instead if the result is not accurate.
  71285. var max = Math.max(Math.max(r, g), b);
  71286. if (max > 255) {
  71287. var scale = 255 / max;
  71288. r *= scale;
  71289. g *= scale;
  71290. b *= scale;
  71291. }
  71292. byteArray[(i * 3) + 0] = r;
  71293. byteArray[(i * 3) + 1] = g;
  71294. byteArray[(i * 3) + 2] = b;
  71295. }
  71296. }
  71297. }
  71298. if (byteArray) {
  71299. results.push(byteArray);
  71300. }
  71301. else {
  71302. results.push(dataFace);
  71303. }
  71304. }
  71305. return results;
  71306. };
  71307. var mipmapGenerator = null;
  71308. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71309. // if (!this._noMipmap &&
  71310. // this._usePMREMGenerator) {
  71311. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71312. // // Custom setup of the generator matching with the PBR shader values.
  71313. // var generator = new BABYLON.PMREMGenerator(data,
  71314. // this._size,
  71315. // this._size,
  71316. // 0,
  71317. // 3,
  71318. // this.getScene().getEngine().getCaps().textureFloat,
  71319. // 2048,
  71320. // 0.25,
  71321. // false,
  71322. // true);
  71323. // return generator.filterCubeMap();
  71324. // };
  71325. // }
  71326. var scene = this.getScene();
  71327. if (scene) {
  71328. 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);
  71329. }
  71330. };
  71331. /**
  71332. * Starts the loading process of the texture.
  71333. */
  71334. HDRCubeTexture.prototype.loadTexture = function () {
  71335. if (this._isBABYLONPreprocessed) {
  71336. this.loadBabylonTexture();
  71337. }
  71338. else {
  71339. this.loadHDRTexture();
  71340. }
  71341. };
  71342. HDRCubeTexture.prototype.clone = function () {
  71343. var scene = this.getScene();
  71344. if (!scene) {
  71345. return this;
  71346. }
  71347. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71348. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71349. // Base texture
  71350. newTexture.level = this.level;
  71351. newTexture.wrapU = this.wrapU;
  71352. newTexture.wrapV = this.wrapV;
  71353. newTexture.coordinatesIndex = this.coordinatesIndex;
  71354. newTexture.coordinatesMode = this.coordinatesMode;
  71355. return newTexture;
  71356. };
  71357. // Methods
  71358. HDRCubeTexture.prototype.delayLoad = function () {
  71359. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71360. return;
  71361. }
  71362. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71363. this._texture = this._getFromCache(this.url, this._noMipmap);
  71364. if (!this._texture) {
  71365. this.loadTexture();
  71366. }
  71367. };
  71368. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71369. return this._textureMatrix;
  71370. };
  71371. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71372. this._textureMatrix = value;
  71373. };
  71374. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71375. var texture = null;
  71376. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71377. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71378. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71379. texture.name = parsedTexture.name;
  71380. texture.hasAlpha = parsedTexture.hasAlpha;
  71381. texture.level = parsedTexture.level;
  71382. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71383. texture.isBlocking = parsedTexture.isBlocking;
  71384. }
  71385. return texture;
  71386. };
  71387. HDRCubeTexture.prototype.serialize = function () {
  71388. if (!this.name) {
  71389. return null;
  71390. }
  71391. var serializationObject = {};
  71392. serializationObject.name = this.name;
  71393. serializationObject.hasAlpha = this.hasAlpha;
  71394. serializationObject.isCube = true;
  71395. serializationObject.level = this.level;
  71396. serializationObject.size = this._size;
  71397. serializationObject.coordinatesMode = this.coordinatesMode;
  71398. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71399. serializationObject.generateHarmonics = this._generateHarmonics;
  71400. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71401. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71402. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71403. serializationObject.noMipmap = this._noMipmap;
  71404. serializationObject.isBlocking = this._isBlocking;
  71405. return serializationObject;
  71406. };
  71407. /**
  71408. * Saves as a file the data contained in the texture in a binary format.
  71409. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71410. * as the spherical used in the lighting.
  71411. * @param url The HDR file url.
  71412. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71413. * @param onError Method called if any error happens during download.
  71414. * @return The packed binary data.
  71415. */
  71416. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71417. if (onError === void 0) { onError = null; }
  71418. var callback = function (buffer) {
  71419. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71420. // Returns a URL you can use as a href.
  71421. var objUrl = window.URL.createObjectURL(data);
  71422. // Simulates a link to it and click to dowload.
  71423. var a = document.createElement("a");
  71424. document.body.appendChild(a);
  71425. a.style.display = "none";
  71426. a.href = objUrl;
  71427. a.download = "envmap.babylon.hdr";
  71428. a.click();
  71429. };
  71430. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71431. };
  71432. /**
  71433. * Serializes the data contained in the texture in a binary format.
  71434. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71435. * as the spherical used in the lighting.
  71436. * @param url The HDR file url.
  71437. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71438. * @param onError Method called if any error happens during download.
  71439. * @return The packed binary data.
  71440. */
  71441. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71442. if (onError === void 0) { onError = null; }
  71443. // Needs the url tho create the texture.
  71444. if (!url) {
  71445. return;
  71446. }
  71447. // Check Power of two size.
  71448. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71449. return;
  71450. }
  71451. // Coming Back in 3.x.
  71452. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71453. };
  71454. HDRCubeTexture._facesMapping = [
  71455. "right",
  71456. "left",
  71457. "up",
  71458. "down",
  71459. "front",
  71460. "back"
  71461. ];
  71462. return HDRCubeTexture;
  71463. }(BABYLON.BaseTexture));
  71464. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71465. })(BABYLON || (BABYLON = {}));
  71466. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71467. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71468. // Huge respect for a such great lib.
  71469. // Earcut license:
  71470. // Copyright (c) 2016, Mapbox
  71471. //
  71472. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71473. // with or without fee is hereby granted, provided that the above copyright notice
  71474. // and this permission notice appear in all copies.
  71475. //
  71476. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71477. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71478. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71479. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71480. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71481. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71482. // THIS SOFTWARE.
  71483. var Earcut;
  71484. (function (Earcut) {
  71485. /**
  71486. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71487. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71488. * @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).
  71489. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71490. */
  71491. function earcut(data, holeIndices, dim) {
  71492. dim = dim || 2;
  71493. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71494. if (!outerNode)
  71495. return triangles;
  71496. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71497. if (hasHoles)
  71498. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71499. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71500. if (data.length > 80 * dim) {
  71501. minX = maxX = data[0];
  71502. minY = maxY = data[1];
  71503. for (var i = dim; i < outerLen; i += dim) {
  71504. x = data[i];
  71505. y = data[i + 1];
  71506. if (x < minX)
  71507. minX = x;
  71508. if (y < minY)
  71509. minY = y;
  71510. if (x > maxX)
  71511. maxX = x;
  71512. if (y > maxY)
  71513. maxY = y;
  71514. }
  71515. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71516. size = Math.max(maxX - minX, maxY - minY);
  71517. }
  71518. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71519. return triangles;
  71520. }
  71521. Earcut.earcut = earcut;
  71522. var Node = /** @class */ (function () {
  71523. function Node(i, x, y) {
  71524. this.i = i;
  71525. this.x = x;
  71526. this.y = y;
  71527. this.prev = null;
  71528. this.next = null;
  71529. this.z = null;
  71530. this.prevZ = null;
  71531. this.nextZ = null;
  71532. this.steiner = false;
  71533. }
  71534. return Node;
  71535. }());
  71536. // create a circular doubly linked list from polygon points in the specified winding order
  71537. function linkedList(data, start, end, dim, clockwise) {
  71538. var i, last = null;
  71539. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71540. for (i = start; i < end; i += dim)
  71541. last = insertNode(i, data[i], data[i + 1], last);
  71542. }
  71543. else {
  71544. for (i = end - dim; i >= start; i -= dim)
  71545. last = insertNode(i, data[i], data[i + 1], last);
  71546. }
  71547. if (last && equals(last, last.next)) {
  71548. removeNode(last);
  71549. last = last.next;
  71550. }
  71551. return last;
  71552. }
  71553. // eliminate colinear or duplicate points
  71554. function filterPoints(start, end) {
  71555. if (!start)
  71556. return start;
  71557. if (!end)
  71558. end = start;
  71559. var p = start, again;
  71560. do {
  71561. again = false;
  71562. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71563. removeNode(p);
  71564. p = end = p.prev;
  71565. if (p === p.next)
  71566. return undefined;
  71567. again = true;
  71568. }
  71569. else {
  71570. p = p.next;
  71571. }
  71572. } while (again || p !== end);
  71573. return end;
  71574. }
  71575. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71576. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71577. if (!ear)
  71578. return;
  71579. // interlink polygon nodes in z-order
  71580. if (!pass && size)
  71581. indexCurve(ear, minX, minY, size);
  71582. var stop = ear, prev, next;
  71583. // iterate through ears, slicing them one by one
  71584. while (ear.prev !== ear.next) {
  71585. prev = ear.prev;
  71586. next = ear.next;
  71587. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71588. // cut off the triangle
  71589. triangles.push(prev.i / dim);
  71590. triangles.push(ear.i / dim);
  71591. triangles.push(next.i / dim);
  71592. removeNode(ear);
  71593. // skipping the next vertice leads to less sliver triangles
  71594. ear = next.next;
  71595. stop = next.next;
  71596. continue;
  71597. }
  71598. ear = next;
  71599. // if we looped through the whole remaining polygon and can't find any more ears
  71600. if (ear === stop) {
  71601. // try filtering points and slicing again
  71602. if (!pass) {
  71603. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71604. // if this didn't work, try curing all small self-intersections locally
  71605. }
  71606. else if (pass === 1) {
  71607. ear = cureLocalIntersections(ear, triangles, dim);
  71608. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71609. // as a last resort, try splitting the remaining polygon into two
  71610. }
  71611. else if (pass === 2) {
  71612. splitEarcut(ear, triangles, dim, minX, minY, size);
  71613. }
  71614. break;
  71615. }
  71616. }
  71617. }
  71618. // check whether a polygon node forms a valid ear with adjacent nodes
  71619. function isEar(ear) {
  71620. var a = ear.prev, b = ear, c = ear.next;
  71621. if (area(a, b, c) >= 0)
  71622. return false; // reflex, can't be an ear
  71623. // now make sure we don't have other points inside the potential ear
  71624. var p = ear.next.next;
  71625. while (p !== ear.prev) {
  71626. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71627. area(p.prev, p, p.next) >= 0)
  71628. return false;
  71629. p = p.next;
  71630. }
  71631. return true;
  71632. }
  71633. function isEarHashed(ear, minX, minY, size) {
  71634. var a = ear.prev, b = ear, c = ear.next;
  71635. if (area(a, b, c) >= 0)
  71636. return false; // reflex, can't be an ear
  71637. // triangle bbox; min & max are calculated like this for speed
  71638. 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);
  71639. // z-order range for the current triangle bbox;
  71640. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71641. // first look for points inside the triangle in increasing z-order
  71642. var p = ear.nextZ;
  71643. while (p && p.z <= maxZ) {
  71644. if (p !== ear.prev &&
  71645. p !== ear.next &&
  71646. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71647. area(p.prev, p, p.next) >= 0)
  71648. return false;
  71649. p = p.nextZ;
  71650. }
  71651. // then look for points in decreasing z-order
  71652. p = ear.prevZ;
  71653. while (p && p.z >= minZ) {
  71654. if (p !== ear.prev &&
  71655. p !== ear.next &&
  71656. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71657. area(p.prev, p, p.next) >= 0)
  71658. return false;
  71659. p = p.prevZ;
  71660. }
  71661. return true;
  71662. }
  71663. // go through all polygon nodes and cure small local self-intersections
  71664. function cureLocalIntersections(start, triangles, dim) {
  71665. var p = start;
  71666. do {
  71667. var a = p.prev, b = p.next.next;
  71668. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71669. triangles.push(a.i / dim);
  71670. triangles.push(p.i / dim);
  71671. triangles.push(b.i / dim);
  71672. // remove two nodes involved
  71673. removeNode(p);
  71674. removeNode(p.next);
  71675. p = start = b;
  71676. }
  71677. p = p.next;
  71678. } while (p !== start);
  71679. return p;
  71680. }
  71681. // try splitting polygon into two and triangulate them independently
  71682. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71683. // look for a valid diagonal that divides the polygon into two
  71684. var a = start;
  71685. do {
  71686. var b = a.next.next;
  71687. while (b !== a.prev) {
  71688. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71689. // split the polygon in two by the diagonal
  71690. var c = splitPolygon(a, b);
  71691. // filter colinear points around the cuts
  71692. a = filterPoints(a, a.next);
  71693. c = filterPoints(c, c.next);
  71694. // run earcut on each half
  71695. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71696. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71697. return;
  71698. }
  71699. b = b.next;
  71700. }
  71701. a = a.next;
  71702. } while (a !== start);
  71703. }
  71704. // link every hole into the outer loop, producing a single-ring polygon without holes
  71705. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71706. var queue = [], i, len, start, end, list;
  71707. for (i = 0, len = holeIndices.length; i < len; i++) {
  71708. start = holeIndices[i] * dim;
  71709. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71710. list = linkedList(data, start, end, dim, false);
  71711. if (list === list.next)
  71712. list.steiner = true;
  71713. queue.push(getLeftmost(list));
  71714. }
  71715. queue.sort(compareX);
  71716. // process holes from left to right
  71717. for (i = 0; i < queue.length; i++) {
  71718. eliminateHole(queue[i], outerNode);
  71719. outerNode = filterPoints(outerNode, outerNode.next);
  71720. }
  71721. return outerNode;
  71722. }
  71723. function compareX(a, b) {
  71724. return a.x - b.x;
  71725. }
  71726. // find a bridge between vertices that connects hole with an outer ring and and link it
  71727. function eliminateHole(hole, outerNode) {
  71728. outerNode = findHoleBridge(hole, outerNode);
  71729. if (outerNode) {
  71730. var b = splitPolygon(outerNode, hole);
  71731. filterPoints(b, b.next);
  71732. }
  71733. }
  71734. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71735. function findHoleBridge(hole, outerNode) {
  71736. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71737. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71738. // segment's endpoint with lesser x will be potential connection point
  71739. do {
  71740. if (hy <= p.y && hy >= p.next.y) {
  71741. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71742. if (x <= hx && x > qx) {
  71743. qx = x;
  71744. if (x === hx) {
  71745. if (hy === p.y)
  71746. return p;
  71747. if (hy === p.next.y)
  71748. return p.next;
  71749. }
  71750. m = p.x < p.next.x ? p : p.next;
  71751. }
  71752. }
  71753. p = p.next;
  71754. } while (p !== outerNode);
  71755. if (!m)
  71756. return null;
  71757. if (hx === qx)
  71758. return m.prev; // hole touches outer segment; pick lower endpoint
  71759. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71760. // if there are no points found, we have a valid connection;
  71761. // otherwise choose the point of the minimum angle with the ray as connection point
  71762. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71763. p = m.next;
  71764. while (p !== stop) {
  71765. if (hx >= p.x &&
  71766. p.x >= mx &&
  71767. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71768. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71769. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71770. m = p;
  71771. tanMin = tan;
  71772. }
  71773. }
  71774. p = p.next;
  71775. }
  71776. return m;
  71777. }
  71778. // interlink polygon nodes in z-order
  71779. function indexCurve(start, minX, minY, size) {
  71780. var p = start;
  71781. do {
  71782. if (p.z === null)
  71783. p.z = zOrder(p.x, p.y, minX, minY, size);
  71784. p.prevZ = p.prev;
  71785. p.nextZ = p.next;
  71786. p = p.next;
  71787. } while (p !== start);
  71788. p.prevZ.nextZ = null;
  71789. p.prevZ = null;
  71790. sortLinked(p);
  71791. }
  71792. // Simon Tatham's linked list merge sort algorithm
  71793. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71794. function sortLinked(list) {
  71795. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71796. do {
  71797. p = list;
  71798. list = null;
  71799. tail = null;
  71800. numMerges = 0;
  71801. while (p) {
  71802. numMerges++;
  71803. q = p;
  71804. pSize = 0;
  71805. for (i = 0; i < inSize; i++) {
  71806. pSize++;
  71807. q = q.nextZ;
  71808. if (!q)
  71809. break;
  71810. }
  71811. qSize = inSize;
  71812. while (pSize > 0 || (qSize > 0 && q)) {
  71813. if (pSize === 0) {
  71814. e = q;
  71815. q = q.nextZ;
  71816. qSize--;
  71817. }
  71818. else if (qSize === 0 || !q) {
  71819. e = p;
  71820. p = p.nextZ;
  71821. pSize--;
  71822. }
  71823. else if (p.z <= q.z) {
  71824. e = p;
  71825. p = p.nextZ;
  71826. pSize--;
  71827. }
  71828. else {
  71829. e = q;
  71830. q = q.nextZ;
  71831. qSize--;
  71832. }
  71833. if (tail)
  71834. tail.nextZ = e;
  71835. else
  71836. list = e;
  71837. e.prevZ = tail;
  71838. tail = e;
  71839. }
  71840. p = q;
  71841. }
  71842. tail.nextZ = null;
  71843. inSize *= 2;
  71844. } while (numMerges > 1);
  71845. return list;
  71846. }
  71847. // z-order of a point given coords and size of the data bounding box
  71848. function zOrder(x, y, minX, minY, size) {
  71849. // coords are transformed into non-negative 15-bit integer range
  71850. x = 32767 * (x - minX) / size;
  71851. y = 32767 * (y - minY) / size;
  71852. x = (x | (x << 8)) & 0x00FF00FF;
  71853. x = (x | (x << 4)) & 0x0F0F0F0F;
  71854. x = (x | (x << 2)) & 0x33333333;
  71855. x = (x | (x << 1)) & 0x55555555;
  71856. y = (y | (y << 8)) & 0x00FF00FF;
  71857. y = (y | (y << 4)) & 0x0F0F0F0F;
  71858. y = (y | (y << 2)) & 0x33333333;
  71859. y = (y | (y << 1)) & 0x55555555;
  71860. return x | (y << 1);
  71861. }
  71862. // find the leftmost node of a polygon ring
  71863. function getLeftmost(start) {
  71864. var p = start, leftmost = start;
  71865. do {
  71866. if (p.x < leftmost.x)
  71867. leftmost = p;
  71868. p = p.next;
  71869. } while (p !== start);
  71870. return leftmost;
  71871. }
  71872. // check if a point lies within a convex triangle
  71873. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71874. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71875. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71876. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71877. }
  71878. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71879. function isValidDiagonal(a, b) {
  71880. return a.next.i !== b.i &&
  71881. a.prev.i !== b.i &&
  71882. !intersectsPolygon(a, b) &&
  71883. locallyInside(a, b) &&
  71884. locallyInside(b, a) &&
  71885. middleInside(a, b);
  71886. }
  71887. // signed area of a triangle
  71888. function area(p, q, r) {
  71889. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71890. }
  71891. // check if two points are equal
  71892. function equals(p1, p2) {
  71893. return p1.x === p2.x && p1.y === p2.y;
  71894. }
  71895. // check if two segments intersect
  71896. function intersects(p1, q1, p2, q2) {
  71897. if ((equals(p1, q1) && equals(p2, q2)) ||
  71898. (equals(p1, q2) && equals(p2, q1)))
  71899. return true;
  71900. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71901. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71902. }
  71903. // check if a polygon diagonal intersects any polygon segments
  71904. function intersectsPolygon(a, b) {
  71905. var p = a;
  71906. do {
  71907. if (p.i !== a.i &&
  71908. p.next.i !== a.i &&
  71909. p.i !== b.i &&
  71910. p.next.i !== b.i &&
  71911. intersects(p, p.next, a, b))
  71912. return true;
  71913. p = p.next;
  71914. } while (p !== a);
  71915. return false;
  71916. }
  71917. // check if a polygon diagonal is locally inside the polygon
  71918. function locallyInside(a, b) {
  71919. return area(a.prev, a, a.next) < 0
  71920. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  71921. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  71922. }
  71923. // check if the middle point of a polygon diagonal is inside the polygon
  71924. function middleInside(a, b) {
  71925. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  71926. do {
  71927. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  71928. inside = !inside;
  71929. p = p.next;
  71930. } while (p !== a);
  71931. return inside;
  71932. }
  71933. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  71934. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  71935. function splitPolygon(a, b) {
  71936. 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;
  71937. a.next = b;
  71938. b.prev = a;
  71939. a2.next = an;
  71940. an.prev = a2;
  71941. b2.next = a2;
  71942. a2.prev = b2;
  71943. bp.next = b2;
  71944. b2.prev = bp;
  71945. return b2;
  71946. }
  71947. // create a node and optionally link it with previous one (in a circular doubly linked list)
  71948. function insertNode(i, x, y, last) {
  71949. var p = new Node(i, x, y);
  71950. if (!last) {
  71951. p.prev = p;
  71952. p.next = p;
  71953. }
  71954. else {
  71955. p.next = last.next;
  71956. p.prev = last;
  71957. last.next.prev = p;
  71958. last.next = p;
  71959. }
  71960. return p;
  71961. }
  71962. function removeNode(p) {
  71963. p.next.prev = p.prev;
  71964. p.prev.next = p.next;
  71965. if (p.prevZ)
  71966. p.prevZ.nextZ = p.nextZ;
  71967. if (p.nextZ)
  71968. p.nextZ.prevZ = p.prevZ;
  71969. }
  71970. /**
  71971. * return a percentage difference between the polygon area and its triangulation area;
  71972. * used to verify correctness of triangulation
  71973. */
  71974. function deviation(data, holeIndices, dim, triangles) {
  71975. var hasHoles = holeIndices && holeIndices.length;
  71976. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  71977. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  71978. if (hasHoles) {
  71979. for (var i = 0, len = holeIndices.length; i < len; i++) {
  71980. var start = holeIndices[i] * dim;
  71981. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71982. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  71983. }
  71984. }
  71985. var trianglesArea = 0;
  71986. for (i = 0; i < triangles.length; i += 3) {
  71987. var a = triangles[i] * dim;
  71988. var b = triangles[i + 1] * dim;
  71989. var c = triangles[i + 2] * dim;
  71990. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  71991. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  71992. }
  71993. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  71994. }
  71995. Earcut.deviation = deviation;
  71996. ;
  71997. function signedArea(data, start, end, dim) {
  71998. var sum = 0;
  71999. for (var i = start, j = end - dim; i < end; i += dim) {
  72000. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  72001. j = i;
  72002. }
  72003. return sum;
  72004. }
  72005. /**
  72006. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  72007. */
  72008. function flatten(data) {
  72009. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  72010. for (var i = 0; i < data.length; i++) {
  72011. for (var j = 0; j < data[i].length; j++) {
  72012. for (var d = 0; d < dim; d++)
  72013. result.vertices.push(data[i][j][d]);
  72014. }
  72015. if (i > 0) {
  72016. holeIndex += data[i - 1].length;
  72017. result.holes.push(holeIndex);
  72018. }
  72019. }
  72020. return result;
  72021. }
  72022. Earcut.flatten = flatten;
  72023. ;
  72024. })(Earcut || (Earcut = {}));
  72025. //# sourceMappingURL=babylon.earcut.js.map
  72026. var BABYLON;
  72027. (function (BABYLON) {
  72028. var IndexedVector2 = /** @class */ (function (_super) {
  72029. __extends(IndexedVector2, _super);
  72030. function IndexedVector2(original, index) {
  72031. var _this = _super.call(this, original.x, original.y) || this;
  72032. _this.index = index;
  72033. return _this;
  72034. }
  72035. return IndexedVector2;
  72036. }(BABYLON.Vector2));
  72037. var PolygonPoints = /** @class */ (function () {
  72038. function PolygonPoints() {
  72039. this.elements = new Array();
  72040. }
  72041. PolygonPoints.prototype.add = function (originalPoints) {
  72042. var _this = this;
  72043. var result = new Array();
  72044. originalPoints.forEach(function (point) {
  72045. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  72046. var newPoint = new IndexedVector2(point, _this.elements.length);
  72047. result.push(newPoint);
  72048. _this.elements.push(newPoint);
  72049. }
  72050. });
  72051. return result;
  72052. };
  72053. PolygonPoints.prototype.computeBounds = function () {
  72054. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72055. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72056. this.elements.forEach(function (point) {
  72057. // x
  72058. if (point.x < lmin.x) {
  72059. lmin.x = point.x;
  72060. }
  72061. else if (point.x > lmax.x) {
  72062. lmax.x = point.x;
  72063. }
  72064. // y
  72065. if (point.y < lmin.y) {
  72066. lmin.y = point.y;
  72067. }
  72068. else if (point.y > lmax.y) {
  72069. lmax.y = point.y;
  72070. }
  72071. });
  72072. return {
  72073. min: lmin,
  72074. max: lmax,
  72075. width: lmax.x - lmin.x,
  72076. height: lmax.y - lmin.y
  72077. };
  72078. };
  72079. return PolygonPoints;
  72080. }());
  72081. var Polygon = /** @class */ (function () {
  72082. function Polygon() {
  72083. }
  72084. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72085. return [
  72086. new BABYLON.Vector2(xmin, ymin),
  72087. new BABYLON.Vector2(xmax, ymin),
  72088. new BABYLON.Vector2(xmax, ymax),
  72089. new BABYLON.Vector2(xmin, ymax)
  72090. ];
  72091. };
  72092. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72093. if (cx === void 0) { cx = 0; }
  72094. if (cy === void 0) { cy = 0; }
  72095. if (numberOfSides === void 0) { numberOfSides = 32; }
  72096. var result = new Array();
  72097. var angle = 0;
  72098. var increment = (Math.PI * 2) / numberOfSides;
  72099. for (var i = 0; i < numberOfSides; i++) {
  72100. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72101. angle -= increment;
  72102. }
  72103. return result;
  72104. };
  72105. Polygon.Parse = function (input) {
  72106. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72107. var i, result = [];
  72108. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72109. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72110. }
  72111. return result;
  72112. };
  72113. Polygon.StartingAt = function (x, y) {
  72114. return BABYLON.Path2.StartingAt(x, y);
  72115. };
  72116. return Polygon;
  72117. }());
  72118. BABYLON.Polygon = Polygon;
  72119. var PolygonMeshBuilder = /** @class */ (function () {
  72120. function PolygonMeshBuilder(name, contours, scene) {
  72121. this._points = new PolygonPoints();
  72122. this._outlinepoints = new PolygonPoints();
  72123. this._holes = new Array();
  72124. this._epoints = new Array();
  72125. this._eholes = new Array();
  72126. this._name = name;
  72127. this._scene = scene;
  72128. var points;
  72129. if (contours instanceof BABYLON.Path2) {
  72130. points = contours.getPoints();
  72131. }
  72132. else {
  72133. points = contours;
  72134. }
  72135. this._addToepoint(points);
  72136. this._points.add(points);
  72137. this._outlinepoints.add(points);
  72138. }
  72139. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72140. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72141. var p = points_1[_i];
  72142. this._epoints.push(p.x, p.y);
  72143. }
  72144. };
  72145. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72146. this._points.add(hole);
  72147. var holepoints = new PolygonPoints();
  72148. holepoints.add(hole);
  72149. this._holes.push(holepoints);
  72150. this._eholes.push(this._epoints.length / 2);
  72151. this._addToepoint(hole);
  72152. return this;
  72153. };
  72154. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72155. var _this = this;
  72156. if (updatable === void 0) { updatable = false; }
  72157. if (depth === void 0) { depth = 0; }
  72158. var result = new BABYLON.Mesh(this._name, this._scene);
  72159. var normals = new Array();
  72160. var positions = new Array();
  72161. var uvs = new Array();
  72162. var bounds = this._points.computeBounds();
  72163. this._points.elements.forEach(function (p) {
  72164. normals.push(0, 1.0, 0);
  72165. positions.push(p.x, 0, p.y);
  72166. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72167. });
  72168. var indices = new Array();
  72169. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72170. for (var i = 0; i < res.length; i++) {
  72171. indices.push(res[i]);
  72172. }
  72173. if (depth > 0) {
  72174. var positionscount = (positions.length / 3); //get the current pointcount
  72175. this._points.elements.forEach(function (p) {
  72176. normals.push(0, -1.0, 0);
  72177. positions.push(p.x, -depth, p.y);
  72178. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72179. });
  72180. var totalCount = indices.length;
  72181. for (var i = 0; i < totalCount; i += 3) {
  72182. var i0 = indices[i + 0];
  72183. var i1 = indices[i + 1];
  72184. var i2 = indices[i + 2];
  72185. indices.push(i2 + positionscount);
  72186. indices.push(i1 + positionscount);
  72187. indices.push(i0 + positionscount);
  72188. }
  72189. //Add the sides
  72190. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72191. this._holes.forEach(function (hole) {
  72192. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72193. });
  72194. }
  72195. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72196. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72197. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72198. result.setIndices(indices);
  72199. return result;
  72200. };
  72201. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72202. var StartIndex = positions.length / 3;
  72203. var ulength = 0;
  72204. for (var i = 0; i < points.elements.length; i++) {
  72205. var p = points.elements[i];
  72206. var p1;
  72207. if ((i + 1) > points.elements.length - 1) {
  72208. p1 = points.elements[0];
  72209. }
  72210. else {
  72211. p1 = points.elements[i + 1];
  72212. }
  72213. positions.push(p.x, 0, p.y);
  72214. positions.push(p.x, -depth, p.y);
  72215. positions.push(p1.x, 0, p1.y);
  72216. positions.push(p1.x, -depth, p1.y);
  72217. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72218. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72219. var v3 = v2.subtract(v1);
  72220. var v4 = new BABYLON.Vector3(0, 1, 0);
  72221. var vn = BABYLON.Vector3.Cross(v3, v4);
  72222. vn = vn.normalize();
  72223. uvs.push(ulength / bounds.width, 0);
  72224. uvs.push(ulength / bounds.width, 1);
  72225. ulength += v3.length();
  72226. uvs.push((ulength / bounds.width), 0);
  72227. uvs.push((ulength / bounds.width), 1);
  72228. if (!flip) {
  72229. normals.push(-vn.x, -vn.y, -vn.z);
  72230. normals.push(-vn.x, -vn.y, -vn.z);
  72231. normals.push(-vn.x, -vn.y, -vn.z);
  72232. normals.push(-vn.x, -vn.y, -vn.z);
  72233. indices.push(StartIndex);
  72234. indices.push(StartIndex + 1);
  72235. indices.push(StartIndex + 2);
  72236. indices.push(StartIndex + 1);
  72237. indices.push(StartIndex + 3);
  72238. indices.push(StartIndex + 2);
  72239. }
  72240. else {
  72241. normals.push(vn.x, vn.y, vn.z);
  72242. normals.push(vn.x, vn.y, vn.z);
  72243. normals.push(vn.x, vn.y, vn.z);
  72244. normals.push(vn.x, vn.y, vn.z);
  72245. indices.push(StartIndex);
  72246. indices.push(StartIndex + 2);
  72247. indices.push(StartIndex + 1);
  72248. indices.push(StartIndex + 1);
  72249. indices.push(StartIndex + 2);
  72250. indices.push(StartIndex + 3);
  72251. }
  72252. StartIndex += 4;
  72253. }
  72254. ;
  72255. };
  72256. return PolygonMeshBuilder;
  72257. }());
  72258. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72259. })(BABYLON || (BABYLON = {}));
  72260. //# sourceMappingURL=babylon.polygonMesh.js.map
  72261. var BABYLON;
  72262. (function (BABYLON) {
  72263. // Unique ID when we import meshes from Babylon to CSG
  72264. var currentCSGMeshId = 0;
  72265. // # class Vertex
  72266. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72267. // one to provide additional features like texture coordinates and vertex
  72268. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72269. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72270. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72271. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72272. // is not used anywhere else.
  72273. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72274. var Vertex = /** @class */ (function () {
  72275. function Vertex(pos, normal, uv) {
  72276. this.pos = pos;
  72277. this.normal = normal;
  72278. this.uv = uv;
  72279. }
  72280. Vertex.prototype.clone = function () {
  72281. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72282. };
  72283. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72284. // orientation of a polygon is flipped.
  72285. Vertex.prototype.flip = function () {
  72286. this.normal = this.normal.scale(-1);
  72287. };
  72288. // Create a new vertex between this vertex and `other` by linearly
  72289. // interpolating all properties using a parameter of `t`. Subclasses should
  72290. // override this to interpolate additional properties.
  72291. Vertex.prototype.interpolate = function (other, t) {
  72292. 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));
  72293. };
  72294. return Vertex;
  72295. }());
  72296. // # class Plane
  72297. // Represents a plane in 3D space.
  72298. var Plane = /** @class */ (function () {
  72299. function Plane(normal, w) {
  72300. this.normal = normal;
  72301. this.w = w;
  72302. }
  72303. Plane.FromPoints = function (a, b, c) {
  72304. var v0 = c.subtract(a);
  72305. var v1 = b.subtract(a);
  72306. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72307. return null;
  72308. }
  72309. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72310. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72311. };
  72312. Plane.prototype.clone = function () {
  72313. return new Plane(this.normal.clone(), this.w);
  72314. };
  72315. Plane.prototype.flip = function () {
  72316. this.normal.scaleInPlace(-1);
  72317. this.w = -this.w;
  72318. };
  72319. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72320. // fragments in the appropriate lists. Coplanar polygons go into either
  72321. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72322. // respect to this plane. Polygons in front or in back of this plane go into
  72323. // either `front` or `back`.
  72324. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72325. var COPLANAR = 0;
  72326. var FRONT = 1;
  72327. var BACK = 2;
  72328. var SPANNING = 3;
  72329. // Classify each point as well as the entire polygon into one of the above
  72330. // four classes.
  72331. var polygonType = 0;
  72332. var types = [];
  72333. var i;
  72334. var t;
  72335. for (i = 0; i < polygon.vertices.length; i++) {
  72336. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72337. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72338. polygonType |= type;
  72339. types.push(type);
  72340. }
  72341. // Put the polygon in the correct list, splitting it when necessary.
  72342. switch (polygonType) {
  72343. case COPLANAR:
  72344. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72345. break;
  72346. case FRONT:
  72347. front.push(polygon);
  72348. break;
  72349. case BACK:
  72350. back.push(polygon);
  72351. break;
  72352. case SPANNING:
  72353. var f = [], b = [];
  72354. for (i = 0; i < polygon.vertices.length; i++) {
  72355. var j = (i + 1) % polygon.vertices.length;
  72356. var ti = types[i], tj = types[j];
  72357. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72358. if (ti !== BACK)
  72359. f.push(vi);
  72360. if (ti !== FRONT)
  72361. b.push(ti !== BACK ? vi.clone() : vi);
  72362. if ((ti | tj) === SPANNING) {
  72363. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72364. var v = vi.interpolate(vj, t);
  72365. f.push(v);
  72366. b.push(v.clone());
  72367. }
  72368. }
  72369. var poly;
  72370. if (f.length >= 3) {
  72371. poly = new Polygon(f, polygon.shared);
  72372. if (poly.plane)
  72373. front.push(poly);
  72374. }
  72375. if (b.length >= 3) {
  72376. poly = new Polygon(b, polygon.shared);
  72377. if (poly.plane)
  72378. back.push(poly);
  72379. }
  72380. break;
  72381. }
  72382. };
  72383. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72384. // point is on the plane.
  72385. Plane.EPSILON = 1e-5;
  72386. return Plane;
  72387. }());
  72388. // # class Polygon
  72389. // Represents a convex polygon. The vertices used to initialize a polygon must
  72390. // be coplanar and form a convex loop.
  72391. //
  72392. // Each convex polygon has a `shared` property, which is shared between all
  72393. // polygons that are clones of each other or were split from the same polygon.
  72394. // This can be used to define per-polygon properties (such as surface color).
  72395. var Polygon = /** @class */ (function () {
  72396. function Polygon(vertices, shared) {
  72397. this.vertices = vertices;
  72398. this.shared = shared;
  72399. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72400. }
  72401. Polygon.prototype.clone = function () {
  72402. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72403. return new Polygon(vertices, this.shared);
  72404. };
  72405. Polygon.prototype.flip = function () {
  72406. this.vertices.reverse().map(function (v) { v.flip(); });
  72407. this.plane.flip();
  72408. };
  72409. return Polygon;
  72410. }());
  72411. // # class Node
  72412. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72413. // by picking a polygon to split along. That polygon (and all other coplanar
  72414. // polygons) are added directly to that node and the other polygons are added to
  72415. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72416. // no distinction between internal and leaf nodes.
  72417. var Node = /** @class */ (function () {
  72418. function Node(polygons) {
  72419. this.plane = null;
  72420. this.front = null;
  72421. this.back = null;
  72422. this.polygons = new Array();
  72423. if (polygons) {
  72424. this.build(polygons);
  72425. }
  72426. }
  72427. Node.prototype.clone = function () {
  72428. var node = new Node();
  72429. node.plane = this.plane && this.plane.clone();
  72430. node.front = this.front && this.front.clone();
  72431. node.back = this.back && this.back.clone();
  72432. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72433. return node;
  72434. };
  72435. // Convert solid space to empty space and empty space to solid space.
  72436. Node.prototype.invert = function () {
  72437. for (var i = 0; i < this.polygons.length; i++) {
  72438. this.polygons[i].flip();
  72439. }
  72440. if (this.plane) {
  72441. this.plane.flip();
  72442. }
  72443. if (this.front) {
  72444. this.front.invert();
  72445. }
  72446. if (this.back) {
  72447. this.back.invert();
  72448. }
  72449. var temp = this.front;
  72450. this.front = this.back;
  72451. this.back = temp;
  72452. };
  72453. // Recursively remove all polygons in `polygons` that are inside this BSP
  72454. // tree.
  72455. Node.prototype.clipPolygons = function (polygons) {
  72456. if (!this.plane)
  72457. return polygons.slice();
  72458. var front = new Array(), back = new Array();
  72459. for (var i = 0; i < polygons.length; i++) {
  72460. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72461. }
  72462. if (this.front) {
  72463. front = this.front.clipPolygons(front);
  72464. }
  72465. if (this.back) {
  72466. back = this.back.clipPolygons(back);
  72467. }
  72468. else {
  72469. back = [];
  72470. }
  72471. return front.concat(back);
  72472. };
  72473. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72474. // `bsp`.
  72475. Node.prototype.clipTo = function (bsp) {
  72476. this.polygons = bsp.clipPolygons(this.polygons);
  72477. if (this.front)
  72478. this.front.clipTo(bsp);
  72479. if (this.back)
  72480. this.back.clipTo(bsp);
  72481. };
  72482. // Return a list of all polygons in this BSP tree.
  72483. Node.prototype.allPolygons = function () {
  72484. var polygons = this.polygons.slice();
  72485. if (this.front)
  72486. polygons = polygons.concat(this.front.allPolygons());
  72487. if (this.back)
  72488. polygons = polygons.concat(this.back.allPolygons());
  72489. return polygons;
  72490. };
  72491. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72492. // new polygons are filtered down to the bottom of the tree and become new
  72493. // nodes there. Each set of polygons is partitioned using the first polygon
  72494. // (no heuristic is used to pick a good split).
  72495. Node.prototype.build = function (polygons) {
  72496. if (!polygons.length)
  72497. return;
  72498. if (!this.plane)
  72499. this.plane = polygons[0].plane.clone();
  72500. var front = new Array(), back = new Array();
  72501. for (var i = 0; i < polygons.length; i++) {
  72502. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72503. }
  72504. if (front.length) {
  72505. if (!this.front)
  72506. this.front = new Node();
  72507. this.front.build(front);
  72508. }
  72509. if (back.length) {
  72510. if (!this.back)
  72511. this.back = new Node();
  72512. this.back.build(back);
  72513. }
  72514. };
  72515. return Node;
  72516. }());
  72517. var CSG = /** @class */ (function () {
  72518. function CSG() {
  72519. this.polygons = new Array();
  72520. }
  72521. // Convert BABYLON.Mesh to BABYLON.CSG
  72522. CSG.FromMesh = function (mesh) {
  72523. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72524. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72525. if (mesh instanceof BABYLON.Mesh) {
  72526. mesh.computeWorldMatrix(true);
  72527. matrix = mesh.getWorldMatrix();
  72528. meshPosition = mesh.position.clone();
  72529. meshRotation = mesh.rotation.clone();
  72530. if (mesh.rotationQuaternion) {
  72531. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72532. }
  72533. meshScaling = mesh.scaling.clone();
  72534. }
  72535. else {
  72536. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72537. }
  72538. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72539. var subMeshes = mesh.subMeshes;
  72540. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72541. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72542. vertices = [];
  72543. for (var j = 0; j < 3; j++) {
  72544. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72545. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72546. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72547. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72548. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72549. vertex = new Vertex(position, normal, uv);
  72550. vertices.push(vertex);
  72551. }
  72552. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72553. // To handle the case of degenerated triangle
  72554. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72555. if (polygon.plane)
  72556. polygons.push(polygon);
  72557. }
  72558. }
  72559. var csg = CSG.FromPolygons(polygons);
  72560. csg.matrix = matrix;
  72561. csg.position = meshPosition;
  72562. csg.rotation = meshRotation;
  72563. csg.scaling = meshScaling;
  72564. csg.rotationQuaternion = meshRotationQuaternion;
  72565. currentCSGMeshId++;
  72566. return csg;
  72567. };
  72568. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72569. CSG.FromPolygons = function (polygons) {
  72570. var csg = new CSG();
  72571. csg.polygons = polygons;
  72572. return csg;
  72573. };
  72574. CSG.prototype.clone = function () {
  72575. var csg = new CSG();
  72576. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72577. csg.copyTransformAttributes(this);
  72578. return csg;
  72579. };
  72580. CSG.prototype.union = function (csg) {
  72581. var a = new Node(this.clone().polygons);
  72582. var b = new Node(csg.clone().polygons);
  72583. a.clipTo(b);
  72584. b.clipTo(a);
  72585. b.invert();
  72586. b.clipTo(a);
  72587. b.invert();
  72588. a.build(b.allPolygons());
  72589. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72590. };
  72591. CSG.prototype.unionInPlace = function (csg) {
  72592. var a = new Node(this.polygons);
  72593. var b = new Node(csg.polygons);
  72594. a.clipTo(b);
  72595. b.clipTo(a);
  72596. b.invert();
  72597. b.clipTo(a);
  72598. b.invert();
  72599. a.build(b.allPolygons());
  72600. this.polygons = a.allPolygons();
  72601. };
  72602. CSG.prototype.subtract = function (csg) {
  72603. var a = new Node(this.clone().polygons);
  72604. var b = new Node(csg.clone().polygons);
  72605. a.invert();
  72606. a.clipTo(b);
  72607. b.clipTo(a);
  72608. b.invert();
  72609. b.clipTo(a);
  72610. b.invert();
  72611. a.build(b.allPolygons());
  72612. a.invert();
  72613. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72614. };
  72615. CSG.prototype.subtractInPlace = function (csg) {
  72616. var a = new Node(this.polygons);
  72617. var b = new Node(csg.polygons);
  72618. a.invert();
  72619. a.clipTo(b);
  72620. b.clipTo(a);
  72621. b.invert();
  72622. b.clipTo(a);
  72623. b.invert();
  72624. a.build(b.allPolygons());
  72625. a.invert();
  72626. this.polygons = a.allPolygons();
  72627. };
  72628. CSG.prototype.intersect = function (csg) {
  72629. var a = new Node(this.clone().polygons);
  72630. var b = new Node(csg.clone().polygons);
  72631. a.invert();
  72632. b.clipTo(a);
  72633. b.invert();
  72634. a.clipTo(b);
  72635. b.clipTo(a);
  72636. a.build(b.allPolygons());
  72637. a.invert();
  72638. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72639. };
  72640. CSG.prototype.intersectInPlace = function (csg) {
  72641. var a = new Node(this.polygons);
  72642. var b = new Node(csg.polygons);
  72643. a.invert();
  72644. b.clipTo(a);
  72645. b.invert();
  72646. a.clipTo(b);
  72647. b.clipTo(a);
  72648. a.build(b.allPolygons());
  72649. a.invert();
  72650. this.polygons = a.allPolygons();
  72651. };
  72652. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72653. // not modified.
  72654. CSG.prototype.inverse = function () {
  72655. var csg = this.clone();
  72656. csg.inverseInPlace();
  72657. return csg;
  72658. };
  72659. CSG.prototype.inverseInPlace = function () {
  72660. this.polygons.map(function (p) { p.flip(); });
  72661. };
  72662. // This is used to keep meshes transformations so they can be restored
  72663. // when we build back a Babylon Mesh
  72664. // NB : All CSG operations are performed in world coordinates
  72665. CSG.prototype.copyTransformAttributes = function (csg) {
  72666. this.matrix = csg.matrix;
  72667. this.position = csg.position;
  72668. this.rotation = csg.rotation;
  72669. this.scaling = csg.scaling;
  72670. this.rotationQuaternion = csg.rotationQuaternion;
  72671. return this;
  72672. };
  72673. // Build Raw mesh from CSG
  72674. // Coordinates here are in world space
  72675. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72676. var matrix = this.matrix.clone();
  72677. matrix.invert();
  72678. 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;
  72679. if (keepSubMeshes) {
  72680. // Sort Polygons, since subMeshes are indices range
  72681. polygons.sort(function (a, b) {
  72682. if (a.shared.meshId === b.shared.meshId) {
  72683. return a.shared.subMeshId - b.shared.subMeshId;
  72684. }
  72685. else {
  72686. return a.shared.meshId - b.shared.meshId;
  72687. }
  72688. });
  72689. }
  72690. for (var i = 0, il = polygons.length; i < il; i++) {
  72691. polygon = polygons[i];
  72692. // Building SubMeshes
  72693. if (!subMesh_dict[polygon.shared.meshId]) {
  72694. subMesh_dict[polygon.shared.meshId] = {};
  72695. }
  72696. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72697. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72698. indexStart: +Infinity,
  72699. indexEnd: -Infinity,
  72700. materialIndex: polygon.shared.materialIndex
  72701. };
  72702. }
  72703. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72704. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72705. polygonIndices[0] = 0;
  72706. polygonIndices[1] = j - 1;
  72707. polygonIndices[2] = j;
  72708. for (var k = 0; k < 3; k++) {
  72709. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72710. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72711. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72712. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72713. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72714. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72715. // Check if 2 points can be merged
  72716. if (!(typeof vertex_idx !== 'undefined' &&
  72717. normals[vertex_idx * 3] === localNormal.x &&
  72718. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72719. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72720. uvs[vertex_idx * 2] === uv.x &&
  72721. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72722. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72723. uvs.push(uv.x, uv.y);
  72724. normals.push(normal.x, normal.y, normal.z);
  72725. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72726. }
  72727. indices.push(vertex_idx);
  72728. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72729. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72730. currentIndex++;
  72731. }
  72732. }
  72733. }
  72734. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72735. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72736. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72737. mesh.setIndices(indices, null);
  72738. if (keepSubMeshes) {
  72739. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72740. var materialIndexOffset = 0, materialMaxIndex;
  72741. mesh.subMeshes = new Array();
  72742. for (var m in subMesh_dict) {
  72743. materialMaxIndex = -1;
  72744. for (var sm in subMesh_dict[m]) {
  72745. subMesh_obj = subMesh_dict[m][sm];
  72746. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72747. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72748. }
  72749. materialIndexOffset += ++materialMaxIndex;
  72750. }
  72751. }
  72752. return mesh;
  72753. };
  72754. // Build Mesh from CSG taking material and transforms into account
  72755. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72756. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72757. mesh.material = material;
  72758. mesh.position.copyFrom(this.position);
  72759. mesh.rotation.copyFrom(this.rotation);
  72760. if (this.rotationQuaternion) {
  72761. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72762. }
  72763. mesh.scaling.copyFrom(this.scaling);
  72764. mesh.computeWorldMatrix(true);
  72765. return mesh;
  72766. };
  72767. return CSG;
  72768. }());
  72769. BABYLON.CSG = CSG;
  72770. })(BABYLON || (BABYLON = {}));
  72771. //# sourceMappingURL=babylon.csg.js.map
  72772. var BABYLON;
  72773. (function (BABYLON) {
  72774. var LensFlare = /** @class */ (function () {
  72775. function LensFlare(size, position, color, imgUrl, system) {
  72776. this.size = size;
  72777. this.position = position;
  72778. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72779. this.color = color || new BABYLON.Color3(1, 1, 1);
  72780. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72781. this._system = system;
  72782. system.lensFlares.push(this);
  72783. }
  72784. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72785. return new LensFlare(size, position, color, imgUrl, system);
  72786. };
  72787. LensFlare.prototype.dispose = function () {
  72788. if (this.texture) {
  72789. this.texture.dispose();
  72790. }
  72791. // Remove from scene
  72792. var index = this._system.lensFlares.indexOf(this);
  72793. this._system.lensFlares.splice(index, 1);
  72794. };
  72795. ;
  72796. return LensFlare;
  72797. }());
  72798. BABYLON.LensFlare = LensFlare;
  72799. })(BABYLON || (BABYLON = {}));
  72800. //# sourceMappingURL=babylon.lensFlare.js.map
  72801. var BABYLON;
  72802. (function (BABYLON) {
  72803. var LensFlareSystem = /** @class */ (function () {
  72804. function LensFlareSystem(name, emitter, scene) {
  72805. this.name = name;
  72806. this.lensFlares = new Array();
  72807. this.borderLimit = 300;
  72808. this.viewportBorder = 0;
  72809. this.layerMask = 0x0FFFFFFF;
  72810. this._vertexBuffers = {};
  72811. this._isEnabled = true;
  72812. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72813. this._emitter = emitter;
  72814. this.id = name;
  72815. scene.lensFlareSystems.push(this);
  72816. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72817. var engine = scene.getEngine();
  72818. // VBO
  72819. var vertices = [];
  72820. vertices.push(1, 1);
  72821. vertices.push(-1, 1);
  72822. vertices.push(-1, -1);
  72823. vertices.push(1, -1);
  72824. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72825. // Indices
  72826. var indices = [];
  72827. indices.push(0);
  72828. indices.push(1);
  72829. indices.push(2);
  72830. indices.push(0);
  72831. indices.push(2);
  72832. indices.push(3);
  72833. this._indexBuffer = engine.createIndexBuffer(indices);
  72834. // Effects
  72835. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72836. }
  72837. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72838. get: function () {
  72839. return this._isEnabled;
  72840. },
  72841. set: function (value) {
  72842. this._isEnabled = value;
  72843. },
  72844. enumerable: true,
  72845. configurable: true
  72846. });
  72847. LensFlareSystem.prototype.getScene = function () {
  72848. return this._scene;
  72849. };
  72850. LensFlareSystem.prototype.getEmitter = function () {
  72851. return this._emitter;
  72852. };
  72853. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72854. this._emitter = newEmitter;
  72855. };
  72856. LensFlareSystem.prototype.getEmitterPosition = function () {
  72857. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72858. };
  72859. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72860. var position = this.getEmitterPosition();
  72861. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72862. this._positionX = position.x;
  72863. this._positionY = position.y;
  72864. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72865. if (this.viewportBorder > 0) {
  72866. globalViewport.x -= this.viewportBorder;
  72867. globalViewport.y -= this.viewportBorder;
  72868. globalViewport.width += this.viewportBorder * 2;
  72869. globalViewport.height += this.viewportBorder * 2;
  72870. position.x += this.viewportBorder;
  72871. position.y += this.viewportBorder;
  72872. this._positionX += this.viewportBorder;
  72873. this._positionY += this.viewportBorder;
  72874. }
  72875. if (position.z > 0) {
  72876. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72877. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72878. return true;
  72879. }
  72880. return true;
  72881. }
  72882. return false;
  72883. };
  72884. LensFlareSystem.prototype._isVisible = function () {
  72885. if (!this._isEnabled || !this._scene.activeCamera) {
  72886. return false;
  72887. }
  72888. var emitterPosition = this.getEmitterPosition();
  72889. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72890. var distance = direction.length();
  72891. direction.normalize();
  72892. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72893. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72894. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72895. };
  72896. LensFlareSystem.prototype.render = function () {
  72897. if (!this._effect.isReady() || !this._scene.activeCamera)
  72898. return false;
  72899. var engine = this._scene.getEngine();
  72900. var viewport = this._scene.activeCamera.viewport;
  72901. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72902. // Position
  72903. if (!this.computeEffectivePosition(globalViewport)) {
  72904. return false;
  72905. }
  72906. // Visibility
  72907. if (!this._isVisible()) {
  72908. return false;
  72909. }
  72910. // Intensity
  72911. var awayX;
  72912. var awayY;
  72913. if (this._positionX < this.borderLimit + globalViewport.x) {
  72914. awayX = this.borderLimit + globalViewport.x - this._positionX;
  72915. }
  72916. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  72917. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  72918. }
  72919. else {
  72920. awayX = 0;
  72921. }
  72922. if (this._positionY < this.borderLimit + globalViewport.y) {
  72923. awayY = this.borderLimit + globalViewport.y - this._positionY;
  72924. }
  72925. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  72926. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  72927. }
  72928. else {
  72929. awayY = 0;
  72930. }
  72931. var away = (awayX > awayY) ? awayX : awayY;
  72932. away -= this.viewportBorder;
  72933. if (away > this.borderLimit) {
  72934. away = this.borderLimit;
  72935. }
  72936. var intensity = 1.0 - (away / this.borderLimit);
  72937. if (intensity < 0) {
  72938. return false;
  72939. }
  72940. if (intensity > 1.0) {
  72941. intensity = 1.0;
  72942. }
  72943. if (this.viewportBorder > 0) {
  72944. globalViewport.x += this.viewportBorder;
  72945. globalViewport.y += this.viewportBorder;
  72946. globalViewport.width -= this.viewportBorder * 2;
  72947. globalViewport.height -= this.viewportBorder * 2;
  72948. this._positionX -= this.viewportBorder;
  72949. this._positionY -= this.viewportBorder;
  72950. }
  72951. // Position
  72952. var centerX = globalViewport.x + globalViewport.width / 2;
  72953. var centerY = globalViewport.y + globalViewport.height / 2;
  72954. var distX = centerX - this._positionX;
  72955. var distY = centerY - this._positionY;
  72956. // Effects
  72957. engine.enableEffect(this._effect);
  72958. engine.setState(false);
  72959. engine.setDepthBuffer(false);
  72960. // VBOs
  72961. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72962. // Flares
  72963. for (var index = 0; index < this.lensFlares.length; index++) {
  72964. var flare = this.lensFlares[index];
  72965. engine.setAlphaMode(flare.alphaMode);
  72966. var x = centerX - (distX * flare.position);
  72967. var y = centerY - (distY * flare.position);
  72968. var cw = flare.size;
  72969. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  72970. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  72971. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  72972. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  72973. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  72974. // Texture
  72975. this._effect.setTexture("textureSampler", flare.texture);
  72976. // Color
  72977. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  72978. // Draw order
  72979. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72980. }
  72981. engine.setDepthBuffer(true);
  72982. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72983. return true;
  72984. };
  72985. LensFlareSystem.prototype.dispose = function () {
  72986. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72987. if (vertexBuffer) {
  72988. vertexBuffer.dispose();
  72989. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72990. }
  72991. if (this._indexBuffer) {
  72992. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72993. this._indexBuffer = null;
  72994. }
  72995. while (this.lensFlares.length) {
  72996. this.lensFlares[0].dispose();
  72997. }
  72998. // Remove from scene
  72999. var index = this._scene.lensFlareSystems.indexOf(this);
  73000. this._scene.lensFlareSystems.splice(index, 1);
  73001. };
  73002. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  73003. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  73004. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  73005. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  73006. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  73007. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  73008. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  73009. var parsedFlare = parsedLensFlareSystem.flares[index];
  73010. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  73011. }
  73012. return lensFlareSystem;
  73013. };
  73014. LensFlareSystem.prototype.serialize = function () {
  73015. var serializationObject = {};
  73016. serializationObject.id = this.id;
  73017. serializationObject.name = this.name;
  73018. serializationObject.emitterId = this.getEmitter().id;
  73019. serializationObject.borderLimit = this.borderLimit;
  73020. serializationObject.flares = [];
  73021. for (var index = 0; index < this.lensFlares.length; index++) {
  73022. var flare = this.lensFlares[index];
  73023. serializationObject.flares.push({
  73024. size: flare.size,
  73025. position: flare.position,
  73026. color: flare.color.asArray(),
  73027. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  73028. });
  73029. }
  73030. return serializationObject;
  73031. };
  73032. return LensFlareSystem;
  73033. }());
  73034. BABYLON.LensFlareSystem = LensFlareSystem;
  73035. })(BABYLON || (BABYLON = {}));
  73036. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  73037. var BABYLON;
  73038. (function (BABYLON) {
  73039. /**
  73040. * This is a holder class for the physics joint created by the physics plugin.
  73041. * It holds a set of functions to control the underlying joint.
  73042. */
  73043. var PhysicsJoint = /** @class */ (function () {
  73044. function PhysicsJoint(type, jointData) {
  73045. this.type = type;
  73046. this.jointData = jointData;
  73047. jointData.nativeParams = jointData.nativeParams || {};
  73048. }
  73049. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  73050. get: function () {
  73051. return this._physicsJoint;
  73052. },
  73053. set: function (newJoint) {
  73054. if (this._physicsJoint) {
  73055. //remove from the wolrd
  73056. }
  73057. this._physicsJoint = newJoint;
  73058. },
  73059. enumerable: true,
  73060. configurable: true
  73061. });
  73062. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  73063. set: function (physicsPlugin) {
  73064. this._physicsPlugin = physicsPlugin;
  73065. },
  73066. enumerable: true,
  73067. configurable: true
  73068. });
  73069. /**
  73070. * Execute a function that is physics-plugin specific.
  73071. * @param {Function} func the function that will be executed.
  73072. * It accepts two parameters: the physics world and the physics joint.
  73073. */
  73074. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73075. func(this._physicsPlugin.world, this._physicsJoint);
  73076. };
  73077. //TODO check if the native joints are the same
  73078. //Joint Types
  73079. PhysicsJoint.DistanceJoint = 0;
  73080. PhysicsJoint.HingeJoint = 1;
  73081. PhysicsJoint.BallAndSocketJoint = 2;
  73082. PhysicsJoint.WheelJoint = 3;
  73083. PhysicsJoint.SliderJoint = 4;
  73084. //OIMO
  73085. PhysicsJoint.PrismaticJoint = 5;
  73086. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73087. PhysicsJoint.UniversalJoint = 6;
  73088. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73089. //Cannon
  73090. //Similar to a Ball-Joint. Different in params
  73091. PhysicsJoint.PointToPointJoint = 8;
  73092. //Cannon only at the moment
  73093. PhysicsJoint.SpringJoint = 9;
  73094. PhysicsJoint.LockJoint = 10;
  73095. return PhysicsJoint;
  73096. }());
  73097. BABYLON.PhysicsJoint = PhysicsJoint;
  73098. /**
  73099. * A class representing a physics distance joint.
  73100. */
  73101. var DistanceJoint = /** @class */ (function (_super) {
  73102. __extends(DistanceJoint, _super);
  73103. function DistanceJoint(jointData) {
  73104. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73105. }
  73106. /**
  73107. * Update the predefined distance.
  73108. */
  73109. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73110. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73111. };
  73112. return DistanceJoint;
  73113. }(PhysicsJoint));
  73114. BABYLON.DistanceJoint = DistanceJoint;
  73115. var MotorEnabledJoint = /** @class */ (function (_super) {
  73116. __extends(MotorEnabledJoint, _super);
  73117. function MotorEnabledJoint(type, jointData) {
  73118. return _super.call(this, type, jointData) || this;
  73119. }
  73120. /**
  73121. * Set the motor values.
  73122. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73123. * @param {number} force the force to apply
  73124. * @param {number} maxForce max force for this motor.
  73125. */
  73126. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73127. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73128. };
  73129. /**
  73130. * Set the motor's limits.
  73131. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73132. */
  73133. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73134. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73135. };
  73136. return MotorEnabledJoint;
  73137. }(PhysicsJoint));
  73138. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73139. /**
  73140. * This class represents a single hinge physics joint
  73141. */
  73142. var HingeJoint = /** @class */ (function (_super) {
  73143. __extends(HingeJoint, _super);
  73144. function HingeJoint(jointData) {
  73145. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73146. }
  73147. /**
  73148. * Set the motor values.
  73149. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73150. * @param {number} force the force to apply
  73151. * @param {number} maxForce max force for this motor.
  73152. */
  73153. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73154. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73155. };
  73156. /**
  73157. * Set the motor's limits.
  73158. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73159. */
  73160. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73161. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73162. };
  73163. return HingeJoint;
  73164. }(MotorEnabledJoint));
  73165. BABYLON.HingeJoint = HingeJoint;
  73166. /**
  73167. * This class represents a dual hinge physics joint (same as wheel joint)
  73168. */
  73169. var Hinge2Joint = /** @class */ (function (_super) {
  73170. __extends(Hinge2Joint, _super);
  73171. function Hinge2Joint(jointData) {
  73172. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73173. }
  73174. /**
  73175. * Set the motor values.
  73176. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73177. * @param {number} force the force to apply
  73178. * @param {number} maxForce max force for this motor.
  73179. * @param {motorIndex} the motor's index, 0 or 1.
  73180. */
  73181. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73182. if (motorIndex === void 0) { motorIndex = 0; }
  73183. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73184. };
  73185. /**
  73186. * Set the motor limits.
  73187. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73188. * @param {number} upperLimit the upper limit
  73189. * @param {number} lowerLimit lower limit
  73190. * @param {motorIndex} the motor's index, 0 or 1.
  73191. */
  73192. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73193. if (motorIndex === void 0) { motorIndex = 0; }
  73194. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73195. };
  73196. return Hinge2Joint;
  73197. }(MotorEnabledJoint));
  73198. BABYLON.Hinge2Joint = Hinge2Joint;
  73199. })(BABYLON || (BABYLON = {}));
  73200. //# sourceMappingURL=babylon.physicsJoint.js.map
  73201. var BABYLON;
  73202. (function (BABYLON) {
  73203. var PhysicsImpostor = /** @class */ (function () {
  73204. function PhysicsImpostor(object, type, _options, _scene) {
  73205. if (_options === void 0) { _options = { mass: 0 }; }
  73206. var _this = this;
  73207. this.object = object;
  73208. this.type = type;
  73209. this._options = _options;
  73210. this._scene = _scene;
  73211. this._bodyUpdateRequired = false;
  73212. this._onBeforePhysicsStepCallbacks = new Array();
  73213. this._onAfterPhysicsStepCallbacks = new Array();
  73214. this._onPhysicsCollideCallbacks = [];
  73215. this._deltaPosition = BABYLON.Vector3.Zero();
  73216. this._isDisposed = false;
  73217. //temp variables for parent rotation calculations
  73218. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73219. this._tmpQuat = new BABYLON.Quaternion();
  73220. this._tmpQuat2 = new BABYLON.Quaternion();
  73221. /**
  73222. * this function is executed by the physics engine.
  73223. */
  73224. this.beforeStep = function () {
  73225. if (!_this._physicsEngine) {
  73226. return;
  73227. }
  73228. _this.object.translate(_this._deltaPosition, -1);
  73229. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73230. _this.object.computeWorldMatrix(false);
  73231. if (_this.object.parent && _this.object.rotationQuaternion) {
  73232. _this.getParentsRotation();
  73233. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73234. }
  73235. else {
  73236. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73237. }
  73238. if (!_this._options.disableBidirectionalTransformation) {
  73239. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73240. }
  73241. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73242. func(_this);
  73243. });
  73244. };
  73245. /**
  73246. * this function is executed by the physics engine.
  73247. */
  73248. this.afterStep = function () {
  73249. if (!_this._physicsEngine) {
  73250. return;
  73251. }
  73252. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73253. func(_this);
  73254. });
  73255. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73256. // object has now its world rotation. needs to be converted to local.
  73257. if (_this.object.parent && _this.object.rotationQuaternion) {
  73258. _this.getParentsRotation();
  73259. _this._tmpQuat.conjugateInPlace();
  73260. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73261. }
  73262. // take the position set and make it the absolute position of this object.
  73263. _this.object.setAbsolutePosition(_this.object.position);
  73264. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73265. _this.object.translate(_this._deltaPosition, 1);
  73266. };
  73267. /**
  73268. * Legacy collision detection event support
  73269. */
  73270. this.onCollideEvent = null;
  73271. //event and body object due to cannon's event-based architecture.
  73272. this.onCollide = function (e) {
  73273. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73274. return;
  73275. }
  73276. if (!_this._physicsEngine) {
  73277. return;
  73278. }
  73279. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73280. if (otherImpostor) {
  73281. // Legacy collision detection event support
  73282. if (_this.onCollideEvent) {
  73283. _this.onCollideEvent(_this, otherImpostor);
  73284. }
  73285. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73286. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73287. }).forEach(function (obj) {
  73288. obj.callback(_this, otherImpostor);
  73289. });
  73290. }
  73291. };
  73292. //sanity check!
  73293. if (!this.object) {
  73294. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73295. return;
  73296. }
  73297. //legacy support for old syntax.
  73298. if (!this._scene && object.getScene) {
  73299. this._scene = object.getScene();
  73300. }
  73301. if (!this._scene) {
  73302. return;
  73303. }
  73304. this._physicsEngine = this._scene.getPhysicsEngine();
  73305. if (!this._physicsEngine) {
  73306. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73307. }
  73308. else {
  73309. //set the object's quaternion, if not set
  73310. if (!this.object.rotationQuaternion) {
  73311. if (this.object.rotation) {
  73312. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73313. }
  73314. else {
  73315. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73316. }
  73317. }
  73318. //default options params
  73319. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73320. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73321. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73322. this._joints = [];
  73323. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73324. if (!this.object.parent || this._options.ignoreParent) {
  73325. this._init();
  73326. }
  73327. else if (this.object.parent.physicsImpostor) {
  73328. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73329. }
  73330. }
  73331. }
  73332. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73333. get: function () {
  73334. return this._isDisposed;
  73335. },
  73336. enumerable: true,
  73337. configurable: true
  73338. });
  73339. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73340. get: function () {
  73341. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73342. },
  73343. set: function (value) {
  73344. this.setMass(value);
  73345. },
  73346. enumerable: true,
  73347. configurable: true
  73348. });
  73349. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73350. get: function () {
  73351. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73352. },
  73353. set: function (value) {
  73354. if (!this._physicsEngine) {
  73355. return;
  73356. }
  73357. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73358. },
  73359. enumerable: true,
  73360. configurable: true
  73361. });
  73362. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73363. get: function () {
  73364. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73365. },
  73366. set: function (value) {
  73367. if (!this._physicsEngine) {
  73368. return;
  73369. }
  73370. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73371. },
  73372. enumerable: true,
  73373. configurable: true
  73374. });
  73375. /**
  73376. * This function will completly initialize this impostor.
  73377. * It will create a new body - but only if this mesh has no parent.
  73378. * If it has, this impostor will not be used other than to define the impostor
  73379. * of the child mesh.
  73380. */
  73381. PhysicsImpostor.prototype._init = function () {
  73382. if (!this._physicsEngine) {
  73383. return;
  73384. }
  73385. this._physicsEngine.removeImpostor(this);
  73386. this.physicsBody = null;
  73387. this._parent = this._parent || this._getPhysicsParent();
  73388. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73389. this._physicsEngine.addImpostor(this);
  73390. }
  73391. };
  73392. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73393. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73394. var parentMesh = this.object.parent;
  73395. return parentMesh.physicsImpostor;
  73396. }
  73397. return null;
  73398. };
  73399. /**
  73400. * Should a new body be generated.
  73401. */
  73402. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73403. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73404. };
  73405. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73406. this.forceUpdate();
  73407. };
  73408. /**
  73409. * Force a regeneration of this or the parent's impostor's body.
  73410. * Use under cautious - This will remove all joints already implemented.
  73411. */
  73412. PhysicsImpostor.prototype.forceUpdate = function () {
  73413. this._init();
  73414. if (this.parent && !this._options.ignoreParent) {
  73415. this.parent.forceUpdate();
  73416. }
  73417. };
  73418. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73419. /*public get mesh(): AbstractMesh {
  73420. return this._mesh;
  73421. }*/
  73422. /**
  73423. * Gets the body that holds this impostor. Either its own, or its parent.
  73424. */
  73425. get: function () {
  73426. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73427. },
  73428. /**
  73429. * Set the physics body. Used mainly by the physics engine/plugin
  73430. */
  73431. set: function (physicsBody) {
  73432. if (this._physicsBody && this._physicsEngine) {
  73433. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73434. }
  73435. this._physicsBody = physicsBody;
  73436. this.resetUpdateFlags();
  73437. },
  73438. enumerable: true,
  73439. configurable: true
  73440. });
  73441. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73442. get: function () {
  73443. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73444. },
  73445. set: function (value) {
  73446. this._parent = value;
  73447. },
  73448. enumerable: true,
  73449. configurable: true
  73450. });
  73451. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73452. this._bodyUpdateRequired = false;
  73453. };
  73454. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73455. if (this.object.getBoundingInfo) {
  73456. var q = this.object.rotationQuaternion;
  73457. //reset rotation
  73458. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73459. //calculate the world matrix with no rotation
  73460. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73461. var boundingInfo = this.object.getBoundingInfo();
  73462. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73463. //bring back the rotation
  73464. this.object.rotationQuaternion = q;
  73465. //calculate the world matrix with the new rotation
  73466. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73467. return size;
  73468. }
  73469. else {
  73470. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73471. }
  73472. };
  73473. PhysicsImpostor.prototype.getObjectCenter = function () {
  73474. if (this.object.getBoundingInfo) {
  73475. var boundingInfo = this.object.getBoundingInfo();
  73476. return boundingInfo.boundingBox.centerWorld;
  73477. }
  73478. else {
  73479. return this.object.position;
  73480. }
  73481. };
  73482. /**
  73483. * Get a specific parametes from the options parameter.
  73484. */
  73485. PhysicsImpostor.prototype.getParam = function (paramName) {
  73486. return this._options[paramName];
  73487. };
  73488. /**
  73489. * Sets a specific parameter in the options given to the physics plugin
  73490. */
  73491. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73492. this._options[paramName] = value;
  73493. this._bodyUpdateRequired = true;
  73494. };
  73495. /**
  73496. * Specifically change the body's mass option. Won't recreate the physics body object
  73497. */
  73498. PhysicsImpostor.prototype.setMass = function (mass) {
  73499. if (this.getParam("mass") !== mass) {
  73500. this.setParam("mass", mass);
  73501. }
  73502. if (this._physicsEngine) {
  73503. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73504. }
  73505. };
  73506. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73507. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73508. };
  73509. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73510. if (this._physicsEngine) {
  73511. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73512. }
  73513. };
  73514. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73515. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73516. };
  73517. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73518. if (this._physicsEngine) {
  73519. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73520. }
  73521. };
  73522. /**
  73523. * Execute a function with the physics plugin native code.
  73524. * Provide a function the will have two variables - the world object and the physics body object.
  73525. */
  73526. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73527. if (this._physicsEngine) {
  73528. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73529. }
  73530. };
  73531. /**
  73532. * Register a function that will be executed before the physics world is stepping forward.
  73533. */
  73534. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73535. this._onBeforePhysicsStepCallbacks.push(func);
  73536. };
  73537. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73538. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73539. if (index > -1) {
  73540. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73541. }
  73542. else {
  73543. BABYLON.Tools.Warn("Function to remove was not found");
  73544. }
  73545. };
  73546. /**
  73547. * Register a function that will be executed after the physics step
  73548. */
  73549. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73550. this._onAfterPhysicsStepCallbacks.push(func);
  73551. };
  73552. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73553. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73554. if (index > -1) {
  73555. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73556. }
  73557. else {
  73558. BABYLON.Tools.Warn("Function to remove was not found");
  73559. }
  73560. };
  73561. /**
  73562. * register a function that will be executed when this impostor collides against a different body.
  73563. */
  73564. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73565. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73566. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73567. };
  73568. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73569. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73570. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73571. if (index > -1) {
  73572. this._onPhysicsCollideCallbacks.splice(index, 1);
  73573. }
  73574. else {
  73575. BABYLON.Tools.Warn("Function to remove was not found");
  73576. }
  73577. };
  73578. PhysicsImpostor.prototype.getParentsRotation = function () {
  73579. var parent = this.object.parent;
  73580. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73581. while (parent) {
  73582. if (parent.rotationQuaternion) {
  73583. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73584. }
  73585. else {
  73586. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73587. }
  73588. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73589. parent = parent.parent;
  73590. }
  73591. return this._tmpQuat;
  73592. };
  73593. /**
  73594. * Apply a force
  73595. */
  73596. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73597. if (this._physicsEngine) {
  73598. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73599. }
  73600. return this;
  73601. };
  73602. /**
  73603. * Apply an impulse
  73604. */
  73605. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73606. if (this._physicsEngine) {
  73607. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73608. }
  73609. return this;
  73610. };
  73611. /**
  73612. * A help function to create a joint.
  73613. */
  73614. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73615. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73616. this.addJoint(otherImpostor, joint);
  73617. return this;
  73618. };
  73619. /**
  73620. * Add a joint to this impostor with a different impostor.
  73621. */
  73622. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73623. this._joints.push({
  73624. otherImpostor: otherImpostor,
  73625. joint: joint
  73626. });
  73627. if (this._physicsEngine) {
  73628. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73629. }
  73630. return this;
  73631. };
  73632. /**
  73633. * Will keep this body still, in a sleep mode.
  73634. */
  73635. PhysicsImpostor.prototype.sleep = function () {
  73636. if (this._physicsEngine) {
  73637. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73638. }
  73639. return this;
  73640. };
  73641. /**
  73642. * Wake the body up.
  73643. */
  73644. PhysicsImpostor.prototype.wakeUp = function () {
  73645. if (this._physicsEngine) {
  73646. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73647. }
  73648. return this;
  73649. };
  73650. PhysicsImpostor.prototype.clone = function (newObject) {
  73651. if (!newObject)
  73652. return null;
  73653. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73654. };
  73655. PhysicsImpostor.prototype.dispose = function () {
  73656. var _this = this;
  73657. //no dispose if no physics engine is available.
  73658. if (!this._physicsEngine) {
  73659. return;
  73660. }
  73661. this._joints.forEach(function (j) {
  73662. if (_this._physicsEngine) {
  73663. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73664. }
  73665. });
  73666. //dispose the physics body
  73667. this._physicsEngine.removeImpostor(this);
  73668. if (this.parent) {
  73669. this.parent.forceUpdate();
  73670. }
  73671. else {
  73672. /*this._object.getChildMeshes().forEach(function(mesh) {
  73673. if (mesh.physicsImpostor) {
  73674. if (disposeChildren) {
  73675. mesh.physicsImpostor.dispose();
  73676. mesh.physicsImpostor = null;
  73677. }
  73678. }
  73679. })*/
  73680. }
  73681. this._isDisposed = true;
  73682. };
  73683. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73684. this._deltaPosition.copyFrom(position);
  73685. };
  73686. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73687. if (!this._deltaRotation) {
  73688. this._deltaRotation = new BABYLON.Quaternion();
  73689. }
  73690. this._deltaRotation.copyFrom(rotation);
  73691. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73692. };
  73693. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73694. if (this._physicsEngine) {
  73695. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73696. }
  73697. return this;
  73698. };
  73699. PhysicsImpostor.prototype.getRadius = function () {
  73700. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73701. };
  73702. /**
  73703. * Sync a bone with this impostor
  73704. * @param bone The bone to sync to the impostor.
  73705. * @param boneMesh The mesh that the bone is influencing.
  73706. * @param jointPivot The pivot of the joint / bone in local space.
  73707. * @param distToJoint Optional distance from the impostor to the joint.
  73708. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73709. */
  73710. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73711. var tempVec = PhysicsImpostor._tmpVecs[0];
  73712. var mesh = this.object;
  73713. if (mesh.rotationQuaternion) {
  73714. if (adjustRotation) {
  73715. var tempQuat = PhysicsImpostor._tmpQuat;
  73716. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73717. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73718. }
  73719. else {
  73720. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73721. }
  73722. }
  73723. tempVec.x = 0;
  73724. tempVec.y = 0;
  73725. tempVec.z = 0;
  73726. if (jointPivot) {
  73727. tempVec.x = jointPivot.x;
  73728. tempVec.y = jointPivot.y;
  73729. tempVec.z = jointPivot.z;
  73730. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73731. if (distToJoint === undefined || distToJoint === null) {
  73732. distToJoint = jointPivot.length();
  73733. }
  73734. tempVec.x *= distToJoint;
  73735. tempVec.y *= distToJoint;
  73736. tempVec.z *= distToJoint;
  73737. }
  73738. if (bone.getParent()) {
  73739. tempVec.addInPlace(mesh.getAbsolutePosition());
  73740. bone.setAbsolutePosition(tempVec, boneMesh);
  73741. }
  73742. else {
  73743. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73744. boneMesh.position.x -= tempVec.x;
  73745. boneMesh.position.y -= tempVec.y;
  73746. boneMesh.position.z -= tempVec.z;
  73747. }
  73748. };
  73749. /**
  73750. * Sync impostor to a bone
  73751. * @param bone The bone that the impostor will be synced to.
  73752. * @param boneMesh The mesh that the bone is influencing.
  73753. * @param jointPivot The pivot of the joint / bone in local space.
  73754. * @param distToJoint Optional distance from the impostor to the joint.
  73755. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73756. * @param boneAxis Optional vector3 axis the bone is aligned with
  73757. */
  73758. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73759. var mesh = this.object;
  73760. if (mesh.rotationQuaternion) {
  73761. if (adjustRotation) {
  73762. var tempQuat = PhysicsImpostor._tmpQuat;
  73763. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73764. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73765. }
  73766. else {
  73767. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73768. }
  73769. }
  73770. var pos = PhysicsImpostor._tmpVecs[0];
  73771. var boneDir = PhysicsImpostor._tmpVecs[1];
  73772. if (!boneAxis) {
  73773. boneAxis = PhysicsImpostor._tmpVecs[2];
  73774. boneAxis.x = 0;
  73775. boneAxis.y = 1;
  73776. boneAxis.z = 0;
  73777. }
  73778. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73779. bone.getAbsolutePositionToRef(boneMesh, pos);
  73780. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73781. distToJoint = jointPivot.length();
  73782. }
  73783. if (distToJoint !== undefined && distToJoint !== null) {
  73784. pos.x += boneDir.x * distToJoint;
  73785. pos.y += boneDir.y * distToJoint;
  73786. pos.z += boneDir.z * distToJoint;
  73787. }
  73788. mesh.setAbsolutePosition(pos);
  73789. };
  73790. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73791. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73792. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73793. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73794. //Impostor types
  73795. PhysicsImpostor.NoImpostor = 0;
  73796. PhysicsImpostor.SphereImpostor = 1;
  73797. PhysicsImpostor.BoxImpostor = 2;
  73798. PhysicsImpostor.PlaneImpostor = 3;
  73799. PhysicsImpostor.MeshImpostor = 4;
  73800. PhysicsImpostor.CylinderImpostor = 7;
  73801. PhysicsImpostor.ParticleImpostor = 8;
  73802. PhysicsImpostor.HeightmapImpostor = 9;
  73803. return PhysicsImpostor;
  73804. }());
  73805. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73806. })(BABYLON || (BABYLON = {}));
  73807. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73808. var BABYLON;
  73809. (function (BABYLON) {
  73810. var PhysicsEngine = /** @class */ (function () {
  73811. function PhysicsEngine(gravity, _physicsPlugin) {
  73812. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73813. this._physicsPlugin = _physicsPlugin;
  73814. //new methods and parameters
  73815. this._impostors = [];
  73816. this._joints = [];
  73817. if (!this._physicsPlugin.isSupported()) {
  73818. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73819. + "Please make sure it is included.");
  73820. }
  73821. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73822. this.setGravity(gravity);
  73823. this.setTimeStep();
  73824. }
  73825. PhysicsEngine.prototype.setGravity = function (gravity) {
  73826. this.gravity = gravity;
  73827. this._physicsPlugin.setGravity(this.gravity);
  73828. };
  73829. /**
  73830. * Set the time step of the physics engine.
  73831. * default is 1/60.
  73832. * To slow it down, enter 1/600 for example.
  73833. * To speed it up, 1/30
  73834. * @param {number} newTimeStep the new timestep to apply to this world.
  73835. */
  73836. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73837. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73838. this._physicsPlugin.setTimeStep(newTimeStep);
  73839. };
  73840. /**
  73841. * Get the time step of the physics engine.
  73842. */
  73843. PhysicsEngine.prototype.getTimeStep = function () {
  73844. return this._physicsPlugin.getTimeStep();
  73845. };
  73846. PhysicsEngine.prototype.dispose = function () {
  73847. this._impostors.forEach(function (impostor) {
  73848. impostor.dispose();
  73849. });
  73850. this._physicsPlugin.dispose();
  73851. };
  73852. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73853. return this._physicsPlugin.name;
  73854. };
  73855. /**
  73856. * Adding a new impostor for the impostor tracking.
  73857. * This will be done by the impostor itself.
  73858. * @param {PhysicsImpostor} impostor the impostor to add
  73859. */
  73860. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73861. impostor.uniqueId = this._impostors.push(impostor);
  73862. //if no parent, generate the body
  73863. if (!impostor.parent) {
  73864. this._physicsPlugin.generatePhysicsBody(impostor);
  73865. }
  73866. };
  73867. /**
  73868. * Remove an impostor from the engine.
  73869. * This impostor and its mesh will not longer be updated by the physics engine.
  73870. * @param {PhysicsImpostor} impostor the impostor to remove
  73871. */
  73872. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73873. var index = this._impostors.indexOf(impostor);
  73874. if (index > -1) {
  73875. var removed = this._impostors.splice(index, 1);
  73876. //Is it needed?
  73877. if (removed.length) {
  73878. //this will also remove it from the world.
  73879. removed[0].physicsBody = null;
  73880. }
  73881. }
  73882. };
  73883. /**
  73884. * Add a joint to the physics engine
  73885. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73886. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73887. * @param {PhysicsJoint} the joint that will connect both impostors.
  73888. */
  73889. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73890. var impostorJoint = {
  73891. mainImpostor: mainImpostor,
  73892. connectedImpostor: connectedImpostor,
  73893. joint: joint
  73894. };
  73895. joint.physicsPlugin = this._physicsPlugin;
  73896. this._joints.push(impostorJoint);
  73897. this._physicsPlugin.generateJoint(impostorJoint);
  73898. };
  73899. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73900. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73901. return (impostorJoint.connectedImpostor === connectedImpostor
  73902. && impostorJoint.joint === joint
  73903. && impostorJoint.mainImpostor === mainImpostor);
  73904. });
  73905. if (matchingJoints.length) {
  73906. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73907. //TODO remove it from the list as well
  73908. }
  73909. };
  73910. /**
  73911. * Called by the scene. no need to call it.
  73912. */
  73913. PhysicsEngine.prototype._step = function (delta) {
  73914. var _this = this;
  73915. //check if any mesh has no body / requires an update
  73916. this._impostors.forEach(function (impostor) {
  73917. if (impostor.isBodyInitRequired()) {
  73918. _this._physicsPlugin.generatePhysicsBody(impostor);
  73919. }
  73920. });
  73921. if (delta > 0.1) {
  73922. delta = 0.1;
  73923. }
  73924. else if (delta <= 0) {
  73925. delta = 1.0 / 60.0;
  73926. }
  73927. this._physicsPlugin.executeStep(delta, this._impostors);
  73928. };
  73929. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  73930. return this._physicsPlugin;
  73931. };
  73932. PhysicsEngine.prototype.getImpostors = function () {
  73933. return this._impostors;
  73934. };
  73935. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  73936. for (var i = 0; i < this._impostors.length; ++i) {
  73937. if (this._impostors[i].object === object) {
  73938. return this._impostors[i];
  73939. }
  73940. }
  73941. return null;
  73942. };
  73943. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  73944. for (var i = 0; i < this._impostors.length; ++i) {
  73945. if (this._impostors[i].physicsBody === body) {
  73946. return this._impostors[i];
  73947. }
  73948. }
  73949. return null;
  73950. };
  73951. // Statics
  73952. PhysicsEngine.Epsilon = 0.001;
  73953. return PhysicsEngine;
  73954. }());
  73955. BABYLON.PhysicsEngine = PhysicsEngine;
  73956. })(BABYLON || (BABYLON = {}));
  73957. //# sourceMappingURL=babylon.physicsEngine.js.map
  73958. var BABYLON;
  73959. (function (BABYLON) {
  73960. var PhysicsHelper = /** @class */ (function () {
  73961. function PhysicsHelper(scene) {
  73962. this._scene = scene;
  73963. this._physicsEngine = this._scene.getPhysicsEngine();
  73964. if (!this._physicsEngine) {
  73965. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  73966. }
  73967. }
  73968. /**
  73969. * @param {Vector3} origin the origin of the explosion
  73970. * @param {number} radius the explosion radius
  73971. * @param {number} strength the explosion strength
  73972. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73973. */
  73974. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  73975. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73976. if (!this._physicsEngine) {
  73977. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  73978. return null;
  73979. }
  73980. var impostors = this._physicsEngine.getImpostors();
  73981. if (impostors.length === 0) {
  73982. return null;
  73983. }
  73984. var event = new PhysicsRadialExplosionEvent(this._scene);
  73985. impostors.forEach(function (impostor) {
  73986. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73987. if (!impostorForceAndContactPoint) {
  73988. return;
  73989. }
  73990. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73991. });
  73992. event.dispose(false);
  73993. return event;
  73994. };
  73995. /**
  73996. * @param {Vector3} origin the origin of the explosion
  73997. * @param {number} radius the explosion radius
  73998. * @param {number} strength the explosion strength
  73999. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74000. */
  74001. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  74002. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74003. if (!this._physicsEngine) {
  74004. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74005. return null;
  74006. }
  74007. var impostors = this._physicsEngine.getImpostors();
  74008. if (impostors.length === 0) {
  74009. return null;
  74010. }
  74011. var event = new PhysicsRadialExplosionEvent(this._scene);
  74012. impostors.forEach(function (impostor) {
  74013. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74014. if (!impostorForceAndContactPoint) {
  74015. return;
  74016. }
  74017. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74018. });
  74019. event.dispose(false);
  74020. return event;
  74021. };
  74022. /**
  74023. * @param {Vector3} origin the origin of the explosion
  74024. * @param {number} radius the explosion radius
  74025. * @param {number} strength the explosion strength
  74026. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74027. */
  74028. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  74029. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74030. if (!this._physicsEngine) {
  74031. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74032. return null;
  74033. }
  74034. var impostors = this._physicsEngine.getImpostors();
  74035. if (impostors.length === 0) {
  74036. return null;
  74037. }
  74038. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  74039. event.dispose(false);
  74040. return event;
  74041. };
  74042. /**
  74043. * @param {Vector3} origin the origin of the updraft
  74044. * @param {number} radius the radius of the updraft
  74045. * @param {number} strength the strength of the updraft
  74046. * @param {number} height the height of the updraft
  74047. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  74048. */
  74049. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  74050. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  74051. if (!this._physicsEngine) {
  74052. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74053. return null;
  74054. }
  74055. if (this._physicsEngine.getImpostors().length === 0) {
  74056. return null;
  74057. }
  74058. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  74059. event.dispose(false);
  74060. return event;
  74061. };
  74062. /**
  74063. * @param {Vector3} origin the of the vortex
  74064. * @param {number} radius the radius of the vortex
  74065. * @param {number} strength the strength of the vortex
  74066. * @param {number} height the height of the vortex
  74067. */
  74068. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74069. if (!this._physicsEngine) {
  74070. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74071. return null;
  74072. }
  74073. if (this._physicsEngine.getImpostors().length === 0) {
  74074. return null;
  74075. }
  74076. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74077. event.dispose(false);
  74078. return event;
  74079. };
  74080. return PhysicsHelper;
  74081. }());
  74082. BABYLON.PhysicsHelper = PhysicsHelper;
  74083. /***** Radial explosion *****/
  74084. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74085. function PhysicsRadialExplosionEvent(scene) {
  74086. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74087. this._rays = [];
  74088. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74089. this._scene = scene;
  74090. }
  74091. /**
  74092. * Returns the data related to the radial explosion event (sphere & rays).
  74093. * @returns {PhysicsRadialExplosionEventData}
  74094. */
  74095. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74096. this._dataFetched = true;
  74097. return {
  74098. sphere: this._sphere,
  74099. rays: this._rays,
  74100. };
  74101. };
  74102. /**
  74103. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74104. * @param impostor
  74105. * @param {Vector3} origin the origin of the explosion
  74106. * @param {number} radius the explosion radius
  74107. * @param {number} strength the explosion strength
  74108. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74109. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74110. */
  74111. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74112. if (impostor.mass === 0) {
  74113. return null;
  74114. }
  74115. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74116. return null;
  74117. }
  74118. if (impostor.object.getClassName() !== 'Mesh') {
  74119. return null;
  74120. }
  74121. var impostorObject = impostor.object;
  74122. var impostorObjectCenter = impostor.getObjectCenter();
  74123. var direction = impostorObjectCenter.subtract(origin);
  74124. var ray = new BABYLON.Ray(origin, direction, radius);
  74125. this._rays.push(ray);
  74126. var hit = ray.intersectsMesh(impostorObject);
  74127. var contactPoint = hit.pickedPoint;
  74128. if (!contactPoint) {
  74129. return null;
  74130. }
  74131. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74132. if (distanceFromOrigin > radius) {
  74133. return null;
  74134. }
  74135. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74136. ? strength
  74137. : strength * (1 - (distanceFromOrigin / radius));
  74138. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74139. return { force: force, contactPoint: contactPoint };
  74140. };
  74141. /**
  74142. * Disposes the sphere.
  74143. * @param {bolean} force
  74144. */
  74145. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74146. var _this = this;
  74147. if (force === void 0) { force = true; }
  74148. if (force) {
  74149. this._sphere.dispose();
  74150. }
  74151. else {
  74152. setTimeout(function () {
  74153. if (!_this._dataFetched) {
  74154. _this._sphere.dispose();
  74155. }
  74156. }, 0);
  74157. }
  74158. };
  74159. /*** Helpers ***/
  74160. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74161. if (!this._sphere) {
  74162. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74163. this._sphere.isVisible = false;
  74164. }
  74165. };
  74166. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74167. var impostorObject = impostor.object;
  74168. this._prepareSphere();
  74169. this._sphere.position = origin;
  74170. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74171. this._sphere._updateBoundingInfo();
  74172. this._sphere.computeWorldMatrix(true);
  74173. return this._sphere.intersectsMesh(impostorObject, true);
  74174. };
  74175. return PhysicsRadialExplosionEvent;
  74176. }());
  74177. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74178. /***** Gravitational Field *****/
  74179. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74180. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74181. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74182. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74183. this._physicsHelper = physicsHelper;
  74184. this._scene = scene;
  74185. this._origin = origin;
  74186. this._radius = radius;
  74187. this._strength = strength;
  74188. this._falloff = falloff;
  74189. this._tickCallback = this._tick.bind(this);
  74190. }
  74191. /**
  74192. * Returns the data related to the gravitational field event (sphere).
  74193. * @returns {PhysicsGravitationalFieldEventData}
  74194. */
  74195. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74196. this._dataFetched = true;
  74197. return {
  74198. sphere: this._sphere,
  74199. };
  74200. };
  74201. /**
  74202. * Enables the gravitational field.
  74203. */
  74204. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74205. this._tickCallback.call(this);
  74206. this._scene.registerBeforeRender(this._tickCallback);
  74207. };
  74208. /**
  74209. * Disables the gravitational field.
  74210. */
  74211. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74212. this._scene.unregisterBeforeRender(this._tickCallback);
  74213. };
  74214. /**
  74215. * Disposes the sphere.
  74216. * @param {bolean} force
  74217. */
  74218. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74219. var _this = this;
  74220. if (force === void 0) { force = true; }
  74221. if (force) {
  74222. this._sphere.dispose();
  74223. }
  74224. else {
  74225. setTimeout(function () {
  74226. if (!_this._dataFetched) {
  74227. _this._sphere.dispose();
  74228. }
  74229. }, 0);
  74230. }
  74231. };
  74232. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74233. // Since the params won't change, we fetch the event only once
  74234. if (this._sphere) {
  74235. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74236. }
  74237. else {
  74238. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74239. if (radialExplosionEvent) {
  74240. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74241. }
  74242. }
  74243. };
  74244. return PhysicsGravitationalFieldEvent;
  74245. }());
  74246. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74247. /***** Updraft *****/
  74248. var PhysicsUpdraftEvent = /** @class */ (function () {
  74249. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74250. this._scene = _scene;
  74251. this._origin = _origin;
  74252. this._radius = _radius;
  74253. this._strength = _strength;
  74254. this._height = _height;
  74255. this._updraftMode = _updraftMode;
  74256. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74257. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74258. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74259. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74260. this._physicsEngine = this._scene.getPhysicsEngine();
  74261. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74262. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74263. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74264. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74265. }
  74266. this._tickCallback = this._tick.bind(this);
  74267. }
  74268. /**
  74269. * Returns the data related to the updraft event (cylinder).
  74270. * @returns {PhysicsUpdraftEventData}
  74271. */
  74272. PhysicsUpdraftEvent.prototype.getData = function () {
  74273. this._dataFetched = true;
  74274. return {
  74275. cylinder: this._cylinder,
  74276. };
  74277. };
  74278. /**
  74279. * Enables the updraft.
  74280. */
  74281. PhysicsUpdraftEvent.prototype.enable = function () {
  74282. this._tickCallback.call(this);
  74283. this._scene.registerBeforeRender(this._tickCallback);
  74284. };
  74285. /**
  74286. * Disables the cortex.
  74287. */
  74288. PhysicsUpdraftEvent.prototype.disable = function () {
  74289. this._scene.unregisterBeforeRender(this._tickCallback);
  74290. };
  74291. /**
  74292. * Disposes the sphere.
  74293. * @param {bolean} force
  74294. */
  74295. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74296. var _this = this;
  74297. if (force === void 0) { force = true; }
  74298. if (force) {
  74299. this._cylinder.dispose();
  74300. }
  74301. else {
  74302. setTimeout(function () {
  74303. if (!_this._dataFetched) {
  74304. _this._cylinder.dispose();
  74305. }
  74306. }, 0);
  74307. }
  74308. };
  74309. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74310. if (impostor.mass === 0) {
  74311. return null;
  74312. }
  74313. if (!this._intersectsWithCylinder(impostor)) {
  74314. return null;
  74315. }
  74316. var impostorObjectCenter = impostor.getObjectCenter();
  74317. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74318. var direction = this._originDirection;
  74319. }
  74320. else {
  74321. var direction = impostorObjectCenter.subtract(this._originTop);
  74322. }
  74323. var multiplier = this._strength * -1;
  74324. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74325. return { force: force, contactPoint: impostorObjectCenter };
  74326. };
  74327. PhysicsUpdraftEvent.prototype._tick = function () {
  74328. var _this = this;
  74329. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74330. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74331. if (!impostorForceAndContactPoint) {
  74332. return;
  74333. }
  74334. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74335. });
  74336. };
  74337. /*** Helpers ***/
  74338. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74339. if (!this._cylinder) {
  74340. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74341. height: this._height,
  74342. diameter: this._radius * 2,
  74343. }, this._scene);
  74344. this._cylinder.isVisible = false;
  74345. }
  74346. };
  74347. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74348. var impostorObject = impostor.object;
  74349. this._prepareCylinder();
  74350. this._cylinder.position = this._cylinderPosition;
  74351. return this._cylinder.intersectsMesh(impostorObject, true);
  74352. };
  74353. return PhysicsUpdraftEvent;
  74354. }());
  74355. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74356. /***** Vortex *****/
  74357. var PhysicsVortexEvent = /** @class */ (function () {
  74358. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74359. this._scene = _scene;
  74360. this._origin = _origin;
  74361. this._radius = _radius;
  74362. this._strength = _strength;
  74363. this._height = _height;
  74364. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74365. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74366. this._updraftMultiplier = 0.02;
  74367. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74368. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74369. this._physicsEngine = this._scene.getPhysicsEngine();
  74370. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74371. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74372. this._tickCallback = this._tick.bind(this);
  74373. }
  74374. /**
  74375. * Returns the data related to the vortex event (cylinder).
  74376. * @returns {PhysicsVortexEventData}
  74377. */
  74378. PhysicsVortexEvent.prototype.getData = function () {
  74379. this._dataFetched = true;
  74380. return {
  74381. cylinder: this._cylinder,
  74382. };
  74383. };
  74384. /**
  74385. * Enables the vortex.
  74386. */
  74387. PhysicsVortexEvent.prototype.enable = function () {
  74388. this._tickCallback.call(this);
  74389. this._scene.registerBeforeRender(this._tickCallback);
  74390. };
  74391. /**
  74392. * Disables the cortex.
  74393. */
  74394. PhysicsVortexEvent.prototype.disable = function () {
  74395. this._scene.unregisterBeforeRender(this._tickCallback);
  74396. };
  74397. /**
  74398. * Disposes the sphere.
  74399. * @param {bolean} force
  74400. */
  74401. PhysicsVortexEvent.prototype.dispose = function (force) {
  74402. var _this = this;
  74403. if (force === void 0) { force = true; }
  74404. if (force) {
  74405. this._cylinder.dispose();
  74406. }
  74407. else {
  74408. setTimeout(function () {
  74409. if (!_this._dataFetched) {
  74410. _this._cylinder.dispose();
  74411. }
  74412. }, 0);
  74413. }
  74414. };
  74415. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74416. if (impostor.mass === 0) {
  74417. return null;
  74418. }
  74419. if (!this._intersectsWithCylinder(impostor)) {
  74420. return null;
  74421. }
  74422. if (impostor.object.getClassName() !== 'Mesh') {
  74423. return null;
  74424. }
  74425. var impostorObject = impostor.object;
  74426. var impostorObjectCenter = impostor.getObjectCenter();
  74427. 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)
  74428. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74429. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74430. var hit = ray.intersectsMesh(impostorObject);
  74431. var contactPoint = hit.pickedPoint;
  74432. if (!contactPoint) {
  74433. return null;
  74434. }
  74435. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74436. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74437. var directionToOrigin = contactPoint.normalize();
  74438. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74439. directionToOrigin = directionToOrigin.negate();
  74440. }
  74441. // TODO: find a more physically based solution
  74442. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74443. var forceX = directionToOrigin.x * this._strength / 8;
  74444. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74445. var forceZ = directionToOrigin.z * this._strength / 8;
  74446. }
  74447. else {
  74448. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74449. var forceY = this._originTop.y * this._updraftMultiplier;
  74450. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74451. }
  74452. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74453. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74454. return { force: force, contactPoint: impostorObjectCenter };
  74455. };
  74456. PhysicsVortexEvent.prototype._tick = function () {
  74457. var _this = this;
  74458. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74459. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74460. if (!impostorForceAndContactPoint) {
  74461. return;
  74462. }
  74463. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74464. });
  74465. };
  74466. /*** Helpers ***/
  74467. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74468. if (!this._cylinder) {
  74469. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74470. height: this._height,
  74471. diameter: this._radius * 2,
  74472. }, this._scene);
  74473. this._cylinder.isVisible = false;
  74474. }
  74475. };
  74476. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74477. var impostorObject = impostor.object;
  74478. this._prepareCylinder();
  74479. this._cylinder.position = this._cylinderPosition;
  74480. return this._cylinder.intersectsMesh(impostorObject, true);
  74481. };
  74482. return PhysicsVortexEvent;
  74483. }());
  74484. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74485. /***** Enums *****/
  74486. /**
  74487. * The strenght of the force in correspondence to the distance of the affected object
  74488. */
  74489. var PhysicsRadialImpulseFalloff;
  74490. (function (PhysicsRadialImpulseFalloff) {
  74491. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74492. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74493. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74494. /**
  74495. * The strenght of the force in correspondence to the distance of the affected object
  74496. */
  74497. var PhysicsUpdraftMode;
  74498. (function (PhysicsUpdraftMode) {
  74499. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74500. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74501. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74502. })(BABYLON || (BABYLON = {}));
  74503. //# sourceMappingURL=babylon.physicsHelper.js.map
  74504. var BABYLON;
  74505. (function (BABYLON) {
  74506. var CannonJSPlugin = /** @class */ (function () {
  74507. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74508. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74509. if (iterations === void 0) { iterations = 10; }
  74510. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74511. this.name = "CannonJSPlugin";
  74512. this._physicsMaterials = new Array();
  74513. this._fixedTimeStep = 1 / 60;
  74514. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74515. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74516. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74517. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74518. this._tmpPosition = BABYLON.Vector3.Zero();
  74519. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74520. this._tmpUnityRotation = new BABYLON.Quaternion();
  74521. if (!this.isSupported()) {
  74522. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74523. return;
  74524. }
  74525. this._extendNamespace();
  74526. this.world = new this.BJSCANNON.World();
  74527. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74528. this.world.solver.iterations = iterations;
  74529. }
  74530. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74531. this.world.gravity.copy(gravity);
  74532. };
  74533. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74534. this._fixedTimeStep = timeStep;
  74535. };
  74536. CannonJSPlugin.prototype.getTimeStep = function () {
  74537. return this._fixedTimeStep;
  74538. };
  74539. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74540. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74541. };
  74542. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74543. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74544. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74545. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74546. };
  74547. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74548. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74549. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74550. impostor.physicsBody.applyForce(impulse, worldPoint);
  74551. };
  74552. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74553. //parent-child relationship. Does this impostor has a parent impostor?
  74554. if (impostor.parent) {
  74555. if (impostor.physicsBody) {
  74556. this.removePhysicsBody(impostor);
  74557. //TODO is that needed?
  74558. impostor.forceUpdate();
  74559. }
  74560. return;
  74561. }
  74562. //should a new body be created for this impostor?
  74563. if (impostor.isBodyInitRequired()) {
  74564. var shape = this._createShape(impostor);
  74565. //unregister events, if body is being changed
  74566. var oldBody = impostor.physicsBody;
  74567. if (oldBody) {
  74568. this.removePhysicsBody(impostor);
  74569. }
  74570. //create the body and material
  74571. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74572. var bodyCreationObject = {
  74573. mass: impostor.getParam("mass"),
  74574. material: material
  74575. };
  74576. // A simple extend, in case native options were used.
  74577. var nativeOptions = impostor.getParam("nativeOptions");
  74578. for (var key in nativeOptions) {
  74579. if (nativeOptions.hasOwnProperty(key)) {
  74580. bodyCreationObject[key] = nativeOptions[key];
  74581. }
  74582. }
  74583. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74584. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74585. this.world.addEventListener("preStep", impostor.beforeStep);
  74586. this.world.addEventListener("postStep", impostor.afterStep);
  74587. impostor.physicsBody.addShape(shape);
  74588. this.world.add(impostor.physicsBody);
  74589. //try to keep the body moving in the right direction by taking old properties.
  74590. //Should be tested!
  74591. if (oldBody) {
  74592. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74593. impostor.physicsBody[param].copy(oldBody[param]);
  74594. });
  74595. }
  74596. this._processChildMeshes(impostor);
  74597. }
  74598. //now update the body's transformation
  74599. this._updatePhysicsBodyTransformation(impostor);
  74600. };
  74601. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74602. var _this = this;
  74603. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74604. var currentRotation = mainImpostor.object.rotationQuaternion;
  74605. if (meshChildren.length) {
  74606. var processMesh = function (localPosition, mesh) {
  74607. if (!currentRotation || !mesh.rotationQuaternion) {
  74608. return;
  74609. }
  74610. var childImpostor = mesh.getPhysicsImpostor();
  74611. if (childImpostor) {
  74612. var parent = childImpostor.parent;
  74613. if (parent !== mainImpostor) {
  74614. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74615. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74616. if (childImpostor.physicsBody) {
  74617. _this.removePhysicsBody(childImpostor);
  74618. childImpostor.physicsBody = null;
  74619. }
  74620. childImpostor.parent = mainImpostor;
  74621. childImpostor.resetUpdateFlags();
  74622. 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));
  74623. //Add the mass of the children.
  74624. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74625. }
  74626. }
  74627. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74628. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74629. };
  74630. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74631. }
  74632. };
  74633. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74634. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74635. this.world.removeEventListener("preStep", impostor.beforeStep);
  74636. this.world.removeEventListener("postStep", impostor.afterStep);
  74637. this.world.remove(impostor.physicsBody);
  74638. };
  74639. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74640. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74641. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74642. if (!mainBody || !connectedBody) {
  74643. return;
  74644. }
  74645. var constraint;
  74646. var jointData = impostorJoint.joint.jointData;
  74647. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74648. var constraintData = {
  74649. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74650. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74651. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74652. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74653. maxForce: jointData.nativeParams.maxForce,
  74654. collideConnected: !!jointData.collision
  74655. };
  74656. switch (impostorJoint.joint.type) {
  74657. case BABYLON.PhysicsJoint.HingeJoint:
  74658. case BABYLON.PhysicsJoint.Hinge2Joint:
  74659. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74660. break;
  74661. case BABYLON.PhysicsJoint.DistanceJoint:
  74662. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74663. break;
  74664. case BABYLON.PhysicsJoint.SpringJoint:
  74665. var springData = jointData;
  74666. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74667. restLength: springData.length,
  74668. stiffness: springData.stiffness,
  74669. damping: springData.damping,
  74670. localAnchorA: constraintData.pivotA,
  74671. localAnchorB: constraintData.pivotB
  74672. });
  74673. break;
  74674. case BABYLON.PhysicsJoint.LockJoint:
  74675. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74676. break;
  74677. case BABYLON.PhysicsJoint.PointToPointJoint:
  74678. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74679. default:
  74680. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74681. break;
  74682. }
  74683. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74684. constraint.collideConnected = !!jointData.collision;
  74685. impostorJoint.joint.physicsJoint = constraint;
  74686. //don't add spring as constraint, as it is not one.
  74687. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74688. this.world.addConstraint(constraint);
  74689. }
  74690. else {
  74691. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74692. constraint.applyForce();
  74693. });
  74694. }
  74695. };
  74696. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74697. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74698. };
  74699. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74700. var index;
  74701. var mat;
  74702. for (index = 0; index < this._physicsMaterials.length; index++) {
  74703. mat = this._physicsMaterials[index];
  74704. if (mat.friction === friction && mat.restitution === restitution) {
  74705. return mat;
  74706. }
  74707. }
  74708. var currentMat = new this.BJSCANNON.Material(name);
  74709. currentMat.friction = friction;
  74710. currentMat.restitution = restitution;
  74711. this._physicsMaterials.push(currentMat);
  74712. return currentMat;
  74713. };
  74714. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74715. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74716. };
  74717. CannonJSPlugin.prototype._createShape = function (impostor) {
  74718. var object = impostor.object;
  74719. var returnValue;
  74720. var extendSize = impostor.getObjectExtendSize();
  74721. switch (impostor.type) {
  74722. case BABYLON.PhysicsImpostor.SphereImpostor:
  74723. var radiusX = extendSize.x;
  74724. var radiusY = extendSize.y;
  74725. var radiusZ = extendSize.z;
  74726. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74727. break;
  74728. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74729. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74730. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74731. break;
  74732. case BABYLON.PhysicsImpostor.BoxImpostor:
  74733. var box = extendSize.scale(0.5);
  74734. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74735. break;
  74736. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74737. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74738. returnValue = new this.BJSCANNON.Plane();
  74739. break;
  74740. case BABYLON.PhysicsImpostor.MeshImpostor:
  74741. // should transform the vertex data to world coordinates!!
  74742. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74743. var rawFaces = object.getIndices ? object.getIndices() : [];
  74744. if (!rawVerts)
  74745. return;
  74746. // get only scale! so the object could transform correctly.
  74747. var oldPosition = object.position.clone();
  74748. var oldRotation = object.rotation && object.rotation.clone();
  74749. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74750. object.position.copyFromFloats(0, 0, 0);
  74751. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74752. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74753. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74754. var transform = object.computeWorldMatrix(true);
  74755. // convert rawVerts to object space
  74756. var temp = new Array();
  74757. var index;
  74758. for (index = 0; index < rawVerts.length; index += 3) {
  74759. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74760. }
  74761. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74762. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74763. //now set back the transformation!
  74764. object.position.copyFrom(oldPosition);
  74765. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74766. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74767. break;
  74768. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74769. var oldPosition2 = object.position.clone();
  74770. var oldRotation2 = object.rotation && object.rotation.clone();
  74771. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74772. object.position.copyFromFloats(0, 0, 0);
  74773. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74774. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74775. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74776. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74777. returnValue = this._createHeightmap(object);
  74778. object.position.copyFrom(oldPosition2);
  74779. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74780. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74781. object.computeWorldMatrix(true);
  74782. break;
  74783. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74784. returnValue = new this.BJSCANNON.Particle();
  74785. break;
  74786. }
  74787. return returnValue;
  74788. };
  74789. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74790. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74791. var transform = object.computeWorldMatrix(true);
  74792. // convert rawVerts to object space
  74793. var temp = new Array();
  74794. var index;
  74795. for (index = 0; index < pos.length; index += 3) {
  74796. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74797. }
  74798. pos = temp;
  74799. var matrix = new Array();
  74800. //For now pointDepth will not be used and will be automatically calculated.
  74801. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74802. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74803. var boundingInfo = object.getBoundingInfo();
  74804. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74805. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74806. var elementSize = dim * 2 / arraySize;
  74807. for (var i = 0; i < pos.length; i = i + 3) {
  74808. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74809. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74810. var y = -pos[i + 2] + minY;
  74811. if (!matrix[x]) {
  74812. matrix[x] = [];
  74813. }
  74814. if (!matrix[x][z]) {
  74815. matrix[x][z] = y;
  74816. }
  74817. matrix[x][z] = Math.max(y, matrix[x][z]);
  74818. }
  74819. for (var x = 0; x <= arraySize; ++x) {
  74820. if (!matrix[x]) {
  74821. var loc = 1;
  74822. while (!matrix[(x + loc) % arraySize]) {
  74823. loc++;
  74824. }
  74825. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74826. //console.log("missing x", x);
  74827. }
  74828. for (var z = 0; z <= arraySize; ++z) {
  74829. if (!matrix[x][z]) {
  74830. var loc = 1;
  74831. var newValue;
  74832. while (newValue === undefined) {
  74833. newValue = matrix[x][(z + loc++) % arraySize];
  74834. }
  74835. matrix[x][z] = newValue;
  74836. }
  74837. }
  74838. }
  74839. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74840. elementSize: elementSize
  74841. });
  74842. //For future reference, needed for body transformation
  74843. shape.minY = minY;
  74844. return shape;
  74845. };
  74846. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74847. var object = impostor.object;
  74848. //make sure it is updated...
  74849. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74850. // The delta between the mesh position and the mesh bounding box center
  74851. var bInfo = object.getBoundingInfo();
  74852. if (!bInfo)
  74853. return;
  74854. var center = impostor.getObjectCenter();
  74855. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74856. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74857. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74858. this._tmpPosition.copyFrom(center);
  74859. var quaternion = object.rotationQuaternion;
  74860. if (!quaternion) {
  74861. return;
  74862. }
  74863. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74864. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74865. //-90 DEG in X, precalculated
  74866. quaternion = quaternion.multiply(this._minus90X);
  74867. //Invert! (Precalculated, 90 deg in X)
  74868. //No need to clone. this will never change.
  74869. impostor.setDeltaRotation(this._plus90X);
  74870. }
  74871. //If it is a heightfield, if should be centered.
  74872. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74873. var mesh = object;
  74874. var boundingInfo = mesh.getBoundingInfo();
  74875. //calculate the correct body position:
  74876. var rotationQuaternion = mesh.rotationQuaternion;
  74877. mesh.rotationQuaternion = this._tmpUnityRotation;
  74878. mesh.computeWorldMatrix(true);
  74879. //get original center with no rotation
  74880. var c = center.clone();
  74881. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74882. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74883. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74884. mesh.setPreTransformMatrix(p);
  74885. mesh.computeWorldMatrix(true);
  74886. //calculate the translation
  74887. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74888. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74889. //add it inverted to the delta
  74890. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74891. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74892. //rotation is back
  74893. mesh.rotationQuaternion = rotationQuaternion;
  74894. mesh.setPreTransformMatrix(oldPivot);
  74895. mesh.computeWorldMatrix(true);
  74896. }
  74897. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74898. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74899. //this._tmpPosition.copyFrom(object.position);
  74900. }
  74901. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74902. //Now update the impostor object
  74903. impostor.physicsBody.position.copy(this._tmpPosition);
  74904. impostor.physicsBody.quaternion.copy(quaternion);
  74905. };
  74906. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74907. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74908. if (impostor.object.rotationQuaternion) {
  74909. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  74910. }
  74911. };
  74912. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74913. impostor.physicsBody.position.copy(newPosition);
  74914. impostor.physicsBody.quaternion.copy(newRotation);
  74915. };
  74916. CannonJSPlugin.prototype.isSupported = function () {
  74917. return this.BJSCANNON !== undefined;
  74918. };
  74919. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74920. impostor.physicsBody.velocity.copy(velocity);
  74921. };
  74922. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74923. impostor.physicsBody.angularVelocity.copy(velocity);
  74924. };
  74925. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74926. var v = impostor.physicsBody.velocity;
  74927. if (!v) {
  74928. return null;
  74929. }
  74930. return new BABYLON.Vector3(v.x, v.y, v.z);
  74931. };
  74932. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74933. var v = impostor.physicsBody.angularVelocity;
  74934. if (!v) {
  74935. return null;
  74936. }
  74937. return new BABYLON.Vector3(v.x, v.y, v.z);
  74938. };
  74939. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74940. impostor.physicsBody.mass = mass;
  74941. impostor.physicsBody.updateMassProperties();
  74942. };
  74943. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  74944. return impostor.physicsBody.mass;
  74945. };
  74946. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  74947. return impostor.physicsBody.material.friction;
  74948. };
  74949. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74950. impostor.physicsBody.material.friction = friction;
  74951. };
  74952. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74953. return impostor.physicsBody.material.restitution;
  74954. };
  74955. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74956. impostor.physicsBody.material.restitution = restitution;
  74957. };
  74958. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  74959. impostor.physicsBody.sleep();
  74960. };
  74961. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  74962. impostor.physicsBody.wakeUp();
  74963. };
  74964. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74965. joint.physicsJoint.distance = maxDistance;
  74966. };
  74967. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74968. // if (!motorIndex) {
  74969. // joint.physicsJoint.enableMotor();
  74970. // }
  74971. // }
  74972. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74973. // if (!motorIndex) {
  74974. // joint.physicsJoint.disableMotor();
  74975. // }
  74976. // }
  74977. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74978. if (!motorIndex) {
  74979. joint.physicsJoint.enableMotor();
  74980. joint.physicsJoint.setMotorSpeed(speed);
  74981. if (maxForce) {
  74982. this.setLimit(joint, maxForce);
  74983. }
  74984. }
  74985. };
  74986. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  74987. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  74988. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  74989. };
  74990. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74991. var body = impostor.physicsBody;
  74992. mesh.position.x = body.position.x;
  74993. mesh.position.y = body.position.y;
  74994. mesh.position.z = body.position.z;
  74995. if (mesh.rotationQuaternion) {
  74996. mesh.rotationQuaternion.x = body.quaternion.x;
  74997. mesh.rotationQuaternion.y = body.quaternion.y;
  74998. mesh.rotationQuaternion.z = body.quaternion.z;
  74999. mesh.rotationQuaternion.w = body.quaternion.w;
  75000. }
  75001. };
  75002. CannonJSPlugin.prototype.getRadius = function (impostor) {
  75003. var shape = impostor.physicsBody.shapes[0];
  75004. return shape.boundingSphereRadius;
  75005. };
  75006. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75007. var shape = impostor.physicsBody.shapes[0];
  75008. result.x = shape.halfExtents.x * 2;
  75009. result.y = shape.halfExtents.y * 2;
  75010. result.z = shape.halfExtents.z * 2;
  75011. };
  75012. CannonJSPlugin.prototype.dispose = function () {
  75013. };
  75014. CannonJSPlugin.prototype._extendNamespace = function () {
  75015. //this will force cannon to execute at least one step when using interpolation
  75016. var step_tmp1 = new this.BJSCANNON.Vec3();
  75017. var Engine = this.BJSCANNON;
  75018. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  75019. maxSubSteps = maxSubSteps || 10;
  75020. timeSinceLastCalled = timeSinceLastCalled || 0;
  75021. if (timeSinceLastCalled === 0) {
  75022. this.internalStep(dt);
  75023. this.time += dt;
  75024. }
  75025. else {
  75026. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  75027. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  75028. var t0 = performance.now();
  75029. for (var i = 0; i !== internalSteps; i++) {
  75030. this.internalStep(dt);
  75031. if (performance.now() - t0 > dt * 1000) {
  75032. break;
  75033. }
  75034. }
  75035. this.time += timeSinceLastCalled;
  75036. var h = this.time % dt;
  75037. var h_div_dt = h / dt;
  75038. var interpvelo = step_tmp1;
  75039. var bodies = this.bodies;
  75040. for (var j = 0; j !== bodies.length; j++) {
  75041. var b = bodies[j];
  75042. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  75043. b.position.vsub(b.previousPosition, interpvelo);
  75044. interpvelo.scale(h_div_dt, interpvelo);
  75045. b.position.vadd(interpvelo, b.interpolatedPosition);
  75046. }
  75047. else {
  75048. b.interpolatedPosition.copy(b.position);
  75049. b.interpolatedQuaternion.copy(b.quaternion);
  75050. }
  75051. }
  75052. }
  75053. };
  75054. };
  75055. return CannonJSPlugin;
  75056. }());
  75057. BABYLON.CannonJSPlugin = CannonJSPlugin;
  75058. })(BABYLON || (BABYLON = {}));
  75059. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  75060. var BABYLON;
  75061. (function (BABYLON) {
  75062. var OimoJSPlugin = /** @class */ (function () {
  75063. function OimoJSPlugin(iterations) {
  75064. this.name = "OimoJSPlugin";
  75065. this._tmpImpostorsArray = [];
  75066. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75067. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  75068. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75069. this.world.worldscale(1);
  75070. this.world.clear();
  75071. //making sure no stats are calculated
  75072. this.world.isNoStat = true;
  75073. }
  75074. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75075. this.world.gravity.copy(gravity);
  75076. };
  75077. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75078. this.world.timeStep = timeStep;
  75079. };
  75080. OimoJSPlugin.prototype.getTimeStep = function () {
  75081. return this.world.timeStep;
  75082. };
  75083. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75084. var _this = this;
  75085. impostors.forEach(function (impostor) {
  75086. impostor.beforeStep();
  75087. });
  75088. this.world.step();
  75089. impostors.forEach(function (impostor) {
  75090. impostor.afterStep();
  75091. //update the ordered impostors array
  75092. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75093. });
  75094. //check for collisions
  75095. var contact = this.world.contacts;
  75096. while (contact !== null) {
  75097. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75098. contact = contact.next;
  75099. continue;
  75100. }
  75101. //is this body colliding with any other? get the impostor
  75102. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75103. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75104. if (!mainImpostor || !collidingImpostor) {
  75105. contact = contact.next;
  75106. continue;
  75107. }
  75108. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75109. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75110. contact = contact.next;
  75111. }
  75112. };
  75113. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75114. var mass = impostor.physicsBody.massInfo.mass;
  75115. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75116. };
  75117. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75118. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75119. this.applyImpulse(impostor, force, contactPoint);
  75120. };
  75121. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75122. var _this = this;
  75123. //parent-child relationship. Does this impostor has a parent impostor?
  75124. if (impostor.parent) {
  75125. if (impostor.physicsBody) {
  75126. this.removePhysicsBody(impostor);
  75127. //TODO is that needed?
  75128. impostor.forceUpdate();
  75129. }
  75130. return;
  75131. }
  75132. if (impostor.isBodyInitRequired()) {
  75133. var bodyConfig = {
  75134. name: impostor.uniqueId,
  75135. //Oimo must have mass, also for static objects.
  75136. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75137. size: [],
  75138. type: [],
  75139. pos: [],
  75140. rot: [],
  75141. move: impostor.getParam("mass") !== 0,
  75142. //Supporting older versions of Oimo
  75143. world: this.world
  75144. };
  75145. var impostors = [impostor];
  75146. var addToArray = function (parent) {
  75147. if (!parent.getChildMeshes)
  75148. return;
  75149. parent.getChildMeshes().forEach(function (m) {
  75150. if (m.physicsImpostor) {
  75151. impostors.push(m.physicsImpostor);
  75152. //m.physicsImpostor._init();
  75153. }
  75154. });
  75155. };
  75156. addToArray(impostor.object);
  75157. var checkWithEpsilon_1 = function (value) {
  75158. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75159. };
  75160. impostors.forEach(function (i) {
  75161. if (!impostor.object.rotationQuaternion) {
  75162. return;
  75163. }
  75164. //get the correct bounding box
  75165. var oldQuaternion = i.object.rotationQuaternion;
  75166. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75167. x: impostor.object.rotationQuaternion.x,
  75168. y: impostor.object.rotationQuaternion.y,
  75169. z: impostor.object.rotationQuaternion.z,
  75170. s: impostor.object.rotationQuaternion.w
  75171. });
  75172. var extendSize = i.getObjectExtendSize();
  75173. if (i === impostor) {
  75174. var center = impostor.getObjectCenter();
  75175. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75176. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75177. //Can also use Array.prototype.push.apply
  75178. bodyConfig.pos.push(center.x);
  75179. bodyConfig.pos.push(center.y);
  75180. bodyConfig.pos.push(center.z);
  75181. //tmp solution
  75182. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75183. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75184. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75185. }
  75186. else {
  75187. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75188. bodyConfig.pos.push(localPosition.x);
  75189. bodyConfig.pos.push(localPosition.y);
  75190. bodyConfig.pos.push(localPosition.z);
  75191. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75192. bodyConfig.rot.push(0);
  75193. bodyConfig.rot.push(0);
  75194. bodyConfig.rot.push(0);
  75195. }
  75196. // register mesh
  75197. switch (i.type) {
  75198. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75199. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75200. case BABYLON.PhysicsImpostor.SphereImpostor:
  75201. var radiusX = extendSize.x;
  75202. var radiusY = extendSize.y;
  75203. var radiusZ = extendSize.z;
  75204. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75205. bodyConfig.type.push('sphere');
  75206. //due to the way oimo works with compounds, add 3 times
  75207. bodyConfig.size.push(size);
  75208. bodyConfig.size.push(size);
  75209. bodyConfig.size.push(size);
  75210. break;
  75211. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75212. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75213. var sizeY = checkWithEpsilon_1(extendSize.y);
  75214. bodyConfig.type.push('cylinder');
  75215. bodyConfig.size.push(sizeX);
  75216. bodyConfig.size.push(sizeY);
  75217. //due to the way oimo works with compounds, add one more value.
  75218. bodyConfig.size.push(sizeY);
  75219. break;
  75220. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75221. case BABYLON.PhysicsImpostor.BoxImpostor:
  75222. default:
  75223. var sizeX = checkWithEpsilon_1(extendSize.x);
  75224. var sizeY = checkWithEpsilon_1(extendSize.y);
  75225. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75226. bodyConfig.type.push('box');
  75227. bodyConfig.size.push(sizeX);
  75228. bodyConfig.size.push(sizeY);
  75229. bodyConfig.size.push(sizeZ);
  75230. break;
  75231. }
  75232. //actually not needed, but hey...
  75233. i.object.rotationQuaternion = oldQuaternion;
  75234. });
  75235. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75236. }
  75237. else {
  75238. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75239. }
  75240. impostor.setDeltaPosition(this._tmpPositionVector);
  75241. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75242. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75243. };
  75244. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75245. //impostor.physicsBody.dispose();
  75246. //Same as : (older oimo versions)
  75247. this.world.removeRigidBody(impostor.physicsBody);
  75248. };
  75249. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75250. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75251. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75252. if (!mainBody || !connectedBody) {
  75253. return;
  75254. }
  75255. var jointData = impostorJoint.joint.jointData;
  75256. var options = jointData.nativeParams || {};
  75257. var type;
  75258. var nativeJointData = {
  75259. body1: mainBody,
  75260. body2: connectedBody,
  75261. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75262. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75263. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75264. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75265. min: options.min,
  75266. max: options.max,
  75267. collision: options.collision || jointData.collision,
  75268. spring: options.spring,
  75269. //supporting older version of Oimo
  75270. world: this.world
  75271. };
  75272. switch (impostorJoint.joint.type) {
  75273. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75274. type = "jointBall";
  75275. break;
  75276. case BABYLON.PhysicsJoint.SpringJoint:
  75277. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75278. var springData = jointData;
  75279. nativeJointData.min = springData.length || nativeJointData.min;
  75280. //Max should also be set, just make sure it is at least min
  75281. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75282. case BABYLON.PhysicsJoint.DistanceJoint:
  75283. type = "jointDistance";
  75284. nativeJointData.max = jointData.maxDistance;
  75285. break;
  75286. case BABYLON.PhysicsJoint.PrismaticJoint:
  75287. type = "jointPrisme";
  75288. break;
  75289. case BABYLON.PhysicsJoint.SliderJoint:
  75290. type = "jointSlide";
  75291. break;
  75292. case BABYLON.PhysicsJoint.WheelJoint:
  75293. type = "jointWheel";
  75294. break;
  75295. case BABYLON.PhysicsJoint.HingeJoint:
  75296. default:
  75297. type = "jointHinge";
  75298. break;
  75299. }
  75300. nativeJointData.type = type;
  75301. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75302. };
  75303. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75304. //Bug in Oimo prevents us from disposing a joint in the playground
  75305. //joint.joint.physicsJoint.dispose();
  75306. //So we will bruteforce it!
  75307. try {
  75308. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75309. }
  75310. catch (e) {
  75311. BABYLON.Tools.Warn(e);
  75312. }
  75313. };
  75314. OimoJSPlugin.prototype.isSupported = function () {
  75315. return this.BJSOIMO !== undefined;
  75316. };
  75317. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75318. if (!impostor.physicsBody.sleeping) {
  75319. //TODO check that
  75320. if (impostor.physicsBody.shapes.next) {
  75321. var parentShape = this._getLastShape(impostor.physicsBody);
  75322. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75323. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75324. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75325. }
  75326. else {
  75327. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75328. }
  75329. if (impostor.object.rotationQuaternion) {
  75330. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75331. impostor.object.rotationQuaternion.normalize();
  75332. }
  75333. }
  75334. };
  75335. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75336. var body = impostor.physicsBody;
  75337. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75338. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75339. body.syncShapes();
  75340. body.awake();
  75341. };
  75342. OimoJSPlugin.prototype._getLastShape = function (body) {
  75343. var lastShape = body.shapes;
  75344. while (lastShape.next) {
  75345. lastShape = lastShape.next;
  75346. }
  75347. return lastShape;
  75348. };
  75349. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75350. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75351. };
  75352. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75353. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75354. };
  75355. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75356. var v = impostor.physicsBody.linearVelocity;
  75357. if (!v) {
  75358. return null;
  75359. }
  75360. return new BABYLON.Vector3(v.x, v.y, v.z);
  75361. };
  75362. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75363. var v = impostor.physicsBody.angularVelocity;
  75364. if (!v) {
  75365. return null;
  75366. }
  75367. return new BABYLON.Vector3(v.x, v.y, v.z);
  75368. };
  75369. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75370. var staticBody = mass === 0;
  75371. //this will actually set the body's density and not its mass.
  75372. //But this is how oimo treats the mass variable.
  75373. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75374. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75375. };
  75376. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75377. return impostor.physicsBody.shapes.density;
  75378. };
  75379. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75380. return impostor.physicsBody.shapes.friction;
  75381. };
  75382. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75383. impostor.physicsBody.shapes.friction = friction;
  75384. };
  75385. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75386. return impostor.physicsBody.shapes.restitution;
  75387. };
  75388. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75389. impostor.physicsBody.shapes.restitution = restitution;
  75390. };
  75391. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75392. impostor.physicsBody.sleep();
  75393. };
  75394. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75395. impostor.physicsBody.awake();
  75396. };
  75397. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75398. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75399. if (minDistance !== void 0) {
  75400. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75401. }
  75402. };
  75403. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75404. //TODO separate rotational and transational motors.
  75405. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75406. if (motor) {
  75407. motor.setMotor(speed, maxForce);
  75408. }
  75409. };
  75410. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75411. //TODO separate rotational and transational motors.
  75412. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75413. if (motor) {
  75414. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75415. }
  75416. };
  75417. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75418. var body = impostor.physicsBody;
  75419. mesh.position.x = body.position.x;
  75420. mesh.position.y = body.position.y;
  75421. mesh.position.z = body.position.z;
  75422. if (mesh.rotationQuaternion) {
  75423. mesh.rotationQuaternion.x = body.orientation.x;
  75424. mesh.rotationQuaternion.y = body.orientation.y;
  75425. mesh.rotationQuaternion.z = body.orientation.z;
  75426. mesh.rotationQuaternion.w = body.orientation.s;
  75427. }
  75428. };
  75429. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75430. return impostor.physicsBody.shapes.radius;
  75431. };
  75432. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75433. var shape = impostor.physicsBody.shapes;
  75434. result.x = shape.halfWidth * 2;
  75435. result.y = shape.halfHeight * 2;
  75436. result.z = shape.halfDepth * 2;
  75437. };
  75438. OimoJSPlugin.prototype.dispose = function () {
  75439. this.world.clear();
  75440. };
  75441. return OimoJSPlugin;
  75442. }());
  75443. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75444. })(BABYLON || (BABYLON = {}));
  75445. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75446. var BABYLON;
  75447. (function (BABYLON) {
  75448. /*
  75449. * Based on jsTGALoader - Javascript loader for TGA file
  75450. * By Vincent Thibault
  75451. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75452. */
  75453. var TGATools = /** @class */ (function () {
  75454. function TGATools() {
  75455. }
  75456. TGATools.GetTGAHeader = function (data) {
  75457. var offset = 0;
  75458. var header = {
  75459. id_length: data[offset++],
  75460. colormap_type: data[offset++],
  75461. image_type: data[offset++],
  75462. colormap_index: data[offset++] | data[offset++] << 8,
  75463. colormap_length: data[offset++] | data[offset++] << 8,
  75464. colormap_size: data[offset++],
  75465. origin: [
  75466. data[offset++] | data[offset++] << 8,
  75467. data[offset++] | data[offset++] << 8
  75468. ],
  75469. width: data[offset++] | data[offset++] << 8,
  75470. height: data[offset++] | data[offset++] << 8,
  75471. pixel_size: data[offset++],
  75472. flags: data[offset++]
  75473. };
  75474. return header;
  75475. };
  75476. TGATools.UploadContent = function (gl, data) {
  75477. // Not enough data to contain header ?
  75478. if (data.length < 19) {
  75479. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75480. return;
  75481. }
  75482. // Read Header
  75483. var offset = 18;
  75484. var header = TGATools.GetTGAHeader(data);
  75485. // Assume it's a valid Targa file.
  75486. if (header.id_length + offset > data.length) {
  75487. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75488. return;
  75489. }
  75490. // Skip not needed data
  75491. offset += header.id_length;
  75492. var use_rle = false;
  75493. var use_pal = false;
  75494. var use_grey = false;
  75495. // Get some informations.
  75496. switch (header.image_type) {
  75497. case TGATools._TYPE_RLE_INDEXED:
  75498. use_rle = true;
  75499. case TGATools._TYPE_INDEXED:
  75500. use_pal = true;
  75501. break;
  75502. case TGATools._TYPE_RLE_RGB:
  75503. use_rle = true;
  75504. case TGATools._TYPE_RGB:
  75505. // use_rgb = true;
  75506. break;
  75507. case TGATools._TYPE_RLE_GREY:
  75508. use_rle = true;
  75509. case TGATools._TYPE_GREY:
  75510. use_grey = true;
  75511. break;
  75512. }
  75513. var pixel_data;
  75514. // var numAlphaBits = header.flags & 0xf;
  75515. var pixel_size = header.pixel_size >> 3;
  75516. var pixel_total = header.width * header.height * pixel_size;
  75517. // Read palettes
  75518. var palettes;
  75519. if (use_pal) {
  75520. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75521. }
  75522. // Read LRE
  75523. if (use_rle) {
  75524. pixel_data = new Uint8Array(pixel_total);
  75525. var c, count, i;
  75526. var localOffset = 0;
  75527. var pixels = new Uint8Array(pixel_size);
  75528. while (offset < pixel_total && localOffset < pixel_total) {
  75529. c = data[offset++];
  75530. count = (c & 0x7f) + 1;
  75531. // RLE pixels
  75532. if (c & 0x80) {
  75533. // Bind pixel tmp array
  75534. for (i = 0; i < pixel_size; ++i) {
  75535. pixels[i] = data[offset++];
  75536. }
  75537. // Copy pixel array
  75538. for (i = 0; i < count; ++i) {
  75539. pixel_data.set(pixels, localOffset + i * pixel_size);
  75540. }
  75541. localOffset += pixel_size * count;
  75542. }
  75543. else {
  75544. count *= pixel_size;
  75545. for (i = 0; i < count; ++i) {
  75546. pixel_data[localOffset + i] = data[offset++];
  75547. }
  75548. localOffset += count;
  75549. }
  75550. }
  75551. }
  75552. else {
  75553. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75554. }
  75555. // Load to texture
  75556. var x_start, y_start, x_step, y_step, y_end, x_end;
  75557. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75558. default:
  75559. case TGATools._ORIGIN_UL:
  75560. x_start = 0;
  75561. x_step = 1;
  75562. x_end = header.width;
  75563. y_start = 0;
  75564. y_step = 1;
  75565. y_end = header.height;
  75566. break;
  75567. case TGATools._ORIGIN_BL:
  75568. x_start = 0;
  75569. x_step = 1;
  75570. x_end = header.width;
  75571. y_start = header.height - 1;
  75572. y_step = -1;
  75573. y_end = -1;
  75574. break;
  75575. case TGATools._ORIGIN_UR:
  75576. x_start = header.width - 1;
  75577. x_step = -1;
  75578. x_end = -1;
  75579. y_start = 0;
  75580. y_step = 1;
  75581. y_end = header.height;
  75582. break;
  75583. case TGATools._ORIGIN_BR:
  75584. x_start = header.width - 1;
  75585. x_step = -1;
  75586. x_end = -1;
  75587. y_start = header.height - 1;
  75588. y_step = -1;
  75589. y_end = -1;
  75590. break;
  75591. }
  75592. // Load the specify method
  75593. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75594. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75595. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75596. };
  75597. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75598. var image = pixel_data, colormap = palettes;
  75599. var width = header.width, height = header.height;
  75600. var color, i = 0, x, y;
  75601. var imageData = new Uint8Array(width * height * 4);
  75602. for (y = y_start; y !== y_end; y += y_step) {
  75603. for (x = x_start; x !== x_end; x += x_step, i++) {
  75604. color = image[i];
  75605. imageData[(x + width * y) * 4 + 3] = 255;
  75606. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75607. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75608. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75609. }
  75610. }
  75611. return imageData;
  75612. };
  75613. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75614. var image = pixel_data;
  75615. var width = header.width, height = header.height;
  75616. var color, i = 0, x, y;
  75617. var imageData = new Uint8Array(width * height * 4);
  75618. for (y = y_start; y !== y_end; y += y_step) {
  75619. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75620. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75621. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75622. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75623. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75624. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75625. }
  75626. }
  75627. return imageData;
  75628. };
  75629. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75630. var image = pixel_data;
  75631. var width = header.width, height = header.height;
  75632. var i = 0, x, y;
  75633. var imageData = new Uint8Array(width * height * 4);
  75634. for (y = y_start; y !== y_end; y += y_step) {
  75635. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75636. imageData[(x + width * y) * 4 + 3] = 255;
  75637. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75638. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75639. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75640. }
  75641. }
  75642. return imageData;
  75643. };
  75644. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75645. var image = pixel_data;
  75646. var width = header.width, height = header.height;
  75647. var i = 0, x, y;
  75648. var imageData = new Uint8Array(width * height * 4);
  75649. for (y = y_start; y !== y_end; y += y_step) {
  75650. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75651. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75652. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75653. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75654. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75655. }
  75656. }
  75657. return imageData;
  75658. };
  75659. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75660. var image = pixel_data;
  75661. var width = header.width, height = header.height;
  75662. var color, i = 0, x, y;
  75663. var imageData = new Uint8Array(width * height * 4);
  75664. for (y = y_start; y !== y_end; y += y_step) {
  75665. for (x = x_start; x !== x_end; x += x_step, i++) {
  75666. color = image[i];
  75667. imageData[(x + width * y) * 4 + 0] = color;
  75668. imageData[(x + width * y) * 4 + 1] = color;
  75669. imageData[(x + width * y) * 4 + 2] = color;
  75670. imageData[(x + width * y) * 4 + 3] = 255;
  75671. }
  75672. }
  75673. return imageData;
  75674. };
  75675. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75676. var image = pixel_data;
  75677. var width = header.width, height = header.height;
  75678. var i = 0, x, y;
  75679. var imageData = new Uint8Array(width * height * 4);
  75680. for (y = y_start; y !== y_end; y += y_step) {
  75681. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75682. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75683. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75684. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75685. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75686. }
  75687. }
  75688. return imageData;
  75689. };
  75690. //private static _TYPE_NO_DATA = 0;
  75691. TGATools._TYPE_INDEXED = 1;
  75692. TGATools._TYPE_RGB = 2;
  75693. TGATools._TYPE_GREY = 3;
  75694. TGATools._TYPE_RLE_INDEXED = 9;
  75695. TGATools._TYPE_RLE_RGB = 10;
  75696. TGATools._TYPE_RLE_GREY = 11;
  75697. TGATools._ORIGIN_MASK = 0x30;
  75698. TGATools._ORIGIN_SHIFT = 0x04;
  75699. TGATools._ORIGIN_BL = 0x00;
  75700. TGATools._ORIGIN_BR = 0x01;
  75701. TGATools._ORIGIN_UL = 0x02;
  75702. TGATools._ORIGIN_UR = 0x03;
  75703. return TGATools;
  75704. }());
  75705. BABYLON.TGATools = TGATools;
  75706. })(BABYLON || (BABYLON = {}));
  75707. //# sourceMappingURL=babylon.tga.js.map
  75708. var BABYLON;
  75709. (function (BABYLON) {
  75710. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75711. // All values and structures referenced from:
  75712. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75713. var DDS_MAGIC = 0x20534444;
  75714. var
  75715. //DDSD_CAPS = 0x1,
  75716. //DDSD_HEIGHT = 0x2,
  75717. //DDSD_WIDTH = 0x4,
  75718. //DDSD_PITCH = 0x8,
  75719. //DDSD_PIXELFORMAT = 0x1000,
  75720. DDSD_MIPMAPCOUNT = 0x20000;
  75721. //DDSD_LINEARSIZE = 0x80000,
  75722. //DDSD_DEPTH = 0x800000;
  75723. // var DDSCAPS_COMPLEX = 0x8,
  75724. // DDSCAPS_MIPMAP = 0x400000,
  75725. // DDSCAPS_TEXTURE = 0x1000;
  75726. var DDSCAPS2_CUBEMAP = 0x200;
  75727. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75728. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75729. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75730. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75731. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75732. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75733. // DDSCAPS2_VOLUME = 0x200000;
  75734. var
  75735. //DDPF_ALPHAPIXELS = 0x1,
  75736. //DDPF_ALPHA = 0x2,
  75737. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75738. //DDPF_YUV = 0x200,
  75739. DDPF_LUMINANCE = 0x20000;
  75740. function FourCCToInt32(value) {
  75741. return value.charCodeAt(0) +
  75742. (value.charCodeAt(1) << 8) +
  75743. (value.charCodeAt(2) << 16) +
  75744. (value.charCodeAt(3) << 24);
  75745. }
  75746. function Int32ToFourCC(value) {
  75747. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75748. }
  75749. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75750. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75751. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75752. var FOURCC_DX10 = FourCCToInt32("DX10");
  75753. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75754. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75755. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75756. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75757. var headerLengthInt = 31; // The header length in 32 bit ints
  75758. // Offsets into the header array
  75759. var off_magic = 0;
  75760. var off_size = 1;
  75761. var off_flags = 2;
  75762. var off_height = 3;
  75763. var off_width = 4;
  75764. var off_mipmapCount = 7;
  75765. var off_pfFlags = 20;
  75766. var off_pfFourCC = 21;
  75767. var off_RGBbpp = 22;
  75768. var off_RMask = 23;
  75769. var off_GMask = 24;
  75770. var off_BMask = 25;
  75771. var off_AMask = 26;
  75772. // var off_caps1 = 27;
  75773. var off_caps2 = 28;
  75774. // var off_caps3 = 29;
  75775. // var off_caps4 = 30;
  75776. var off_dxgiFormat = 32;
  75777. ;
  75778. var DDSTools = /** @class */ (function () {
  75779. function DDSTools() {
  75780. }
  75781. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75782. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75783. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75784. var mipmapCount = 1;
  75785. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75786. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75787. }
  75788. var fourCC = header[off_pfFourCC];
  75789. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75790. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75791. switch (fourCC) {
  75792. case FOURCC_D3DFMT_R16G16B16A16F:
  75793. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75794. break;
  75795. case FOURCC_D3DFMT_R32G32B32A32F:
  75796. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75797. break;
  75798. case FOURCC_DX10:
  75799. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75800. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75801. break;
  75802. }
  75803. }
  75804. return {
  75805. width: header[off_width],
  75806. height: header[off_height],
  75807. mipmapCount: mipmapCount,
  75808. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75809. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75810. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75811. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75812. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75813. dxgiFormat: dxgiFormat,
  75814. textureType: textureType
  75815. };
  75816. };
  75817. DDSTools._ToHalfFloat = function (value) {
  75818. if (!DDSTools._FloatView) {
  75819. DDSTools._FloatView = new Float32Array(1);
  75820. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75821. }
  75822. DDSTools._FloatView[0] = value;
  75823. var x = DDSTools._Int32View[0];
  75824. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75825. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75826. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75827. /* If zero, or denormal, or exponent underflows too much for a denormal
  75828. * half, return signed zero. */
  75829. if (e < 103) {
  75830. return bits;
  75831. }
  75832. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75833. if (e > 142) {
  75834. bits |= 0x7c00;
  75835. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75836. * not Inf, so make sure we set one mantissa bit too. */
  75837. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75838. return bits;
  75839. }
  75840. /* If exponent underflows but not too much, return a denormal */
  75841. if (e < 113) {
  75842. m |= 0x0800;
  75843. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75844. * to 1, which is OK. */
  75845. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75846. return bits;
  75847. }
  75848. bits |= ((e - 112) << 10) | (m >> 1);
  75849. bits += m & 1;
  75850. return bits;
  75851. };
  75852. DDSTools._FromHalfFloat = function (value) {
  75853. var s = (value & 0x8000) >> 15;
  75854. var e = (value & 0x7C00) >> 10;
  75855. var f = value & 0x03FF;
  75856. if (e === 0) {
  75857. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75858. }
  75859. else if (e == 0x1F) {
  75860. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75861. }
  75862. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75863. };
  75864. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75865. var destArray = new Float32Array(dataLength);
  75866. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75867. var index = 0;
  75868. for (var y = 0; y < height; y++) {
  75869. for (var x = 0; x < width; x++) {
  75870. var srcPos = (x + y * width) * 4;
  75871. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75872. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75873. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75874. if (DDSTools.StoreLODInAlphaChannel) {
  75875. destArray[index + 3] = lod;
  75876. }
  75877. else {
  75878. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75879. }
  75880. index += 4;
  75881. }
  75882. }
  75883. return destArray;
  75884. };
  75885. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75886. if (DDSTools.StoreLODInAlphaChannel) {
  75887. var destArray = new Uint16Array(dataLength);
  75888. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75889. var index = 0;
  75890. for (var y = 0; y < height; y++) {
  75891. for (var x = 0; x < width; x++) {
  75892. var srcPos = (x + y * width) * 4;
  75893. destArray[index] = srcData[srcPos];
  75894. destArray[index + 1] = srcData[srcPos + 1];
  75895. destArray[index + 2] = srcData[srcPos + 2];
  75896. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75897. index += 4;
  75898. }
  75899. }
  75900. return destArray;
  75901. }
  75902. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75903. };
  75904. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75905. if (DDSTools.StoreLODInAlphaChannel) {
  75906. var destArray = new Float32Array(dataLength);
  75907. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75908. var index = 0;
  75909. for (var y = 0; y < height; y++) {
  75910. for (var x = 0; x < width; x++) {
  75911. var srcPos = (x + y * width) * 4;
  75912. destArray[index] = srcData[srcPos];
  75913. destArray[index + 1] = srcData[srcPos + 1];
  75914. destArray[index + 2] = srcData[srcPos + 2];
  75915. destArray[index + 3] = lod;
  75916. index += 4;
  75917. }
  75918. }
  75919. return destArray;
  75920. }
  75921. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  75922. };
  75923. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75924. var destArray = new Uint8Array(dataLength);
  75925. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75926. var index = 0;
  75927. for (var y = 0; y < height; y++) {
  75928. for (var x = 0; x < width; x++) {
  75929. var srcPos = (x + y * width) * 4;
  75930. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  75931. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  75932. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  75933. if (DDSTools.StoreLODInAlphaChannel) {
  75934. destArray[index + 3] = lod;
  75935. }
  75936. else {
  75937. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  75938. }
  75939. index += 4;
  75940. }
  75941. }
  75942. return destArray;
  75943. };
  75944. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75945. var destArray = new Uint8Array(dataLength);
  75946. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75947. var index = 0;
  75948. for (var y = 0; y < height; y++) {
  75949. for (var x = 0; x < width; x++) {
  75950. var srcPos = (x + y * width) * 4;
  75951. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  75952. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  75953. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  75954. if (DDSTools.StoreLODInAlphaChannel) {
  75955. destArray[index + 3] = lod;
  75956. }
  75957. else {
  75958. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  75959. }
  75960. index += 4;
  75961. }
  75962. }
  75963. return destArray;
  75964. };
  75965. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  75966. var byteArray = new Uint8Array(dataLength);
  75967. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75968. var index = 0;
  75969. for (var y = 0; y < height; y++) {
  75970. for (var x = 0; x < width; x++) {
  75971. var srcPos = (x + y * width) * 4;
  75972. byteArray[index] = srcData[srcPos + rOffset];
  75973. byteArray[index + 1] = srcData[srcPos + gOffset];
  75974. byteArray[index + 2] = srcData[srcPos + bOffset];
  75975. byteArray[index + 3] = srcData[srcPos + aOffset];
  75976. index += 4;
  75977. }
  75978. }
  75979. return byteArray;
  75980. };
  75981. DDSTools._ExtractLongWordOrder = function (value) {
  75982. if (value === 0 || value === 255 || value === -16777216) {
  75983. return 0;
  75984. }
  75985. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  75986. };
  75987. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  75988. var byteArray = new Uint8Array(dataLength);
  75989. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75990. var index = 0;
  75991. for (var y = 0; y < height; y++) {
  75992. for (var x = 0; x < width; x++) {
  75993. var srcPos = (x + y * width) * 3;
  75994. byteArray[index] = srcData[srcPos + rOffset];
  75995. byteArray[index + 1] = srcData[srcPos + gOffset];
  75996. byteArray[index + 2] = srcData[srcPos + bOffset];
  75997. index += 3;
  75998. }
  75999. }
  76000. return byteArray;
  76001. };
  76002. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  76003. var byteArray = new Uint8Array(dataLength);
  76004. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76005. var index = 0;
  76006. for (var y = 0; y < height; y++) {
  76007. for (var x = 0; x < width; x++) {
  76008. var srcPos = (x + y * width);
  76009. byteArray[index] = srcData[srcPos];
  76010. index++;
  76011. }
  76012. }
  76013. return byteArray;
  76014. };
  76015. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  76016. if (lodIndex === void 0) { lodIndex = -1; }
  76017. var ext = engine.getCaps().s3tc;
  76018. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76019. var fourCC, width, height, dataLength = 0, dataOffset;
  76020. var byteArray, mipmapCount, mip;
  76021. var internalFormat = 0;
  76022. var format = 0;
  76023. var blockBytes = 1;
  76024. if (header[off_magic] !== DDS_MAGIC) {
  76025. BABYLON.Tools.Error("Invalid magic number in DDS header");
  76026. return;
  76027. }
  76028. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  76029. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  76030. return;
  76031. }
  76032. if (info.isCompressed && !ext) {
  76033. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  76034. return;
  76035. }
  76036. var bpp = header[off_RGBbpp];
  76037. dataOffset = header[off_size] + 4;
  76038. var computeFormats = false;
  76039. if (info.isFourCC) {
  76040. fourCC = header[off_pfFourCC];
  76041. switch (fourCC) {
  76042. case FOURCC_DXT1:
  76043. blockBytes = 8;
  76044. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  76045. break;
  76046. case FOURCC_DXT3:
  76047. blockBytes = 16;
  76048. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  76049. break;
  76050. case FOURCC_DXT5:
  76051. blockBytes = 16;
  76052. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  76053. break;
  76054. case FOURCC_D3DFMT_R16G16B16A16F:
  76055. computeFormats = true;
  76056. break;
  76057. case FOURCC_D3DFMT_R32G32B32A32F:
  76058. computeFormats = true;
  76059. break;
  76060. case FOURCC_DX10:
  76061. // There is an additionnal header so dataOffset need to be changed
  76062. dataOffset += 5 * 4; // 5 uints
  76063. var supported = false;
  76064. switch (info.dxgiFormat) {
  76065. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76066. computeFormats = true;
  76067. supported = true;
  76068. break;
  76069. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76070. info.isRGB = true;
  76071. info.isFourCC = false;
  76072. bpp = 32;
  76073. supported = true;
  76074. break;
  76075. }
  76076. if (supported) {
  76077. break;
  76078. }
  76079. default:
  76080. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76081. return;
  76082. }
  76083. }
  76084. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76085. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76086. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76087. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76088. if (computeFormats) {
  76089. format = engine._getWebGLTextureType(info.textureType);
  76090. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76091. }
  76092. mipmapCount = 1;
  76093. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76094. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76095. }
  76096. for (var face = 0; face < faces; face++) {
  76097. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76098. width = header[off_width];
  76099. height = header[off_height];
  76100. for (mip = 0; mip < mipmapCount; ++mip) {
  76101. if (lodIndex === -1 || lodIndex === mip) {
  76102. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76103. var i = (lodIndex === -1) ? mip : 0;
  76104. if (!info.isCompressed && info.isFourCC) {
  76105. dataLength = width * height * 4;
  76106. var floatArray = null;
  76107. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76108. if (bpp === 128) {
  76109. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76110. }
  76111. else if (bpp === 64) {
  76112. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76113. }
  76114. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76115. format = engine._getWebGLTextureType(info.textureType);
  76116. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76117. }
  76118. else {
  76119. if (bpp === 128) {
  76120. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76121. }
  76122. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76123. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76124. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76125. format = engine._getWebGLTextureType(info.textureType);
  76126. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76127. }
  76128. else {
  76129. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76130. }
  76131. }
  76132. if (floatArray) {
  76133. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76134. }
  76135. }
  76136. else if (info.isRGB) {
  76137. if (bpp === 24) {
  76138. dataLength = width * height * 3;
  76139. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76140. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76141. }
  76142. else {
  76143. dataLength = width * height * 4;
  76144. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76145. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76146. }
  76147. }
  76148. else if (info.isLuminance) {
  76149. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76150. var unpaddedRowSize = width;
  76151. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76152. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76153. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76154. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76155. }
  76156. else {
  76157. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76158. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76159. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76160. }
  76161. }
  76162. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76163. width *= 0.5;
  76164. height *= 0.5;
  76165. width = Math.max(1.0, width);
  76166. height = Math.max(1.0, height);
  76167. }
  76168. if (currentFace !== undefined) {
  76169. // Loading a single face
  76170. break;
  76171. }
  76172. }
  76173. };
  76174. DDSTools.StoreLODInAlphaChannel = false;
  76175. return DDSTools;
  76176. }());
  76177. BABYLON.DDSTools = DDSTools;
  76178. })(BABYLON || (BABYLON = {}));
  76179. //# sourceMappingURL=babylon.dds.js.map
  76180. var BABYLON;
  76181. (function (BABYLON) {
  76182. /**
  76183. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76184. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76185. */
  76186. var KhronosTextureContainer = /** @class */ (function () {
  76187. /**
  76188. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76189. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76190. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76191. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76192. */
  76193. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76194. this.arrayBuffer = arrayBuffer;
  76195. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76196. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76197. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76198. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76199. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76200. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76201. BABYLON.Tools.Error("texture missing KTX identifier");
  76202. return;
  76203. }
  76204. // load the reset of the header in native 32 bit int
  76205. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76206. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76207. var oppositeEndianess = header[0] === 0x01020304;
  76208. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76209. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76210. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76211. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76212. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76213. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76214. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76215. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76216. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76217. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76218. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76219. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76220. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76221. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76222. if (this.glType !== 0) {
  76223. BABYLON.Tools.Error("only compressed formats currently supported");
  76224. return;
  76225. }
  76226. else {
  76227. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76228. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76229. }
  76230. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76231. BABYLON.Tools.Error("only 2D textures currently supported");
  76232. return;
  76233. }
  76234. if (this.numberOfArrayElements !== 0) {
  76235. BABYLON.Tools.Error("texture arrays not currently supported");
  76236. return;
  76237. }
  76238. if (this.numberOfFaces !== facesExpected) {
  76239. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76240. return;
  76241. }
  76242. // we now have a completely validated file, so could use existence of loadType as success
  76243. // would need to make this more elaborate & adjust checks above to support more than one load type
  76244. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76245. }
  76246. // not as fast hardware based, but will probably never need to use
  76247. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76248. return ((val & 0xFF) << 24)
  76249. | ((val & 0xFF00) << 8)
  76250. | ((val >> 8) & 0xFF00)
  76251. | ((val >> 24) & 0xFF);
  76252. };
  76253. /**
  76254. * It is assumed that the texture has already been created & is currently bound
  76255. */
  76256. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76257. switch (this.loadType) {
  76258. case KhronosTextureContainer.COMPRESSED_2D:
  76259. this._upload2DCompressedLevels(gl, loadMipmaps);
  76260. break;
  76261. case KhronosTextureContainer.TEX_2D:
  76262. case KhronosTextureContainer.COMPRESSED_3D:
  76263. case KhronosTextureContainer.TEX_3D:
  76264. }
  76265. };
  76266. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76267. // initialize width & height for level 1
  76268. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76269. var width = this.pixelWidth;
  76270. var height = this.pixelHeight;
  76271. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76272. for (var level = 0; level < mipmapCount; level++) {
  76273. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76274. for (var face = 0; face < this.numberOfFaces; face++) {
  76275. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76276. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76277. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76278. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76279. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76280. }
  76281. width = Math.max(1.0, width * 0.5);
  76282. height = Math.max(1.0, height * 0.5);
  76283. }
  76284. };
  76285. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76286. // load types
  76287. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76288. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76289. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76290. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76291. return KhronosTextureContainer;
  76292. }());
  76293. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76294. })(BABYLON || (BABYLON = {}));
  76295. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76296. var BABYLON;
  76297. (function (BABYLON) {
  76298. var Debug = /** @class */ (function () {
  76299. function Debug() {
  76300. }
  76301. Debug.AxesViewer = /** @class */ (function () {
  76302. function AxesViewer(scene, scaleLines) {
  76303. if (scaleLines === void 0) { scaleLines = 1; }
  76304. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76305. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76306. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76307. this.scaleLines = 1;
  76308. this.scaleLines = scaleLines;
  76309. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76310. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76311. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76312. this._xmesh.renderingGroupId = 2;
  76313. this._ymesh.renderingGroupId = 2;
  76314. this._zmesh.renderingGroupId = 2;
  76315. this._xmesh.material.checkReadyOnlyOnce = true;
  76316. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76317. this._ymesh.material.checkReadyOnlyOnce = true;
  76318. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76319. this._zmesh.material.checkReadyOnlyOnce = true;
  76320. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76321. this.scene = scene;
  76322. }
  76323. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76324. var scaleLines = this.scaleLines;
  76325. if (this._xmesh) {
  76326. this._xmesh.position.copyFrom(position);
  76327. }
  76328. if (this._ymesh) {
  76329. this._ymesh.position.copyFrom(position);
  76330. }
  76331. if (this._zmesh) {
  76332. this._zmesh.position.copyFrom(position);
  76333. }
  76334. var point2 = this._xline[1];
  76335. point2.x = xaxis.x * scaleLines;
  76336. point2.y = xaxis.y * scaleLines;
  76337. point2.z = xaxis.z * scaleLines;
  76338. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76339. point2 = this._yline[1];
  76340. point2.x = yaxis.x * scaleLines;
  76341. point2.y = yaxis.y * scaleLines;
  76342. point2.z = yaxis.z * scaleLines;
  76343. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76344. point2 = this._zline[1];
  76345. point2.x = zaxis.x * scaleLines;
  76346. point2.y = zaxis.y * scaleLines;
  76347. point2.z = zaxis.z * scaleLines;
  76348. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76349. };
  76350. AxesViewer.prototype.dispose = function () {
  76351. if (this._xmesh) {
  76352. this._xmesh.dispose();
  76353. }
  76354. if (this._ymesh) {
  76355. this._ymesh.dispose();
  76356. }
  76357. if (this._zmesh) {
  76358. this._zmesh.dispose();
  76359. }
  76360. this._xmesh = null;
  76361. this._ymesh = null;
  76362. this._zmesh = null;
  76363. this.scene = null;
  76364. };
  76365. return AxesViewer;
  76366. }());
  76367. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76368. __extends(BoneAxesViewer, _super);
  76369. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76370. if (scaleLines === void 0) { scaleLines = 1; }
  76371. var _this = _super.call(this, scene, scaleLines) || this;
  76372. _this.pos = BABYLON.Vector3.Zero();
  76373. _this.xaxis = BABYLON.Vector3.Zero();
  76374. _this.yaxis = BABYLON.Vector3.Zero();
  76375. _this.zaxis = BABYLON.Vector3.Zero();
  76376. _this.mesh = mesh;
  76377. _this.bone = bone;
  76378. return _this;
  76379. }
  76380. BoneAxesViewer.prototype.update = function () {
  76381. if (!this.mesh || !this.bone) {
  76382. return;
  76383. }
  76384. var bone = this.bone;
  76385. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76386. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76387. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76388. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76389. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76390. };
  76391. BoneAxesViewer.prototype.dispose = function () {
  76392. if (this.mesh) {
  76393. this.mesh = null;
  76394. this.bone = null;
  76395. _super.prototype.dispose.call(this);
  76396. }
  76397. };
  76398. return BoneAxesViewer;
  76399. }(Debug.AxesViewer));
  76400. Debug.PhysicsViewer = /** @class */ (function () {
  76401. function PhysicsViewer(scene) {
  76402. this._impostors = [];
  76403. this._meshes = [];
  76404. this._numMeshes = 0;
  76405. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76406. var physicEngine = this._scene.getPhysicsEngine();
  76407. if (physicEngine) {
  76408. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76409. }
  76410. }
  76411. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76412. var plugin = this._physicsEnginePlugin;
  76413. for (var i = 0; i < this._numMeshes; i++) {
  76414. var impostor = this._impostors[i];
  76415. if (!impostor) {
  76416. continue;
  76417. }
  76418. if (impostor.isDisposed) {
  76419. this.hideImpostor(this._impostors[i--]);
  76420. }
  76421. else {
  76422. var mesh = this._meshes[i];
  76423. if (mesh && plugin) {
  76424. plugin.syncMeshWithImpostor(mesh, impostor);
  76425. }
  76426. }
  76427. }
  76428. };
  76429. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76430. if (!this._scene) {
  76431. return;
  76432. }
  76433. for (var i = 0; i < this._numMeshes; i++) {
  76434. if (this._impostors[i] == impostor) {
  76435. return;
  76436. }
  76437. }
  76438. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76439. if (debugMesh) {
  76440. this._impostors[this._numMeshes] = impostor;
  76441. this._meshes[this._numMeshes] = debugMesh;
  76442. if (this._numMeshes === 0) {
  76443. this._renderFunction = this._updateDebugMeshes.bind(this);
  76444. this._scene.registerBeforeRender(this._renderFunction);
  76445. }
  76446. this._numMeshes++;
  76447. }
  76448. };
  76449. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76450. if (!impostor || !this._scene) {
  76451. return;
  76452. }
  76453. var removed = false;
  76454. for (var i = 0; i < this._numMeshes; i++) {
  76455. if (this._impostors[i] == impostor) {
  76456. var mesh = this._meshes[i];
  76457. if (!mesh) {
  76458. continue;
  76459. }
  76460. this._scene.removeMesh(mesh);
  76461. mesh.dispose();
  76462. this._numMeshes--;
  76463. if (this._numMeshes > 0) {
  76464. this._meshes[i] = this._meshes[this._numMeshes];
  76465. this._impostors[i] = this._impostors[this._numMeshes];
  76466. this._meshes[this._numMeshes] = null;
  76467. this._impostors[this._numMeshes] = null;
  76468. }
  76469. else {
  76470. this._meshes[0] = null;
  76471. this._impostors[0] = null;
  76472. }
  76473. removed = true;
  76474. break;
  76475. }
  76476. }
  76477. if (removed && this._numMeshes === 0) {
  76478. this._scene.unregisterBeforeRender(this._renderFunction);
  76479. }
  76480. };
  76481. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76482. if (!this._debugMaterial) {
  76483. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76484. this._debugMaterial.wireframe = true;
  76485. }
  76486. return this._debugMaterial;
  76487. };
  76488. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76489. if (!this._debugBoxMesh) {
  76490. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76491. this._debugBoxMesh.renderingGroupId = 1;
  76492. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76493. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76494. scene.removeMesh(this._debugBoxMesh);
  76495. }
  76496. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76497. };
  76498. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76499. if (!this._debugSphereMesh) {
  76500. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76501. this._debugSphereMesh.renderingGroupId = 1;
  76502. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76503. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76504. scene.removeMesh(this._debugSphereMesh);
  76505. }
  76506. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76507. };
  76508. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76509. var mesh = null;
  76510. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76511. mesh = this._getDebugBoxMesh(scene);
  76512. impostor.getBoxSizeToRef(mesh.scaling);
  76513. }
  76514. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76515. mesh = this._getDebugSphereMesh(scene);
  76516. var radius = impostor.getRadius();
  76517. mesh.scaling.x = radius * 2;
  76518. mesh.scaling.y = radius * 2;
  76519. mesh.scaling.z = radius * 2;
  76520. }
  76521. return mesh;
  76522. };
  76523. PhysicsViewer.prototype.dispose = function () {
  76524. for (var i = 0; i < this._numMeshes; i++) {
  76525. this.hideImpostor(this._impostors[i]);
  76526. }
  76527. if (this._debugBoxMesh) {
  76528. this._debugBoxMesh.dispose();
  76529. }
  76530. if (this._debugSphereMesh) {
  76531. this._debugSphereMesh.dispose();
  76532. }
  76533. if (this._debugMaterial) {
  76534. this._debugMaterial.dispose();
  76535. }
  76536. this._impostors.length = 0;
  76537. this._scene = null;
  76538. this._physicsEnginePlugin = null;
  76539. };
  76540. return PhysicsViewer;
  76541. }());
  76542. Debug.SkeletonViewer = /** @class */ (function () {
  76543. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76544. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76545. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76546. this.skeleton = skeleton;
  76547. this.mesh = mesh;
  76548. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76549. this.renderingGroupId = renderingGroupId;
  76550. this.color = BABYLON.Color3.White();
  76551. this._debugLines = new Array();
  76552. this._isEnabled = false;
  76553. this._scene = scene;
  76554. this.update();
  76555. this._renderFunction = this.update.bind(this);
  76556. }
  76557. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76558. get: function () {
  76559. return this._isEnabled;
  76560. },
  76561. set: function (value) {
  76562. if (this._isEnabled === value) {
  76563. return;
  76564. }
  76565. this._isEnabled = value;
  76566. if (value) {
  76567. this._scene.registerBeforeRender(this._renderFunction);
  76568. }
  76569. else {
  76570. this._scene.unregisterBeforeRender(this._renderFunction);
  76571. }
  76572. },
  76573. enumerable: true,
  76574. configurable: true
  76575. });
  76576. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76577. if (x === void 0) { x = 0; }
  76578. if (y === void 0) { y = 0; }
  76579. if (z === void 0) { z = 0; }
  76580. var tmat = BABYLON.Tmp.Matrix[0];
  76581. var parentBone = bone.getParent();
  76582. tmat.copyFrom(bone.getLocalMatrix());
  76583. if (x !== 0 || y !== 0 || z !== 0) {
  76584. var tmat2 = BABYLON.Tmp.Matrix[1];
  76585. BABYLON.Matrix.IdentityToRef(tmat2);
  76586. tmat2.m[12] = x;
  76587. tmat2.m[13] = y;
  76588. tmat2.m[14] = z;
  76589. tmat2.multiplyToRef(tmat, tmat);
  76590. }
  76591. if (parentBone) {
  76592. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76593. }
  76594. tmat.multiplyToRef(meshMat, tmat);
  76595. position.x = tmat.m[12];
  76596. position.y = tmat.m[13];
  76597. position.z = tmat.m[14];
  76598. };
  76599. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76600. var len = bones.length;
  76601. var meshPos = this.mesh.position;
  76602. for (var i = 0; i < len; i++) {
  76603. var bone = bones[i];
  76604. var points = this._debugLines[i];
  76605. if (!points) {
  76606. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76607. this._debugLines[i] = points;
  76608. }
  76609. this._getBonePosition(points[0], bone, meshMat);
  76610. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76611. points[0].subtractInPlace(meshPos);
  76612. points[1].subtractInPlace(meshPos);
  76613. }
  76614. };
  76615. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76616. var len = bones.length;
  76617. var boneNum = 0;
  76618. var meshPos = this.mesh.position;
  76619. for (var i = len - 1; i >= 0; i--) {
  76620. var childBone = bones[i];
  76621. var parentBone = childBone.getParent();
  76622. if (!parentBone) {
  76623. continue;
  76624. }
  76625. var points = this._debugLines[boneNum];
  76626. if (!points) {
  76627. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76628. this._debugLines[boneNum] = points;
  76629. }
  76630. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76631. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76632. points[0].subtractInPlace(meshPos);
  76633. points[1].subtractInPlace(meshPos);
  76634. boneNum++;
  76635. }
  76636. };
  76637. SkeletonViewer.prototype.update = function () {
  76638. if (this.autoUpdateBonesMatrices) {
  76639. this.skeleton.computeAbsoluteTransforms();
  76640. }
  76641. if (this.skeleton.bones[0].length === undefined) {
  76642. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76643. }
  76644. else {
  76645. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76646. }
  76647. if (!this._debugMesh) {
  76648. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76649. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76650. }
  76651. else {
  76652. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76653. }
  76654. this._debugMesh.position.copyFrom(this.mesh.position);
  76655. this._debugMesh.color = this.color;
  76656. };
  76657. SkeletonViewer.prototype.dispose = function () {
  76658. if (this._debugMesh) {
  76659. this.isEnabled = false;
  76660. this._debugMesh.dispose();
  76661. this._debugMesh = null;
  76662. }
  76663. };
  76664. return SkeletonViewer;
  76665. }());
  76666. return Debug;
  76667. }());
  76668. BABYLON.Debug = Debug;
  76669. })(BABYLON || (BABYLON = {}));
  76670. //# sourceMappingURL=babylon.debugModules.js.map
  76671. var BABYLON;
  76672. (function (BABYLON) {
  76673. var RayHelper = /** @class */ (function () {
  76674. function RayHelper(ray) {
  76675. this.ray = ray;
  76676. }
  76677. RayHelper.CreateAndShow = function (ray, scene, color) {
  76678. var helper = new RayHelper(ray);
  76679. helper.show(scene, color);
  76680. return helper;
  76681. };
  76682. RayHelper.prototype.show = function (scene, color) {
  76683. if (!this._renderFunction && this.ray) {
  76684. var ray = this.ray;
  76685. this._renderFunction = this._render.bind(this);
  76686. this._scene = scene;
  76687. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76688. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76689. if (this._renderFunction) {
  76690. this._scene.registerBeforeRender(this._renderFunction);
  76691. }
  76692. }
  76693. if (color && this._renderLine) {
  76694. this._renderLine.color.copyFrom(color);
  76695. }
  76696. };
  76697. RayHelper.prototype.hide = function () {
  76698. if (this._renderFunction && this._scene) {
  76699. this._scene.unregisterBeforeRender(this._renderFunction);
  76700. this._scene = null;
  76701. this._renderFunction = null;
  76702. if (this._renderLine) {
  76703. this._renderLine.dispose();
  76704. this._renderLine = null;
  76705. }
  76706. this._renderPoints = [];
  76707. }
  76708. };
  76709. RayHelper.prototype._render = function () {
  76710. var ray = this.ray;
  76711. if (!ray) {
  76712. return;
  76713. }
  76714. var point = this._renderPoints[1];
  76715. var len = Math.min(ray.length, 1000000);
  76716. point.copyFrom(ray.direction);
  76717. point.scaleInPlace(len);
  76718. point.addInPlace(ray.origin);
  76719. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76720. };
  76721. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76722. this._attachedToMesh = mesh;
  76723. var ray = this.ray;
  76724. if (!ray) {
  76725. return;
  76726. }
  76727. if (!ray.direction) {
  76728. ray.direction = BABYLON.Vector3.Zero();
  76729. }
  76730. if (!ray.origin) {
  76731. ray.origin = BABYLON.Vector3.Zero();
  76732. }
  76733. if (length) {
  76734. ray.length = length;
  76735. }
  76736. if (!meshSpaceOrigin) {
  76737. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76738. }
  76739. if (!meshSpaceDirection) {
  76740. // -1 so that this will work with Mesh.lookAt
  76741. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76742. }
  76743. if (!this._meshSpaceDirection) {
  76744. this._meshSpaceDirection = meshSpaceDirection.clone();
  76745. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76746. }
  76747. else {
  76748. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76749. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76750. }
  76751. if (!this._updateToMeshFunction) {
  76752. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76753. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76754. }
  76755. this._updateToMesh();
  76756. };
  76757. RayHelper.prototype.detachFromMesh = function () {
  76758. if (this._attachedToMesh) {
  76759. if (this._updateToMeshFunction) {
  76760. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76761. }
  76762. this._attachedToMesh = null;
  76763. this._updateToMeshFunction = null;
  76764. }
  76765. };
  76766. RayHelper.prototype._updateToMesh = function () {
  76767. var ray = this.ray;
  76768. if (!this._attachedToMesh || !ray) {
  76769. return;
  76770. }
  76771. if (this._attachedToMesh._isDisposed) {
  76772. this.detachFromMesh();
  76773. return;
  76774. }
  76775. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76776. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76777. };
  76778. RayHelper.prototype.dispose = function () {
  76779. this.hide();
  76780. this.detachFromMesh();
  76781. this.ray = null;
  76782. };
  76783. return RayHelper;
  76784. }());
  76785. BABYLON.RayHelper = RayHelper;
  76786. })(BABYLON || (BABYLON = {}));
  76787. //# sourceMappingURL=babylon.rayHelper.js.map
  76788. var BABYLON;
  76789. (function (BABYLON) {
  76790. // load the inspector using require, if not present in the global namespace.
  76791. var DebugLayer = /** @class */ (function () {
  76792. function DebugLayer(scene) {
  76793. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76794. this._scene = scene;
  76795. // load inspector using require, if it doesn't exist on the global namespace.
  76796. }
  76797. /** Creates the inspector window. */
  76798. DebugLayer.prototype._createInspector = function (config) {
  76799. if (config === void 0) { config = {}; }
  76800. var popup = config.popup || false;
  76801. var initialTab = config.initialTab || 0;
  76802. var parentElement = config.parentElement || null;
  76803. if (!this._inspector) {
  76804. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76805. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76806. } // else nothing to do,; instance is already existing
  76807. };
  76808. DebugLayer.prototype.isVisible = function () {
  76809. if (!this._inspector) {
  76810. return false;
  76811. }
  76812. return true;
  76813. };
  76814. DebugLayer.prototype.hide = function () {
  76815. if (this._inspector) {
  76816. try {
  76817. this._inspector.dispose();
  76818. }
  76819. catch (e) {
  76820. // If the inspector has been removed directly from the inspector tool
  76821. }
  76822. this._inspector = null;
  76823. }
  76824. };
  76825. DebugLayer.prototype.show = function (config) {
  76826. if (config === void 0) { config = {}; }
  76827. if (typeof this.BJSINSPECTOR == 'undefined') {
  76828. // Load inspector and add it to the DOM
  76829. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76830. }
  76831. else {
  76832. // Otherwise creates the inspector
  76833. this._createInspector(config);
  76834. }
  76835. };
  76836. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76837. return DebugLayer;
  76838. }());
  76839. BABYLON.DebugLayer = DebugLayer;
  76840. })(BABYLON || (BABYLON = {}));
  76841. //# sourceMappingURL=babylon.debugLayer.js.map
  76842. var BABYLON;
  76843. (function (BABYLON) {
  76844. var BoundingBoxRenderer = /** @class */ (function () {
  76845. function BoundingBoxRenderer(scene) {
  76846. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76847. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76848. this.showBackLines = true;
  76849. this.renderList = new BABYLON.SmartArray(32);
  76850. this._vertexBuffers = {};
  76851. this._scene = scene;
  76852. }
  76853. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76854. if (this._colorShader) {
  76855. return;
  76856. }
  76857. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76858. attributes: [BABYLON.VertexBuffer.PositionKind],
  76859. uniforms: ["world", "viewProjection", "color"]
  76860. });
  76861. var engine = this._scene.getEngine();
  76862. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76863. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76864. this._createIndexBuffer();
  76865. };
  76866. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76867. var engine = this._scene.getEngine();
  76868. 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]);
  76869. };
  76870. BoundingBoxRenderer.prototype._rebuild = function () {
  76871. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76872. if (vb) {
  76873. vb._rebuild();
  76874. }
  76875. this._createIndexBuffer();
  76876. };
  76877. BoundingBoxRenderer.prototype.reset = function () {
  76878. this.renderList.reset();
  76879. };
  76880. BoundingBoxRenderer.prototype.render = function () {
  76881. if (this.renderList.length === 0) {
  76882. return;
  76883. }
  76884. this._prepareRessources();
  76885. if (!this._colorShader.isReady()) {
  76886. return;
  76887. }
  76888. var engine = this._scene.getEngine();
  76889. engine.setDepthWrite(false);
  76890. this._colorShader._preBind();
  76891. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76892. var boundingBox = this.renderList.data[boundingBoxIndex];
  76893. var min = boundingBox.minimum;
  76894. var max = boundingBox.maximum;
  76895. var diff = max.subtract(min);
  76896. var median = min.add(diff.scale(0.5));
  76897. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76898. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76899. .multiply(boundingBox.getWorldMatrix());
  76900. // VBOs
  76901. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76902. if (this.showBackLines) {
  76903. // Back
  76904. engine.setDepthFunctionToGreaterOrEqual();
  76905. this._scene.resetCachedMaterial();
  76906. this._colorShader.setColor4("color", this.backColor.toColor4());
  76907. this._colorShader.bind(worldMatrix);
  76908. // Draw order
  76909. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76910. }
  76911. // Front
  76912. engine.setDepthFunctionToLess();
  76913. this._scene.resetCachedMaterial();
  76914. this._colorShader.setColor4("color", this.frontColor.toColor4());
  76915. this._colorShader.bind(worldMatrix);
  76916. // Draw order
  76917. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76918. }
  76919. this._colorShader.unbind();
  76920. engine.setDepthFunctionToLessOrEqual();
  76921. engine.setDepthWrite(true);
  76922. };
  76923. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  76924. this._prepareRessources();
  76925. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  76926. return;
  76927. }
  76928. var engine = this._scene.getEngine();
  76929. engine.setDepthWrite(false);
  76930. engine.setColorWrite(false);
  76931. this._colorShader._preBind();
  76932. var boundingBox = mesh._boundingInfo.boundingBox;
  76933. var min = boundingBox.minimum;
  76934. var max = boundingBox.maximum;
  76935. var diff = max.subtract(min);
  76936. var median = min.add(diff.scale(0.5));
  76937. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76938. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76939. .multiply(boundingBox.getWorldMatrix());
  76940. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76941. engine.setDepthFunctionToLess();
  76942. this._scene.resetCachedMaterial();
  76943. this._colorShader.bind(worldMatrix);
  76944. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76945. this._colorShader.unbind();
  76946. engine.setDepthFunctionToLessOrEqual();
  76947. engine.setDepthWrite(true);
  76948. engine.setColorWrite(true);
  76949. };
  76950. BoundingBoxRenderer.prototype.dispose = function () {
  76951. if (!this._colorShader) {
  76952. return;
  76953. }
  76954. this.renderList.dispose();
  76955. this._colorShader.dispose();
  76956. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76957. if (buffer) {
  76958. buffer.dispose();
  76959. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76960. }
  76961. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76962. };
  76963. return BoundingBoxRenderer;
  76964. }());
  76965. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  76966. })(BABYLON || (BABYLON = {}));
  76967. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  76968. var BABYLON;
  76969. (function (BABYLON) {
  76970. var MorphTarget = /** @class */ (function () {
  76971. function MorphTarget(name, influence) {
  76972. if (influence === void 0) { influence = 0; }
  76973. this.name = name;
  76974. this.animations = new Array();
  76975. this._positions = null;
  76976. this._normals = null;
  76977. this._tangents = null;
  76978. this.onInfluenceChanged = new BABYLON.Observable();
  76979. this.influence = influence;
  76980. }
  76981. Object.defineProperty(MorphTarget.prototype, "influence", {
  76982. get: function () {
  76983. return this._influence;
  76984. },
  76985. set: function (influence) {
  76986. if (this._influence === influence) {
  76987. return;
  76988. }
  76989. var previous = this._influence;
  76990. this._influence = influence;
  76991. if (this.onInfluenceChanged.hasObservers) {
  76992. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  76993. }
  76994. },
  76995. enumerable: true,
  76996. configurable: true
  76997. });
  76998. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  76999. get: function () {
  77000. return !!this._positions;
  77001. },
  77002. enumerable: true,
  77003. configurable: true
  77004. });
  77005. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  77006. get: function () {
  77007. return !!this._normals;
  77008. },
  77009. enumerable: true,
  77010. configurable: true
  77011. });
  77012. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  77013. get: function () {
  77014. return !!this._tangents;
  77015. },
  77016. enumerable: true,
  77017. configurable: true
  77018. });
  77019. MorphTarget.prototype.setPositions = function (data) {
  77020. this._positions = data;
  77021. };
  77022. MorphTarget.prototype.getPositions = function () {
  77023. return this._positions;
  77024. };
  77025. MorphTarget.prototype.setNormals = function (data) {
  77026. this._normals = data;
  77027. };
  77028. MorphTarget.prototype.getNormals = function () {
  77029. return this._normals;
  77030. };
  77031. MorphTarget.prototype.setTangents = function (data) {
  77032. this._tangents = data;
  77033. };
  77034. MorphTarget.prototype.getTangents = function () {
  77035. return this._tangents;
  77036. };
  77037. /**
  77038. * Serializes the current target into a Serialization object.
  77039. * Returns the serialized object.
  77040. */
  77041. MorphTarget.prototype.serialize = function () {
  77042. var serializationObject = {};
  77043. serializationObject.name = this.name;
  77044. serializationObject.influence = this.influence;
  77045. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  77046. if (this.hasNormals) {
  77047. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  77048. }
  77049. if (this.hasTangents) {
  77050. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  77051. }
  77052. // Animations
  77053. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  77054. return serializationObject;
  77055. };
  77056. // Statics
  77057. MorphTarget.Parse = function (serializationObject) {
  77058. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  77059. result.setPositions(serializationObject.positions);
  77060. if (serializationObject.normals) {
  77061. result.setNormals(serializationObject.normals);
  77062. }
  77063. if (serializationObject.tangents) {
  77064. result.setTangents(serializationObject.tangents);
  77065. }
  77066. // Animations
  77067. if (serializationObject.animations) {
  77068. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77069. var parsedAnimation = serializationObject.animations[animationIndex];
  77070. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77071. }
  77072. }
  77073. return result;
  77074. };
  77075. MorphTarget.FromMesh = function (mesh, name, influence) {
  77076. if (!name) {
  77077. name = mesh.name;
  77078. }
  77079. var result = new MorphTarget(name, influence);
  77080. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77081. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77082. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77083. }
  77084. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77085. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77086. }
  77087. return result;
  77088. };
  77089. return MorphTarget;
  77090. }());
  77091. BABYLON.MorphTarget = MorphTarget;
  77092. })(BABYLON || (BABYLON = {}));
  77093. //# sourceMappingURL=babylon.morphTarget.js.map
  77094. var BABYLON;
  77095. (function (BABYLON) {
  77096. var MorphTargetManager = /** @class */ (function () {
  77097. function MorphTargetManager(scene) {
  77098. if (scene === void 0) { scene = null; }
  77099. this._targets = new Array();
  77100. this._targetObservable = new Array();
  77101. this._activeTargets = new BABYLON.SmartArray(16);
  77102. this._supportsNormals = false;
  77103. this._supportsTangents = false;
  77104. this._vertexCount = 0;
  77105. this._uniqueId = 0;
  77106. this._tempInfluences = new Array();
  77107. if (!scene) {
  77108. scene = BABYLON.Engine.LastCreatedScene;
  77109. }
  77110. this._scene = scene;
  77111. if (this._scene) {
  77112. this._scene.morphTargetManagers.push(this);
  77113. this._uniqueId = this._scene.getUniqueId();
  77114. }
  77115. }
  77116. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77117. get: function () {
  77118. return this._uniqueId;
  77119. },
  77120. enumerable: true,
  77121. configurable: true
  77122. });
  77123. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77124. get: function () {
  77125. return this._vertexCount;
  77126. },
  77127. enumerable: true,
  77128. configurable: true
  77129. });
  77130. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77131. get: function () {
  77132. return this._supportsNormals;
  77133. },
  77134. enumerable: true,
  77135. configurable: true
  77136. });
  77137. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77138. get: function () {
  77139. return this._supportsTangents;
  77140. },
  77141. enumerable: true,
  77142. configurable: true
  77143. });
  77144. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77145. get: function () {
  77146. return this._targets.length;
  77147. },
  77148. enumerable: true,
  77149. configurable: true
  77150. });
  77151. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77152. get: function () {
  77153. return this._activeTargets.length;
  77154. },
  77155. enumerable: true,
  77156. configurable: true
  77157. });
  77158. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77159. get: function () {
  77160. return this._influences;
  77161. },
  77162. enumerable: true,
  77163. configurable: true
  77164. });
  77165. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77166. return this._activeTargets.data[index];
  77167. };
  77168. MorphTargetManager.prototype.getTarget = function (index) {
  77169. return this._targets[index];
  77170. };
  77171. MorphTargetManager.prototype.addTarget = function (target) {
  77172. var _this = this;
  77173. this._targets.push(target);
  77174. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77175. _this._syncActiveTargets(needUpdate);
  77176. }));
  77177. this._syncActiveTargets(true);
  77178. };
  77179. MorphTargetManager.prototype.removeTarget = function (target) {
  77180. var index = this._targets.indexOf(target);
  77181. if (index >= 0) {
  77182. this._targets.splice(index, 1);
  77183. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77184. this._syncActiveTargets(true);
  77185. }
  77186. };
  77187. /**
  77188. * Serializes the current manager into a Serialization object.
  77189. * Returns the serialized object.
  77190. */
  77191. MorphTargetManager.prototype.serialize = function () {
  77192. var serializationObject = {};
  77193. serializationObject.id = this.uniqueId;
  77194. serializationObject.targets = [];
  77195. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77196. var target = _a[_i];
  77197. serializationObject.targets.push(target.serialize());
  77198. }
  77199. return serializationObject;
  77200. };
  77201. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77202. var influenceCount = 0;
  77203. this._activeTargets.reset();
  77204. this._supportsNormals = true;
  77205. this._supportsTangents = true;
  77206. this._vertexCount = 0;
  77207. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77208. var target = _a[_i];
  77209. this._activeTargets.push(target);
  77210. this._tempInfluences[influenceCount++] = target.influence;
  77211. var positions = target.getPositions();
  77212. if (positions) {
  77213. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77214. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77215. var vertexCount = positions.length / 3;
  77216. if (this._vertexCount === 0) {
  77217. this._vertexCount = vertexCount;
  77218. }
  77219. else if (this._vertexCount !== vertexCount) {
  77220. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77221. return;
  77222. }
  77223. }
  77224. }
  77225. if (!this._influences || this._influences.length !== influenceCount) {
  77226. this._influences = new Float32Array(influenceCount);
  77227. }
  77228. for (var index = 0; index < influenceCount; index++) {
  77229. this._influences[index] = this._tempInfluences[index];
  77230. }
  77231. if (needUpdate && this._scene) {
  77232. // Flag meshes as dirty to resync with the active targets
  77233. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77234. var mesh = _c[_b];
  77235. if (mesh.morphTargetManager === this) {
  77236. mesh._syncGeometryWithMorphTargetManager();
  77237. }
  77238. }
  77239. }
  77240. };
  77241. // Statics
  77242. MorphTargetManager.Parse = function (serializationObject, scene) {
  77243. var result = new MorphTargetManager(scene);
  77244. result._uniqueId = serializationObject.id;
  77245. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77246. var targetData = _a[_i];
  77247. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77248. }
  77249. return result;
  77250. };
  77251. return MorphTargetManager;
  77252. }());
  77253. BABYLON.MorphTargetManager = MorphTargetManager;
  77254. })(BABYLON || (BABYLON = {}));
  77255. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77256. var BABYLON;
  77257. (function (BABYLON) {
  77258. var Octree = /** @class */ (function () {
  77259. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77260. if (maxDepth === void 0) { maxDepth = 2; }
  77261. this.maxDepth = maxDepth;
  77262. this.dynamicContent = new Array();
  77263. this._maxBlockCapacity = maxBlockCapacity || 64;
  77264. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77265. this._creationFunc = creationFunc;
  77266. }
  77267. // Methods
  77268. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77269. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77270. };
  77271. Octree.prototype.addMesh = function (entry) {
  77272. for (var index = 0; index < this.blocks.length; index++) {
  77273. var block = this.blocks[index];
  77274. block.addEntry(entry);
  77275. }
  77276. };
  77277. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77278. this._selectionContent.reset();
  77279. for (var index = 0; index < this.blocks.length; index++) {
  77280. var block = this.blocks[index];
  77281. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77282. }
  77283. if (allowDuplicate) {
  77284. this._selectionContent.concat(this.dynamicContent);
  77285. }
  77286. else {
  77287. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77288. }
  77289. return this._selectionContent;
  77290. };
  77291. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77292. this._selectionContent.reset();
  77293. for (var index = 0; index < this.blocks.length; index++) {
  77294. var block = this.blocks[index];
  77295. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77296. }
  77297. if (allowDuplicate) {
  77298. this._selectionContent.concat(this.dynamicContent);
  77299. }
  77300. else {
  77301. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77302. }
  77303. return this._selectionContent;
  77304. };
  77305. Octree.prototype.intersectsRay = function (ray) {
  77306. this._selectionContent.reset();
  77307. for (var index = 0; index < this.blocks.length; index++) {
  77308. var block = this.blocks[index];
  77309. block.intersectsRay(ray, this._selectionContent);
  77310. }
  77311. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77312. return this._selectionContent;
  77313. };
  77314. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77315. target.blocks = new Array();
  77316. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77317. // Segmenting space
  77318. for (var x = 0; x < 2; x++) {
  77319. for (var y = 0; y < 2; y++) {
  77320. for (var z = 0; z < 2; z++) {
  77321. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77322. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77323. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77324. block.addEntries(entries);
  77325. target.blocks.push(block);
  77326. }
  77327. }
  77328. }
  77329. };
  77330. Octree.CreationFuncForMeshes = function (entry, block) {
  77331. var boundingInfo = entry.getBoundingInfo();
  77332. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77333. block.entries.push(entry);
  77334. }
  77335. };
  77336. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77337. var boundingInfo = entry.getBoundingInfo();
  77338. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77339. block.entries.push(entry);
  77340. }
  77341. };
  77342. return Octree;
  77343. }());
  77344. BABYLON.Octree = Octree;
  77345. })(BABYLON || (BABYLON = {}));
  77346. //# sourceMappingURL=babylon.octree.js.map
  77347. var BABYLON;
  77348. (function (BABYLON) {
  77349. var OctreeBlock = /** @class */ (function () {
  77350. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77351. this.entries = new Array();
  77352. this._boundingVectors = new Array();
  77353. this._capacity = capacity;
  77354. this._depth = depth;
  77355. this._maxDepth = maxDepth;
  77356. this._creationFunc = creationFunc;
  77357. this._minPoint = minPoint;
  77358. this._maxPoint = maxPoint;
  77359. this._boundingVectors.push(minPoint.clone());
  77360. this._boundingVectors.push(maxPoint.clone());
  77361. this._boundingVectors.push(minPoint.clone());
  77362. this._boundingVectors[2].x = maxPoint.x;
  77363. this._boundingVectors.push(minPoint.clone());
  77364. this._boundingVectors[3].y = maxPoint.y;
  77365. this._boundingVectors.push(minPoint.clone());
  77366. this._boundingVectors[4].z = maxPoint.z;
  77367. this._boundingVectors.push(maxPoint.clone());
  77368. this._boundingVectors[5].z = minPoint.z;
  77369. this._boundingVectors.push(maxPoint.clone());
  77370. this._boundingVectors[6].x = minPoint.x;
  77371. this._boundingVectors.push(maxPoint.clone());
  77372. this._boundingVectors[7].y = minPoint.y;
  77373. }
  77374. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77375. // Property
  77376. get: function () {
  77377. return this._capacity;
  77378. },
  77379. enumerable: true,
  77380. configurable: true
  77381. });
  77382. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77383. get: function () {
  77384. return this._minPoint;
  77385. },
  77386. enumerable: true,
  77387. configurable: true
  77388. });
  77389. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77390. get: function () {
  77391. return this._maxPoint;
  77392. },
  77393. enumerable: true,
  77394. configurable: true
  77395. });
  77396. // Methods
  77397. OctreeBlock.prototype.addEntry = function (entry) {
  77398. if (this.blocks) {
  77399. for (var index = 0; index < this.blocks.length; index++) {
  77400. var block = this.blocks[index];
  77401. block.addEntry(entry);
  77402. }
  77403. return;
  77404. }
  77405. this._creationFunc(entry, this);
  77406. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77407. this.createInnerBlocks();
  77408. }
  77409. };
  77410. OctreeBlock.prototype.addEntries = function (entries) {
  77411. for (var index = 0; index < entries.length; index++) {
  77412. var mesh = entries[index];
  77413. this.addEntry(mesh);
  77414. }
  77415. };
  77416. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77417. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77418. if (this.blocks) {
  77419. for (var index = 0; index < this.blocks.length; index++) {
  77420. var block = this.blocks[index];
  77421. block.select(frustumPlanes, selection, allowDuplicate);
  77422. }
  77423. return;
  77424. }
  77425. if (allowDuplicate) {
  77426. selection.concat(this.entries);
  77427. }
  77428. else {
  77429. selection.concatWithNoDuplicate(this.entries);
  77430. }
  77431. }
  77432. };
  77433. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77434. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77435. if (this.blocks) {
  77436. for (var index = 0; index < this.blocks.length; index++) {
  77437. var block = this.blocks[index];
  77438. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77439. }
  77440. return;
  77441. }
  77442. if (allowDuplicate) {
  77443. selection.concat(this.entries);
  77444. }
  77445. else {
  77446. selection.concatWithNoDuplicate(this.entries);
  77447. }
  77448. }
  77449. };
  77450. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77451. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77452. if (this.blocks) {
  77453. for (var index = 0; index < this.blocks.length; index++) {
  77454. var block = this.blocks[index];
  77455. block.intersectsRay(ray, selection);
  77456. }
  77457. return;
  77458. }
  77459. selection.concatWithNoDuplicate(this.entries);
  77460. }
  77461. };
  77462. OctreeBlock.prototype.createInnerBlocks = function () {
  77463. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77464. };
  77465. return OctreeBlock;
  77466. }());
  77467. BABYLON.OctreeBlock = OctreeBlock;
  77468. })(BABYLON || (BABYLON = {}));
  77469. //# sourceMappingURL=babylon.octreeBlock.js.map
  77470. var BABYLON;
  77471. (function (BABYLON) {
  77472. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77473. __extends(VRDistortionCorrectionPostProcess, _super);
  77474. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77475. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77476. 'LensCenter',
  77477. 'Scale',
  77478. 'ScaleIn',
  77479. 'HmdWarpParam'
  77480. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77481. _this._isRightEye = isRightEye;
  77482. _this._distortionFactors = vrMetrics.distortionK;
  77483. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77484. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77485. _this.adaptScaleToCurrentViewport = true;
  77486. _this.onSizeChangedObservable.add(function () {
  77487. _this.aspectRatio = _this.width * .5 / _this.height;
  77488. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77489. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77490. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77491. });
  77492. _this.onApplyObservable.add(function (effect) {
  77493. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77494. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77495. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77496. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77497. });
  77498. return _this;
  77499. }
  77500. return VRDistortionCorrectionPostProcess;
  77501. }(BABYLON.PostProcess));
  77502. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77503. })(BABYLON || (BABYLON = {}));
  77504. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77505. var BABYLON;
  77506. (function (BABYLON) {
  77507. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77508. __extends(AnaglyphPostProcess, _super);
  77509. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77510. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77511. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77512. _this.onApplyObservable.add(function (effect) {
  77513. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77514. });
  77515. return _this;
  77516. }
  77517. return AnaglyphPostProcess;
  77518. }(BABYLON.PostProcess));
  77519. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77520. })(BABYLON || (BABYLON = {}));
  77521. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77522. var BABYLON;
  77523. (function (BABYLON) {
  77524. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77525. __extends(StereoscopicInterlacePostProcess, _super);
  77526. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77527. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77528. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77529. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77530. _this.onSizeChangedObservable.add(function () {
  77531. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77532. });
  77533. _this.onApplyObservable.add(function (effect) {
  77534. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77535. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77536. });
  77537. return _this;
  77538. }
  77539. return StereoscopicInterlacePostProcess;
  77540. }(BABYLON.PostProcess));
  77541. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77542. })(BABYLON || (BABYLON = {}));
  77543. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77544. var BABYLON;
  77545. (function (BABYLON) {
  77546. /**
  77547. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77548. * Screen rotation is taken into account.
  77549. */
  77550. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77551. function FreeCameraDeviceOrientationInput() {
  77552. var _this = this;
  77553. this._screenOrientationAngle = 0;
  77554. this._screenQuaternion = new BABYLON.Quaternion();
  77555. this._alpha = 0;
  77556. this._beta = 0;
  77557. this._gamma = 0;
  77558. this._orientationChanged = function () {
  77559. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77560. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77561. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77562. };
  77563. this._deviceOrientation = function (evt) {
  77564. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77565. _this._beta = evt.beta !== null ? evt.beta : 0;
  77566. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77567. };
  77568. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77569. this._orientationChanged();
  77570. }
  77571. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77572. get: function () {
  77573. return this._camera;
  77574. },
  77575. set: function (camera) {
  77576. this._camera = camera;
  77577. if (this._camera != null && !this._camera.rotationQuaternion) {
  77578. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77579. }
  77580. },
  77581. enumerable: true,
  77582. configurable: true
  77583. });
  77584. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77585. window.addEventListener("orientationchange", this._orientationChanged);
  77586. window.addEventListener("deviceorientation", this._deviceOrientation);
  77587. //In certain cases, the attach control is called AFTER orientation was changed,
  77588. //So this is needed.
  77589. this._orientationChanged();
  77590. };
  77591. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77592. window.removeEventListener("orientationchange", this._orientationChanged);
  77593. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77594. };
  77595. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77596. //if no device orientation provided, don't update the rotation.
  77597. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77598. if (!this._alpha)
  77599. return;
  77600. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77601. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77602. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77603. //Mirror on XY Plane
  77604. this._camera.rotationQuaternion.z *= -1;
  77605. this._camera.rotationQuaternion.w *= -1;
  77606. };
  77607. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77608. return "FreeCameraDeviceOrientationInput";
  77609. };
  77610. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77611. return "deviceOrientation";
  77612. };
  77613. return FreeCameraDeviceOrientationInput;
  77614. }());
  77615. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77616. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77617. })(BABYLON || (BABYLON = {}));
  77618. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77619. var BABYLON;
  77620. (function (BABYLON) {
  77621. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77622. function ArcRotateCameraVRDeviceOrientationInput() {
  77623. this.alphaCorrection = 1;
  77624. this.betaCorrection = 1;
  77625. this.gammaCorrection = 1;
  77626. this._alpha = 0;
  77627. this._gamma = 0;
  77628. this._dirty = false;
  77629. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77630. }
  77631. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77632. this.camera.attachControl(element, noPreventDefault);
  77633. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77634. };
  77635. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77636. if (evt.alpha !== null) {
  77637. this._alpha = +evt.alpha | 0;
  77638. }
  77639. if (evt.gamma !== null) {
  77640. this._gamma = +evt.gamma | 0;
  77641. }
  77642. this._dirty = true;
  77643. };
  77644. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77645. if (this._dirty) {
  77646. this._dirty = false;
  77647. if (this._gamma < 0) {
  77648. this._gamma = 180 + this._gamma;
  77649. }
  77650. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77651. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77652. }
  77653. };
  77654. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77655. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77656. };
  77657. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77658. return "ArcRotateCameraVRDeviceOrientationInput";
  77659. };
  77660. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77661. return "VRDeviceOrientation";
  77662. };
  77663. return ArcRotateCameraVRDeviceOrientationInput;
  77664. }());
  77665. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77666. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77667. })(BABYLON || (BABYLON = {}));
  77668. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77669. var BABYLON;
  77670. (function (BABYLON) {
  77671. var VRCameraMetrics = /** @class */ (function () {
  77672. function VRCameraMetrics() {
  77673. this.compensateDistortion = true;
  77674. }
  77675. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77676. get: function () {
  77677. return this.hResolution / (2 * this.vResolution);
  77678. },
  77679. enumerable: true,
  77680. configurable: true
  77681. });
  77682. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77683. get: function () {
  77684. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77685. },
  77686. enumerable: true,
  77687. configurable: true
  77688. });
  77689. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77690. get: function () {
  77691. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77692. var h = (4 * meters) / this.hScreenSize;
  77693. return BABYLON.Matrix.Translation(h, 0, 0);
  77694. },
  77695. enumerable: true,
  77696. configurable: true
  77697. });
  77698. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77699. get: function () {
  77700. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77701. var h = (4 * meters) / this.hScreenSize;
  77702. return BABYLON.Matrix.Translation(-h, 0, 0);
  77703. },
  77704. enumerable: true,
  77705. configurable: true
  77706. });
  77707. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77708. get: function () {
  77709. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77710. },
  77711. enumerable: true,
  77712. configurable: true
  77713. });
  77714. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77715. get: function () {
  77716. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77717. },
  77718. enumerable: true,
  77719. configurable: true
  77720. });
  77721. VRCameraMetrics.GetDefault = function () {
  77722. var result = new VRCameraMetrics();
  77723. result.hResolution = 1280;
  77724. result.vResolution = 800;
  77725. result.hScreenSize = 0.149759993;
  77726. result.vScreenSize = 0.0935999975;
  77727. result.vScreenCenter = 0.0467999987;
  77728. result.eyeToScreenDistance = 0.0410000011;
  77729. result.lensSeparationDistance = 0.0635000020;
  77730. result.interpupillaryDistance = 0.0640000030;
  77731. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77732. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77733. result.postProcessScaleFactor = 1.714605507808412;
  77734. result.lensCenterOffset = 0.151976421;
  77735. return result;
  77736. };
  77737. return VRCameraMetrics;
  77738. }());
  77739. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77740. })(BABYLON || (BABYLON = {}));
  77741. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77742. var BABYLON;
  77743. (function (BABYLON) {
  77744. /**
  77745. * This represents a WebVR camera.
  77746. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77747. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77748. */
  77749. var WebVRFreeCamera = /** @class */ (function (_super) {
  77750. __extends(WebVRFreeCamera, _super);
  77751. /**
  77752. * Instantiates a WebVRFreeCamera.
  77753. * @param name The name of the WebVRFreeCamera
  77754. * @param position The starting anchor position for the camera
  77755. * @param scene The scene the camera belongs to
  77756. * @param webVROptions a set of customizable options for the webVRCamera
  77757. */
  77758. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77759. if (webVROptions === void 0) { webVROptions = {}; }
  77760. var _this = _super.call(this, name, position, scene) || this;
  77761. _this.webVROptions = webVROptions;
  77762. /**
  77763. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77764. */
  77765. _this._vrDevice = null;
  77766. /**
  77767. * The rawPose of the vrDevice.
  77768. */
  77769. _this.rawPose = null;
  77770. _this._specsVersion = "1.1";
  77771. _this._attached = false;
  77772. _this._descendants = [];
  77773. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77774. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77775. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77776. _this._standingMatrix = null;
  77777. /**
  77778. * Represents device position in babylon space.
  77779. */
  77780. _this.devicePosition = BABYLON.Vector3.Zero();
  77781. /**
  77782. * Represents device rotation in babylon space.
  77783. */
  77784. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77785. /**
  77786. * The scale of the device to be used when translating from device space to babylon space.
  77787. */
  77788. _this.deviceScaleFactor = 1;
  77789. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77790. _this._worldToDevice = BABYLON.Matrix.Identity();
  77791. /**
  77792. * References to the webVR controllers for the vrDevice.
  77793. */
  77794. _this.controllers = [];
  77795. /**
  77796. * Emits an event when a controller is attached.
  77797. */
  77798. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77799. /**
  77800. * Emits an event when a controller's mesh has been loaded;
  77801. */
  77802. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77803. /**
  77804. * If the rig cameras be used as parent instead of this camera.
  77805. */
  77806. _this.rigParenting = true;
  77807. _this._defaultHeight = undefined;
  77808. _this._workingVector = BABYLON.Vector3.Zero();
  77809. _this._oneVector = BABYLON.Vector3.One();
  77810. _this._workingMatrix = BABYLON.Matrix.Identity();
  77811. _this._cache.position = BABYLON.Vector3.Zero();
  77812. if (webVROptions.defaultHeight) {
  77813. _this._defaultHeight = webVROptions.defaultHeight;
  77814. _this.position.y = _this._defaultHeight;
  77815. }
  77816. _this.minZ = 0.1;
  77817. //legacy support - the compensation boolean was removed.
  77818. if (arguments.length === 5) {
  77819. _this.webVROptions = arguments[4];
  77820. }
  77821. // default webVR options
  77822. if (_this.webVROptions.trackPosition == undefined) {
  77823. _this.webVROptions.trackPosition = true;
  77824. }
  77825. if (_this.webVROptions.controllerMeshes == undefined) {
  77826. _this.webVROptions.controllerMeshes = true;
  77827. }
  77828. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77829. _this.webVROptions.defaultLightingOnControllers = true;
  77830. }
  77831. _this.rotationQuaternion = new BABYLON.Quaternion();
  77832. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77833. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77834. }
  77835. //enable VR
  77836. var engine = _this.getEngine();
  77837. _this._onVREnabled = function (success) { if (success) {
  77838. _this.initControllers();
  77839. } };
  77840. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77841. engine.initWebVR().add(function (event) {
  77842. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77843. return;
  77844. }
  77845. _this._vrDevice = event.vrDisplay;
  77846. //reset the rig parameters.
  77847. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77848. if (_this._attached) {
  77849. _this.getEngine().enableVR();
  77850. }
  77851. });
  77852. if (typeof (VRFrameData) !== "undefined")
  77853. _this._frameData = new VRFrameData();
  77854. /**
  77855. * The idea behind the following lines:
  77856. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77857. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77858. * the second will not show it correctly.
  77859. *
  77860. * To solve this - each object that has the camera as parent will be added to a protected array.
  77861. * When the rig camera renders, it will take this array and set all of those to be its children.
  77862. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77863. * Amazing!
  77864. */
  77865. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77866. if (camera.parent === _this && _this.rigParenting) {
  77867. _this._descendants = _this.getDescendants(true, function (n) {
  77868. // don't take the cameras or the controllers!
  77869. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77870. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77871. return !isController && !isRigCamera;
  77872. });
  77873. _this._descendants.forEach(function (node) {
  77874. node.parent = camera;
  77875. });
  77876. }
  77877. });
  77878. scene.onAfterCameraRenderObservable.add(function (camera) {
  77879. if (camera.parent === _this && _this.rigParenting) {
  77880. _this._descendants.forEach(function (node) {
  77881. node.parent = _this;
  77882. });
  77883. }
  77884. });
  77885. return _this;
  77886. }
  77887. /**
  77888. * Gets the device distance from the ground.
  77889. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77890. */
  77891. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77892. if (this._standingMatrix && this._defaultHeight === undefined) {
  77893. // Add standing matrix offset to get real offset from ground in room
  77894. this._standingMatrix.getTranslationToRef(this._workingVector);
  77895. return this._deviceRoomPosition.y + this._workingVector.y;
  77896. }
  77897. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77898. return this._defaultHeight || 0;
  77899. };
  77900. /**
  77901. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77902. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77903. */
  77904. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77905. var _this = this;
  77906. if (callback === void 0) { callback = function (bool) { }; }
  77907. // Use standing matrix if available
  77908. if (!navigator || !navigator.getVRDisplays) {
  77909. callback(false);
  77910. }
  77911. else {
  77912. navigator.getVRDisplays().then(function (displays) {
  77913. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  77914. callback(false);
  77915. }
  77916. else {
  77917. _this._standingMatrix = new BABYLON.Matrix();
  77918. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  77919. if (!_this.getScene().useRightHandedSystem) {
  77920. [2, 6, 8, 9, 14].forEach(function (num) {
  77921. if (_this._standingMatrix) {
  77922. _this._standingMatrix.m[num] *= -1;
  77923. }
  77924. });
  77925. }
  77926. callback(true);
  77927. }
  77928. });
  77929. }
  77930. };
  77931. /**
  77932. * Disposes the camera
  77933. */
  77934. WebVRFreeCamera.prototype.dispose = function () {
  77935. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  77936. _super.prototype.dispose.call(this);
  77937. };
  77938. /**
  77939. * Gets a vrController by name.
  77940. * @param name The name of the controller to retreive
  77941. * @returns the controller matching the name specified or null if not found
  77942. */
  77943. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  77944. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  77945. var gp = _a[_i];
  77946. if (gp.hand === name) {
  77947. return gp;
  77948. }
  77949. }
  77950. return null;
  77951. };
  77952. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  77953. /**
  77954. * The controller corrisponding to the users left hand.
  77955. */
  77956. get: function () {
  77957. if (!this._leftController) {
  77958. this._leftController = this.getControllerByName("left");
  77959. }
  77960. return this._leftController;
  77961. },
  77962. enumerable: true,
  77963. configurable: true
  77964. });
  77965. ;
  77966. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  77967. /**
  77968. * The controller corrisponding to the users right hand.
  77969. */
  77970. get: function () {
  77971. if (!this._rightController) {
  77972. this._rightController = this.getControllerByName("right");
  77973. }
  77974. return this._rightController;
  77975. },
  77976. enumerable: true,
  77977. configurable: true
  77978. });
  77979. ;
  77980. /**
  77981. * Casts a ray forward from the vrCamera's gaze.
  77982. * @param length Length of the ray (default: 100)
  77983. * @returns the ray corrisponding to the gaze
  77984. */
  77985. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  77986. if (length === void 0) { length = 100; }
  77987. if (this.leftCamera) {
  77988. // Use left eye to avoid computation to compute center on every call
  77989. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  77990. }
  77991. else {
  77992. return _super.prototype.getForwardRay.call(this, length);
  77993. }
  77994. };
  77995. /**
  77996. * Updates the camera based on device's frame data
  77997. */
  77998. WebVRFreeCamera.prototype._checkInputs = function () {
  77999. if (this._vrDevice && this._vrDevice.isPresenting) {
  78000. this._vrDevice.getFrameData(this._frameData);
  78001. this.updateFromDevice(this._frameData.pose);
  78002. }
  78003. _super.prototype._checkInputs.call(this);
  78004. };
  78005. /**
  78006. * Updates the poseControlled values based on the input device pose.
  78007. * @param poseData Pose coming from the device
  78008. */
  78009. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  78010. if (poseData && poseData.orientation) {
  78011. this.rawPose = poseData;
  78012. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  78013. if (this.getScene().useRightHandedSystem) {
  78014. this._deviceRoomRotationQuaternion.z *= -1;
  78015. this._deviceRoomRotationQuaternion.w *= -1;
  78016. }
  78017. if (this.webVROptions.trackPosition && this.rawPose.position) {
  78018. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  78019. if (this.getScene().useRightHandedSystem) {
  78020. this._deviceRoomPosition.z *= -1;
  78021. }
  78022. }
  78023. }
  78024. };
  78025. /**
  78026. * WebVR's attach control will start broadcasting frames to the device.
  78027. * Note that in certain browsers (chrome for example) this function must be called
  78028. * within a user-interaction callback. Example:
  78029. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  78030. *
  78031. * @param element html element to attach the vrDevice to
  78032. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  78033. */
  78034. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  78035. _super.prototype.attachControl.call(this, element, noPreventDefault);
  78036. this._attached = true;
  78037. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  78038. if (this._vrDevice) {
  78039. this.getEngine().enableVR();
  78040. }
  78041. };
  78042. /**
  78043. * Detaches the camera from the html element and disables VR
  78044. *
  78045. * @param element html element to detach from
  78046. */
  78047. WebVRFreeCamera.prototype.detachControl = function (element) {
  78048. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78049. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78050. _super.prototype.detachControl.call(this, element);
  78051. this._attached = false;
  78052. this.getEngine().disableVR();
  78053. };
  78054. /**
  78055. * @returns the name of this class
  78056. */
  78057. WebVRFreeCamera.prototype.getClassName = function () {
  78058. return "WebVRFreeCamera";
  78059. };
  78060. /**
  78061. * Calls resetPose on the vrDisplay
  78062. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  78063. */
  78064. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  78065. //uses the vrDisplay's "resetPose()".
  78066. //pitch and roll won't be affected.
  78067. this._vrDevice.resetPose();
  78068. };
  78069. /**
  78070. * Updates the rig cameras (left and right eye)
  78071. */
  78072. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78073. var camLeft = this._rigCameras[0];
  78074. var camRight = this._rigCameras[1];
  78075. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78076. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78077. camLeft.position.copyFrom(this._deviceRoomPosition);
  78078. camRight.position.copyFrom(this._deviceRoomPosition);
  78079. };
  78080. /**
  78081. * Updates the cached values of the camera
  78082. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78083. */
  78084. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78085. var _this = this;
  78086. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78087. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78088. if (!this.updateCacheCalled) {
  78089. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78090. this.updateCacheCalled = true;
  78091. this.update();
  78092. }
  78093. // Set working vector to the device position in room space rotated by the new rotation
  78094. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78095. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78096. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78097. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78098. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78099. // Add translation from anchor position
  78100. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78101. this._workingVector.addInPlace(this.position);
  78102. this._workingVector.subtractInPlace(this._cache.position);
  78103. this._deviceToWorld.setTranslation(this._workingVector);
  78104. // Set an inverted matrix to be used when updating the camera
  78105. this._deviceToWorld.invertToRef(this._worldToDevice);
  78106. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78107. this.controllers.forEach(function (controller) {
  78108. controller._deviceToWorld = _this._deviceToWorld;
  78109. controller.update();
  78110. });
  78111. }
  78112. if (!ignoreParentClass) {
  78113. _super.prototype._updateCache.call(this);
  78114. }
  78115. this.updateCacheCalled = false;
  78116. };
  78117. /**
  78118. * Updates the current device position and rotation in the babylon world
  78119. */
  78120. WebVRFreeCamera.prototype.update = function () {
  78121. // Get current device position in babylon world
  78122. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78123. // Get current device rotation in babylon world
  78124. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78125. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78126. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78127. _super.prototype.update.call(this);
  78128. };
  78129. /**
  78130. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78131. * @returns an identity matrix
  78132. */
  78133. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78134. return BABYLON.Matrix.Identity();
  78135. };
  78136. /**
  78137. * This function is called by the two RIG cameras.
  78138. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78139. */
  78140. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78141. var _this = this;
  78142. //WebVR 1.1
  78143. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78144. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78145. if (!this.getScene().useRightHandedSystem) {
  78146. [2, 6, 8, 9, 14].forEach(function (num) {
  78147. _this._webvrViewMatrix.m[num] *= -1;
  78148. });
  78149. }
  78150. // update the camera rotation matrix
  78151. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78152. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78153. // Computing target and final matrix
  78154. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78155. var parentCamera = this._cameraRigParams["parentCamera"];
  78156. // should the view matrix be updated with scale and position offset?
  78157. if (parentCamera.deviceScaleFactor !== 1) {
  78158. this._webvrViewMatrix.invert();
  78159. // scale the position, if set
  78160. if (parentCamera.deviceScaleFactor) {
  78161. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78162. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78163. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78164. }
  78165. this._webvrViewMatrix.invert();
  78166. }
  78167. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78168. return this._webvrViewMatrix;
  78169. };
  78170. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78171. var _this = this;
  78172. var parentCamera = this.parent;
  78173. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78174. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78175. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78176. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78177. //babylon compatible matrix
  78178. if (!this.getScene().useRightHandedSystem) {
  78179. [8, 9, 10, 11].forEach(function (num) {
  78180. _this._projectionMatrix.m[num] *= -1;
  78181. });
  78182. }
  78183. return this._projectionMatrix;
  78184. };
  78185. /**
  78186. * Initializes the controllers and their meshes
  78187. */
  78188. WebVRFreeCamera.prototype.initControllers = function () {
  78189. var _this = this;
  78190. this.controllers = [];
  78191. var manager = this.getScene().gamepadManager;
  78192. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78193. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78194. var webVrController = gamepad;
  78195. if (webVrController.defaultModel) {
  78196. webVrController.defaultModel.setEnabled(false);
  78197. }
  78198. if (webVrController.hand === "right") {
  78199. _this._rightController = null;
  78200. }
  78201. if (webVrController.hand === "left") {
  78202. _this._rightController = null;
  78203. }
  78204. var controllerIndex = _this.controllers.indexOf(webVrController);
  78205. if (controllerIndex !== -1) {
  78206. _this.controllers.splice(controllerIndex, 1);
  78207. }
  78208. }
  78209. });
  78210. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78211. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78212. var webVrController_1 = gamepad;
  78213. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78214. if (_this.webVROptions.controllerMeshes) {
  78215. if (webVrController_1.defaultModel) {
  78216. webVrController_1.defaultModel.setEnabled(true);
  78217. }
  78218. else {
  78219. // Load the meshes
  78220. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78221. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78222. if (_this.webVROptions.defaultLightingOnControllers) {
  78223. if (!_this._lightOnControllers) {
  78224. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78225. }
  78226. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78227. var children = mesh.getChildren();
  78228. if (children.length !== 0) {
  78229. children.forEach(function (mesh) {
  78230. light.includedOnlyMeshes.push(mesh);
  78231. activateLightOnSubMeshes_1(mesh, light);
  78232. });
  78233. }
  78234. };
  78235. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78236. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78237. }
  78238. });
  78239. }
  78240. }
  78241. webVrController_1.attachToPoseControlledCamera(_this);
  78242. // since this is async - sanity check. Is the controller already stored?
  78243. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78244. //add to the controllers array
  78245. _this.controllers.push(webVrController_1);
  78246. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78247. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78248. // So we're overriding setting left & right manually to be sure
  78249. var firstViveWandDetected = false;
  78250. for (var i = 0; i < _this.controllers.length; i++) {
  78251. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78252. if (!firstViveWandDetected) {
  78253. firstViveWandDetected = true;
  78254. _this.controllers[i].hand = "left";
  78255. }
  78256. else {
  78257. _this.controllers[i].hand = "right";
  78258. }
  78259. }
  78260. }
  78261. //did we find enough controllers? Great! let the developer know.
  78262. if (_this.controllers.length >= 2) {
  78263. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78264. }
  78265. }
  78266. }
  78267. });
  78268. };
  78269. return WebVRFreeCamera;
  78270. }(BABYLON.FreeCamera));
  78271. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78272. })(BABYLON || (BABYLON = {}));
  78273. //# sourceMappingURL=babylon.webVRCamera.js.map
  78274. var BABYLON;
  78275. (function (BABYLON) {
  78276. // We're mainly based on the logic defined into the FreeCamera code
  78277. /**
  78278. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78279. * being tilted forward or back and left or right.
  78280. */
  78281. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78282. __extends(DeviceOrientationCamera, _super);
  78283. /**
  78284. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78285. * @param name The name of the camera
  78286. * @param position The start position camera
  78287. * @param scene The scene the camera belongs to
  78288. */
  78289. function DeviceOrientationCamera(name, position, scene) {
  78290. var _this = _super.call(this, name, position, scene) || this;
  78291. _this._quaternionCache = new BABYLON.Quaternion();
  78292. _this.inputs.addDeviceOrientation();
  78293. return _this;
  78294. }
  78295. /**
  78296. * Gets the current instance class name ("DeviceOrientationCamera").
  78297. * This helps avoiding instanceof at run time.
  78298. * @returns the class name
  78299. */
  78300. DeviceOrientationCamera.prototype.getClassName = function () {
  78301. return "DeviceOrientationCamera";
  78302. };
  78303. /**
  78304. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78305. */
  78306. DeviceOrientationCamera.prototype._checkInputs = function () {
  78307. _super.prototype._checkInputs.call(this);
  78308. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78309. if (this._initialQuaternion) {
  78310. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78311. }
  78312. };
  78313. /**
  78314. * Reset the camera to its default orientation on the specified axis only.
  78315. * @param axis The axis to reset
  78316. */
  78317. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78318. var _this = this;
  78319. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78320. //can only work if this camera has a rotation quaternion already.
  78321. if (!this.rotationQuaternion)
  78322. return;
  78323. if (!this._initialQuaternion) {
  78324. this._initialQuaternion = new BABYLON.Quaternion();
  78325. }
  78326. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78327. ['x', 'y', 'z'].forEach(function (axisName) {
  78328. if (!axis[axisName]) {
  78329. _this._initialQuaternion[axisName] = 0;
  78330. }
  78331. else {
  78332. _this._initialQuaternion[axisName] *= -1;
  78333. }
  78334. });
  78335. this._initialQuaternion.normalize();
  78336. //force rotation update
  78337. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78338. };
  78339. return DeviceOrientationCamera;
  78340. }(BABYLON.FreeCamera));
  78341. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78342. })(BABYLON || (BABYLON = {}));
  78343. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78344. var BABYLON;
  78345. (function (BABYLON) {
  78346. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78347. __extends(VRDeviceOrientationFreeCamera, _super);
  78348. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78349. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78350. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78351. var _this = _super.call(this, name, position, scene) || this;
  78352. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78353. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78354. return _this;
  78355. }
  78356. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78357. return "VRDeviceOrientationFreeCamera";
  78358. };
  78359. return VRDeviceOrientationFreeCamera;
  78360. }(BABYLON.DeviceOrientationCamera));
  78361. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78362. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78363. __extends(VRDeviceOrientationGamepadCamera, _super);
  78364. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78365. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78366. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78367. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78368. _this.inputs.addGamepad();
  78369. return _this;
  78370. }
  78371. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78372. return "VRDeviceOrientationGamepadCamera";
  78373. };
  78374. return VRDeviceOrientationGamepadCamera;
  78375. }(VRDeviceOrientationFreeCamera));
  78376. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78377. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78378. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78379. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78380. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78381. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78382. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78383. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78384. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78385. _this.inputs.addVRDeviceOrientation();
  78386. return _this;
  78387. }
  78388. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78389. return "VRDeviceOrientationArcRotateCamera";
  78390. };
  78391. return VRDeviceOrientationArcRotateCamera;
  78392. }(BABYLON.ArcRotateCamera));
  78393. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78394. })(BABYLON || (BABYLON = {}));
  78395. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78396. var BABYLON;
  78397. (function (BABYLON) {
  78398. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78399. __extends(AnaglyphFreeCamera, _super);
  78400. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78401. var _this = _super.call(this, name, position, scene) || this;
  78402. _this.interaxialDistance = interaxialDistance;
  78403. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78404. return _this;
  78405. }
  78406. AnaglyphFreeCamera.prototype.getClassName = function () {
  78407. return "AnaglyphFreeCamera";
  78408. };
  78409. return AnaglyphFreeCamera;
  78410. }(BABYLON.FreeCamera));
  78411. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78412. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78413. __extends(AnaglyphArcRotateCamera, _super);
  78414. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78415. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78416. _this.interaxialDistance = interaxialDistance;
  78417. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78418. return _this;
  78419. }
  78420. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78421. return "AnaglyphArcRotateCamera";
  78422. };
  78423. return AnaglyphArcRotateCamera;
  78424. }(BABYLON.ArcRotateCamera));
  78425. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78426. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78427. __extends(AnaglyphGamepadCamera, _super);
  78428. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78429. var _this = _super.call(this, name, position, scene) || this;
  78430. _this.interaxialDistance = interaxialDistance;
  78431. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78432. return _this;
  78433. }
  78434. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78435. return "AnaglyphGamepadCamera";
  78436. };
  78437. return AnaglyphGamepadCamera;
  78438. }(BABYLON.GamepadCamera));
  78439. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78440. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78441. __extends(AnaglyphUniversalCamera, _super);
  78442. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78443. var _this = _super.call(this, name, position, scene) || this;
  78444. _this.interaxialDistance = interaxialDistance;
  78445. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78446. return _this;
  78447. }
  78448. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78449. return "AnaglyphUniversalCamera";
  78450. };
  78451. return AnaglyphUniversalCamera;
  78452. }(BABYLON.UniversalCamera));
  78453. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78454. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78455. __extends(StereoscopicFreeCamera, _super);
  78456. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78457. var _this = _super.call(this, name, position, scene) || this;
  78458. _this.interaxialDistance = interaxialDistance;
  78459. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78460. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78461. return _this;
  78462. }
  78463. StereoscopicFreeCamera.prototype.getClassName = function () {
  78464. return "StereoscopicFreeCamera";
  78465. };
  78466. return StereoscopicFreeCamera;
  78467. }(BABYLON.FreeCamera));
  78468. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78469. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78470. __extends(StereoscopicArcRotateCamera, _super);
  78471. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78472. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78473. _this.interaxialDistance = interaxialDistance;
  78474. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78475. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78476. return _this;
  78477. }
  78478. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78479. return "StereoscopicArcRotateCamera";
  78480. };
  78481. return StereoscopicArcRotateCamera;
  78482. }(BABYLON.ArcRotateCamera));
  78483. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78484. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78485. __extends(StereoscopicGamepadCamera, _super);
  78486. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78487. var _this = _super.call(this, name, position, scene) || this;
  78488. _this.interaxialDistance = interaxialDistance;
  78489. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78490. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78491. return _this;
  78492. }
  78493. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78494. return "StereoscopicGamepadCamera";
  78495. };
  78496. return StereoscopicGamepadCamera;
  78497. }(BABYLON.GamepadCamera));
  78498. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78499. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78500. __extends(StereoscopicUniversalCamera, _super);
  78501. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78502. var _this = _super.call(this, name, position, scene) || this;
  78503. _this.interaxialDistance = interaxialDistance;
  78504. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78505. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78506. return _this;
  78507. }
  78508. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78509. return "StereoscopicUniversalCamera";
  78510. };
  78511. return StereoscopicUniversalCamera;
  78512. }(BABYLON.UniversalCamera));
  78513. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78514. })(BABYLON || (BABYLON = {}));
  78515. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78516. var BABYLON;
  78517. (function (BABYLON) {
  78518. /**
  78519. * Helps to quickly add VR support to an existing scene.
  78520. * See http://doc.babylonjs.com/how_to/webvr_helper
  78521. */
  78522. var VRExperienceHelper = /** @class */ (function () {
  78523. /**
  78524. * Instantiates a VRExperienceHelper.
  78525. * Helps to quickly add VR support to an existing scene.
  78526. * @param scene The scene the VRExperienceHelper belongs to.
  78527. * @param webVROptions Options to modify the vr experience helper's behavior.
  78528. */
  78529. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78530. if (webVROptions === void 0) { webVROptions = {}; }
  78531. var _this = this;
  78532. this.webVROptions = webVROptions;
  78533. // Can the system support WebVR, even if a headset isn't plugged in?
  78534. this._webVRsupported = false;
  78535. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78536. this._webVRready = false;
  78537. // Are we waiting for the requestPresent callback to complete?
  78538. this._webVRrequesting = false;
  78539. // Are we presenting to the headset right now?
  78540. this._webVRpresenting = false;
  78541. // Are we presenting in the fullscreen fallback?
  78542. this._fullscreenVRpresenting = false;
  78543. /**
  78544. * Observable raised when entering VR.
  78545. */
  78546. this.onEnteringVRObservable = new BABYLON.Observable();
  78547. /**
  78548. * Observable raised when exiting VR.
  78549. */
  78550. this.onExitingVRObservable = new BABYLON.Observable();
  78551. /**
  78552. * Observable raised when controller mesh is loaded.
  78553. */
  78554. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78555. this._useCustomVRButton = false;
  78556. this._teleportationRequested = false;
  78557. this._teleportationEnabledOnLeftController = false;
  78558. this._teleportationEnabledOnRightController = false;
  78559. this._interactionsEnabledOnLeftController = false;
  78560. this._interactionsEnabledOnRightController = false;
  78561. this._leftControllerReady = false;
  78562. this._rightControllerReady = false;
  78563. this._floorMeshesCollection = [];
  78564. this._teleportationAllowed = false;
  78565. this._rotationAllowed = true;
  78566. this._teleportationRequestInitiated = false;
  78567. this._teleportationBackRequestInitiated = false;
  78568. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78569. this._rotationRightAsked = false;
  78570. this._rotationLeftAsked = false;
  78571. this._isDefaultTeleportationTarget = true;
  78572. this._teleportationFillColor = "#444444";
  78573. this._teleportationBorderColor = "#FFFFFF";
  78574. this._rotationAngle = 0;
  78575. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78576. this._padSensibilityUp = 0.65;
  78577. this._padSensibilityDown = 0.35;
  78578. /**
  78579. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78580. */
  78581. this.onNewMeshSelected = new BABYLON.Observable();
  78582. /**
  78583. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78584. */
  78585. this.onNewMeshPicked = new BABYLON.Observable();
  78586. /**
  78587. * Observable raised before camera teleportation
  78588. */
  78589. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78590. /**
  78591. * Observable raised after camera teleportation
  78592. */
  78593. this.onAfterCameraTeleport = new BABYLON.Observable();
  78594. /**
  78595. * Observable raised when current selected mesh gets unselected
  78596. */
  78597. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78598. /**
  78599. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78600. */
  78601. this.teleportationEnabled = true;
  78602. this._pointerDownOnMeshAsked = false;
  78603. this._isActionableMesh = false;
  78604. this._teleportationInitialized = false;
  78605. this._interactionsEnabled = false;
  78606. this._interactionsRequested = false;
  78607. this._displayGaze = true;
  78608. this._displayLaserPointer = true;
  78609. this._dpadPressed = true;
  78610. this._onResize = function () {
  78611. _this.moveButtonToBottomRight();
  78612. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78613. _this.exitVR();
  78614. }
  78615. };
  78616. this._onFullscreenChange = function () {
  78617. if (document.fullscreen !== undefined) {
  78618. _this._fullscreenVRpresenting = document.fullscreen;
  78619. }
  78620. else if (document.mozFullScreen !== undefined) {
  78621. _this._fullscreenVRpresenting = document.mozFullScreen;
  78622. }
  78623. else if (document.webkitIsFullScreen !== undefined) {
  78624. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78625. }
  78626. else if (document.msIsFullScreen !== undefined) {
  78627. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78628. }
  78629. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78630. _this.exitVR();
  78631. if (!_this._useCustomVRButton) {
  78632. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78633. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78634. }
  78635. }
  78636. };
  78637. this.beforeRender = function () {
  78638. _this._castRayAndSelectObject();
  78639. };
  78640. this._onNewGamepadConnected = function (gamepad) {
  78641. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78642. if (gamepad.leftStick) {
  78643. gamepad.onleftstickchanged(function (stickValues) {
  78644. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78645. // Listening to classic/xbox gamepad only if no VR controller is active
  78646. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78647. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78648. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78649. _this._checkTeleportWithRay(stickValues);
  78650. _this._checkTeleportBackwards(stickValues);
  78651. }
  78652. }
  78653. });
  78654. }
  78655. if (gamepad.rightStick) {
  78656. gamepad.onrightstickchanged(function (stickValues) {
  78657. if (_this._teleportationInitialized) {
  78658. _this._checkRotate(stickValues);
  78659. }
  78660. });
  78661. }
  78662. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78663. gamepad.onbuttondown(function (buttonPressed) {
  78664. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78665. _this._selectionPointerDown();
  78666. }
  78667. });
  78668. gamepad.onbuttonup(function (buttonPressed) {
  78669. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78670. _this._selectionPointerUp();
  78671. }
  78672. });
  78673. }
  78674. }
  78675. else {
  78676. var webVRController = gamepad;
  78677. _this._tryEnableInteractionOnController(webVRController);
  78678. }
  78679. };
  78680. // 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
  78681. this._tryEnableInteractionOnController = function (webVRController) {
  78682. if (webVRController.hand === "left") {
  78683. _this._leftControllerReady = true;
  78684. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78685. _this._enableInteractionOnController(webVRController);
  78686. }
  78687. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78688. _this._enableTeleportationOnController(webVRController);
  78689. }
  78690. }
  78691. if (webVRController.hand === "right") {
  78692. _this._rightControllerReady = true;
  78693. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78694. _this._enableInteractionOnController(webVRController);
  78695. }
  78696. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78697. _this._enableTeleportationOnController(webVRController);
  78698. }
  78699. }
  78700. };
  78701. this._onNewGamepadDisconnected = function (gamepad) {
  78702. if (gamepad instanceof BABYLON.WebVRController) {
  78703. if (gamepad.hand === "left") {
  78704. _this._interactionsEnabledOnLeftController = false;
  78705. _this._teleportationEnabledOnLeftController = false;
  78706. _this._leftControllerReady = false;
  78707. if (_this._leftLaserPointer) {
  78708. _this._leftLaserPointer.dispose();
  78709. }
  78710. }
  78711. if (gamepad.hand === "right") {
  78712. _this._interactionsEnabledOnRightController = false;
  78713. _this._teleportationEnabledOnRightController = false;
  78714. _this._rightControllerReady = false;
  78715. if (_this._rightLaserPointer) {
  78716. _this._rightLaserPointer.dispose();
  78717. }
  78718. }
  78719. }
  78720. };
  78721. this._workingVector = BABYLON.Vector3.Zero();
  78722. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78723. this._workingMatrix = BABYLON.Matrix.Identity();
  78724. this._scene = scene;
  78725. this._canvas = scene.getEngine().getRenderingCanvas();
  78726. // Parse options
  78727. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78728. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78729. }
  78730. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78731. webVROptions.createDeviceOrientationCamera = true;
  78732. }
  78733. if (webVROptions.defaultHeight === undefined) {
  78734. webVROptions.defaultHeight = 1.7;
  78735. }
  78736. if (webVROptions.useCustomVRButton) {
  78737. this._useCustomVRButton = true;
  78738. if (webVROptions.customVRButton) {
  78739. this._btnVR = webVROptions.customVRButton;
  78740. }
  78741. }
  78742. if (webVROptions.rayLength) {
  78743. this._rayLength = webVROptions.rayLength;
  78744. }
  78745. this._defaultHeight = webVROptions.defaultHeight;
  78746. // Set position
  78747. if (this._scene.activeCamera) {
  78748. this._position = this._scene.activeCamera.position.clone();
  78749. }
  78750. else {
  78751. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78752. }
  78753. // Set non-vr camera
  78754. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78755. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78756. // Copy data from existing camera
  78757. if (this._scene.activeCamera) {
  78758. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78759. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78760. // Set rotation from previous camera
  78761. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78762. var targetCamera = this._scene.activeCamera;
  78763. if (targetCamera.rotationQuaternion) {
  78764. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78765. }
  78766. else {
  78767. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78768. }
  78769. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78770. }
  78771. }
  78772. this._scene.activeCamera = this._deviceOrientationCamera;
  78773. if (this._canvas) {
  78774. this._scene.activeCamera.attachControl(this._canvas);
  78775. }
  78776. }
  78777. else {
  78778. this._existingCamera = this._scene.activeCamera;
  78779. }
  78780. // Create VR cameras
  78781. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78782. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78783. }
  78784. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78785. this._webVRCamera.useStandingMatrix();
  78786. // Create default button
  78787. if (!this._useCustomVRButton) {
  78788. this._btnVR = document.createElement("BUTTON");
  78789. this._btnVR.className = "babylonVRicon";
  78790. this._btnVR.id = "babylonVRiconbtn";
  78791. this._btnVR.title = "Click to switch to VR";
  78792. 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) }";
  78793. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78794. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78795. // css += ".babylonVRicon.vrdisplaysupported { }";
  78796. // css += ".babylonVRicon.vrdisplayready { }";
  78797. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78798. var style = document.createElement('style');
  78799. style.appendChild(document.createTextNode(css));
  78800. document.getElementsByTagName('head')[0].appendChild(style);
  78801. this.moveButtonToBottomRight();
  78802. }
  78803. // VR button click event
  78804. if (this._btnVR) {
  78805. this._btnVR.addEventListener("click", function () {
  78806. if (!_this.isInVRMode) {
  78807. _this.enterVR();
  78808. }
  78809. else {
  78810. _this.exitVR();
  78811. }
  78812. });
  78813. }
  78814. // Window events
  78815. window.addEventListener("resize", this._onResize);
  78816. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78817. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78818. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78819. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78820. // Display vr button when headset is connected
  78821. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78822. this.displayVRButton();
  78823. }
  78824. else {
  78825. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78826. if (e.vrDisplay) {
  78827. _this.displayVRButton();
  78828. }
  78829. });
  78830. }
  78831. // Exiting VR mode using 'ESC' key on desktop
  78832. this._onKeyDown = function (event) {
  78833. if (event.keyCode === 27 && _this.isInVRMode) {
  78834. _this.exitVR();
  78835. }
  78836. };
  78837. document.addEventListener("keydown", this._onKeyDown);
  78838. // Exiting VR mode double tapping the touch screen
  78839. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78840. if (_this.isInVRMode) {
  78841. _this.exitVR();
  78842. if (_this._fullscreenVRpresenting) {
  78843. _this._scene.getEngine().switchFullscreen(true);
  78844. }
  78845. }
  78846. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78847. // Listen for WebVR display changes
  78848. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78849. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78850. this._onVRRequestPresentStart = function () {
  78851. _this._webVRrequesting = true;
  78852. _this.updateButtonVisibility();
  78853. };
  78854. this._onVRRequestPresentComplete = function (success) {
  78855. _this._webVRrequesting = false;
  78856. _this.updateButtonVisibility();
  78857. };
  78858. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78859. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78860. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78861. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78862. scene.onDisposeObservable.add(function () {
  78863. _this.dispose();
  78864. });
  78865. // Gamepad connection events
  78866. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78867. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78868. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78869. this.updateButtonVisibility();
  78870. //create easing functions
  78871. this._circleEase = new BABYLON.CircleEase();
  78872. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78873. }
  78874. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78875. /** Return this.onEnteringVRObservable
  78876. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78877. */
  78878. get: function () {
  78879. return this.onEnteringVRObservable;
  78880. },
  78881. enumerable: true,
  78882. configurable: true
  78883. });
  78884. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78885. /** Return this.onExitingVRObservable
  78886. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78887. */
  78888. get: function () {
  78889. return this.onExitingVRObservable;
  78890. },
  78891. enumerable: true,
  78892. configurable: true
  78893. });
  78894. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78895. /** Return this.onControllerMeshLoadedObservable
  78896. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78897. */
  78898. get: function () {
  78899. return this.onControllerMeshLoadedObservable;
  78900. },
  78901. enumerable: true,
  78902. configurable: true
  78903. });
  78904. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78905. /**
  78906. * The mesh used to display where the user is going to teleport.
  78907. */
  78908. get: function () {
  78909. return this._teleportationTarget;
  78910. },
  78911. /**
  78912. * Sets the mesh to be used to display where the user is going to teleport.
  78913. */
  78914. set: function (value) {
  78915. if (value) {
  78916. value.name = "teleportationTarget";
  78917. this._isDefaultTeleportationTarget = false;
  78918. this._teleportationTarget = value;
  78919. }
  78920. },
  78921. enumerable: true,
  78922. configurable: true
  78923. });
  78924. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  78925. /**
  78926. * The mesh used to display where the user is selecting.
  78927. */
  78928. get: function () {
  78929. return this._gazeTracker;
  78930. },
  78931. /**
  78932. * Sets the mesh to be used to display where the user is selecting.
  78933. */
  78934. set: function (value) {
  78935. if (value) {
  78936. this._gazeTracker = value;
  78937. this._gazeTracker.bakeCurrentTransformIntoVertices();
  78938. this._gazeTracker.isPickable = false;
  78939. this._gazeTracker.isVisible = false;
  78940. }
  78941. },
  78942. enumerable: true,
  78943. configurable: true
  78944. });
  78945. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  78946. /**
  78947. * If the ray of the gaze should be displayed.
  78948. */
  78949. get: function () {
  78950. return this._displayGaze;
  78951. },
  78952. /**
  78953. * Sets if the ray of the gaze should be displayed.
  78954. */
  78955. set: function (value) {
  78956. this._displayGaze = value;
  78957. if (!value) {
  78958. this._gazeTracker.isVisible = false;
  78959. }
  78960. },
  78961. enumerable: true,
  78962. configurable: true
  78963. });
  78964. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  78965. /**
  78966. * If the ray of the LaserPointer should be displayed.
  78967. */
  78968. get: function () {
  78969. return this._displayLaserPointer;
  78970. },
  78971. /**
  78972. * Sets if the ray of the LaserPointer should be displayed.
  78973. */
  78974. set: function (value) {
  78975. this._displayLaserPointer = value;
  78976. if (!value) {
  78977. if (this._rightLaserPointer) {
  78978. this._rightLaserPointer.isVisible = false;
  78979. }
  78980. if (this._leftLaserPointer) {
  78981. this._leftLaserPointer.isVisible = false;
  78982. }
  78983. }
  78984. else {
  78985. if (this._rightLaserPointer) {
  78986. this._rightLaserPointer.isVisible = true;
  78987. }
  78988. else if (this._leftLaserPointer) {
  78989. this._leftLaserPointer.isVisible = true;
  78990. }
  78991. }
  78992. },
  78993. enumerable: true,
  78994. configurable: true
  78995. });
  78996. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  78997. /**
  78998. * The deviceOrientationCamera used as the camera when not in VR.
  78999. */
  79000. get: function () {
  79001. return this._deviceOrientationCamera;
  79002. },
  79003. enumerable: true,
  79004. configurable: true
  79005. });
  79006. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  79007. /**
  79008. * Based on the current WebVR support, returns the current VR camera used.
  79009. */
  79010. get: function () {
  79011. if (this._webVRready) {
  79012. return this._webVRCamera;
  79013. }
  79014. else {
  79015. return this._scene.activeCamera;
  79016. }
  79017. },
  79018. enumerable: true,
  79019. configurable: true
  79020. });
  79021. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  79022. /**
  79023. * The webVRCamera which is used when in VR.
  79024. */
  79025. get: function () {
  79026. return this._webVRCamera;
  79027. },
  79028. enumerable: true,
  79029. configurable: true
  79030. });
  79031. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  79032. /**
  79033. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  79034. */
  79035. get: function () {
  79036. return this._vrDeviceOrientationCamera;
  79037. },
  79038. enumerable: true,
  79039. configurable: true
  79040. });
  79041. // Raised when one of the controller has loaded successfully its associated default mesh
  79042. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  79043. this._tryEnableInteractionOnController(webVRController);
  79044. try {
  79045. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  79046. }
  79047. catch (err) {
  79048. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  79049. }
  79050. };
  79051. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  79052. /**
  79053. * Gets a value indicating if we are currently in VR mode.
  79054. */
  79055. get: function () {
  79056. return this._webVRpresenting || this._fullscreenVRpresenting;
  79057. },
  79058. enumerable: true,
  79059. configurable: true
  79060. });
  79061. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  79062. var vrDisplay = this._scene.getEngine().getVRDevice();
  79063. if (vrDisplay) {
  79064. var wasPresenting = this._webVRpresenting;
  79065. // A VR display is connected
  79066. this._webVRpresenting = vrDisplay.isPresenting;
  79067. if (wasPresenting && !this._webVRpresenting)
  79068. this.exitVR();
  79069. }
  79070. else {
  79071. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79072. }
  79073. this.updateButtonVisibility();
  79074. };
  79075. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79076. this._webVRsupported = eventArgs.vrSupported;
  79077. this._webVRready = !!eventArgs.vrDisplay;
  79078. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79079. this.updateButtonVisibility();
  79080. };
  79081. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79082. if (this._canvas && !this._useCustomVRButton) {
  79083. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79084. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79085. }
  79086. };
  79087. VRExperienceHelper.prototype.displayVRButton = function () {
  79088. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79089. document.body.appendChild(this._btnVR);
  79090. this._btnVRDisplayed = true;
  79091. }
  79092. };
  79093. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79094. if (!this._btnVR || this._useCustomVRButton) {
  79095. return;
  79096. }
  79097. this._btnVR.className = "babylonVRicon";
  79098. if (this.isInVRMode) {
  79099. this._btnVR.className += " vrdisplaypresenting";
  79100. }
  79101. else {
  79102. if (this._webVRready)
  79103. this._btnVR.className += " vrdisplayready";
  79104. if (this._webVRsupported)
  79105. this._btnVR.className += " vrdisplaysupported";
  79106. if (this._webVRrequesting)
  79107. this._btnVR.className += " vrdisplayrequesting";
  79108. }
  79109. };
  79110. /**
  79111. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79112. * Otherwise, will use the fullscreen API.
  79113. */
  79114. VRExperienceHelper.prototype.enterVR = function () {
  79115. if (this.onEnteringVRObservable) {
  79116. try {
  79117. this.onEnteringVRObservable.notifyObservers(this);
  79118. }
  79119. catch (err) {
  79120. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79121. }
  79122. }
  79123. if (this._scene.activeCamera) {
  79124. this._position = this._scene.activeCamera.position.clone();
  79125. // make sure that we return to the last active camera
  79126. this._existingCamera = this._scene.activeCamera;
  79127. }
  79128. if (this._webVRrequesting)
  79129. return;
  79130. // If WebVR is supported and a headset is connected
  79131. if (this._webVRready) {
  79132. if (!this._webVRpresenting) {
  79133. this._webVRCamera.position = this._position;
  79134. this._scene.activeCamera = this._webVRCamera;
  79135. }
  79136. }
  79137. else if (this._vrDeviceOrientationCamera) {
  79138. this._vrDeviceOrientationCamera.position = this._position;
  79139. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79140. this._scene.getEngine().switchFullscreen(true);
  79141. this.updateButtonVisibility();
  79142. }
  79143. if (this._scene.activeCamera && this._canvas) {
  79144. this._scene.activeCamera.attachControl(this._canvas);
  79145. }
  79146. if (this._interactionsEnabled) {
  79147. this._scene.registerBeforeRender(this.beforeRender);
  79148. }
  79149. };
  79150. /**
  79151. * Attempt to exit VR, or fullscreen.
  79152. */
  79153. VRExperienceHelper.prototype.exitVR = function () {
  79154. if (this.onExitingVRObservable) {
  79155. try {
  79156. this.onExitingVRObservable.notifyObservers(this);
  79157. }
  79158. catch (err) {
  79159. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79160. }
  79161. }
  79162. if (this._webVRpresenting) {
  79163. this._scene.getEngine().disableVR();
  79164. }
  79165. if (this._scene.activeCamera) {
  79166. this._position = this._scene.activeCamera.position.clone();
  79167. }
  79168. if (this._deviceOrientationCamera) {
  79169. this._deviceOrientationCamera.position = this._position;
  79170. this._scene.activeCamera = this._deviceOrientationCamera;
  79171. if (this._canvas) {
  79172. this._scene.activeCamera.attachControl(this._canvas);
  79173. }
  79174. }
  79175. else if (this._existingCamera) {
  79176. this._existingCamera.position = this._position;
  79177. this._scene.activeCamera = this._existingCamera;
  79178. }
  79179. this.updateButtonVisibility();
  79180. if (this._interactionsEnabled) {
  79181. this._scene.unregisterBeforeRender(this.beforeRender);
  79182. }
  79183. };
  79184. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79185. /**
  79186. * The position of the vr experience helper.
  79187. */
  79188. get: function () {
  79189. return this._position;
  79190. },
  79191. /**
  79192. * Sets the position of the vr experience helper.
  79193. */
  79194. set: function (value) {
  79195. this._position = value;
  79196. if (this._scene.activeCamera) {
  79197. this._scene.activeCamera.position = value;
  79198. }
  79199. },
  79200. enumerable: true,
  79201. configurable: true
  79202. });
  79203. /**
  79204. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79205. */
  79206. VRExperienceHelper.prototype.enableInteractions = function () {
  79207. var _this = this;
  79208. if (!this._interactionsEnabled) {
  79209. this._interactionsRequested = true;
  79210. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79211. this._enableInteractionOnController(this._webVRCamera.leftController);
  79212. }
  79213. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79214. this._enableInteractionOnController(this._webVRCamera.rightController);
  79215. }
  79216. if (!this._gazeTracker) {
  79217. this._createGazeTracker();
  79218. }
  79219. this.raySelectionPredicate = function (mesh) {
  79220. return mesh.isVisible;
  79221. };
  79222. this.meshSelectionPredicate = function (mesh) {
  79223. return true;
  79224. };
  79225. this._raySelectionPredicate = function (mesh) {
  79226. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79227. && mesh.name.indexOf("teleportationTarget") === -1
  79228. && mesh.name.indexOf("torusTeleportation") === -1
  79229. && mesh.name.indexOf("laserPointer") === -1)) {
  79230. return _this.raySelectionPredicate(mesh);
  79231. }
  79232. return false;
  79233. };
  79234. this._interactionsEnabled = true;
  79235. }
  79236. };
  79237. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79238. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79239. if (this._floorMeshesCollection[i].id === mesh.id) {
  79240. return true;
  79241. }
  79242. }
  79243. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79244. return true;
  79245. }
  79246. return false;
  79247. };
  79248. /**
  79249. * Adds a floor mesh to be used for teleportation.
  79250. * @param floorMesh the mesh to be used for teleportation.
  79251. */
  79252. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79253. if (!this._floorMeshesCollection) {
  79254. return;
  79255. }
  79256. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79257. return;
  79258. }
  79259. this._floorMeshesCollection.push(floorMesh);
  79260. };
  79261. /**
  79262. * Removes a floor mesh from being used for teleportation.
  79263. * @param floorMesh the mesh to be removed.
  79264. */
  79265. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79266. if (!this._floorMeshesCollection) {
  79267. return;
  79268. }
  79269. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79270. if (meshIndex !== -1) {
  79271. this._floorMeshesCollection.splice(meshIndex, 1);
  79272. }
  79273. };
  79274. /**
  79275. * Enables interactions and teleportation using the VR controllers and gaze.
  79276. * @param vrTeleportationOptions options to modify teleportation behavior.
  79277. */
  79278. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79279. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79280. if (!this._teleportationInitialized) {
  79281. this._teleportationRequested = true;
  79282. this.enableInteractions();
  79283. if (vrTeleportationOptions.floorMeshName) {
  79284. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79285. }
  79286. if (vrTeleportationOptions.floorMeshes) {
  79287. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79288. }
  79289. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79290. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79291. }
  79292. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79293. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79294. }
  79295. // Creates an image processing post process for the vignette not relying
  79296. // on the main scene configuration for image processing to reduce setup and spaces
  79297. // (gamma/linear) conflicts.
  79298. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79299. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79300. imageProcessingConfiguration.vignetteEnabled = true;
  79301. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79302. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79303. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79304. this._teleportationInitialized = true;
  79305. if (this._isDefaultTeleportationTarget) {
  79306. this._createTeleportationCircles();
  79307. }
  79308. }
  79309. };
  79310. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79311. var _this = this;
  79312. var controllerMesh = webVRController.mesh;
  79313. if (controllerMesh) {
  79314. var makeNotPick = function (root) {
  79315. root.name += " laserPointer";
  79316. root.getChildMeshes().forEach(function (c) {
  79317. makeNotPick(c);
  79318. });
  79319. };
  79320. makeNotPick(controllerMesh);
  79321. var childMeshes = controllerMesh.getChildMeshes();
  79322. for (var i = 0; i < childMeshes.length; i++) {
  79323. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79324. controllerMesh = childMeshes[i];
  79325. break;
  79326. }
  79327. }
  79328. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79329. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79330. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79331. laserPointerMaterial.alpha = 0.6;
  79332. laserPointer.material = laserPointerMaterial;
  79333. laserPointer.rotation.x = Math.PI / 2;
  79334. laserPointer.parent = controllerMesh;
  79335. laserPointer.position.z = -0.5;
  79336. laserPointer.isVisible = false;
  79337. if (webVRController.hand === "left") {
  79338. this._leftLaserPointer = laserPointer;
  79339. this._interactionsEnabledOnLeftController = true;
  79340. if (!this._rightLaserPointer) {
  79341. this._leftLaserPointer.isVisible = true;
  79342. }
  79343. }
  79344. else {
  79345. this._rightLaserPointer = laserPointer;
  79346. this._interactionsEnabledOnRightController = true;
  79347. if (!this._leftLaserPointer) {
  79348. this._rightLaserPointer.isVisible = true;
  79349. }
  79350. }
  79351. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79352. // Enabling / disabling laserPointer
  79353. if (_this._displayLaserPointer && stateObject.value === 1) {
  79354. laserPointer.isVisible = !laserPointer.isVisible;
  79355. // Laser pointer can only be active on left or right, not both at the same time
  79356. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79357. _this._rightLaserPointer.isVisible = false;
  79358. }
  79359. else if (_this._leftLaserPointer) {
  79360. _this._leftLaserPointer.isVisible = false;
  79361. }
  79362. }
  79363. });
  79364. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79365. if (!_this._pointerDownOnMeshAsked) {
  79366. if (stateObject.value > _this._padSensibilityUp) {
  79367. _this._selectionPointerDown();
  79368. }
  79369. }
  79370. else if (stateObject.value < _this._padSensibilityDown) {
  79371. _this._selectionPointerUp();
  79372. }
  79373. });
  79374. }
  79375. };
  79376. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79377. if (webVRController === void 0) { webVRController = null; }
  79378. if (!this._teleportationRequestInitiated) {
  79379. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79380. if (webVRController) {
  79381. // If laser pointer wasn't enabled yet
  79382. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79383. this._leftLaserPointer.isVisible = true;
  79384. if (this._rightLaserPointer) {
  79385. this._rightLaserPointer.isVisible = false;
  79386. }
  79387. }
  79388. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79389. this._rightLaserPointer.isVisible = true;
  79390. if (this._leftLaserPointer) {
  79391. this._leftLaserPointer.isVisible = false;
  79392. }
  79393. }
  79394. }
  79395. this._teleportationRequestInitiated = true;
  79396. }
  79397. }
  79398. else {
  79399. // Listening to the proper controller values changes to confirm teleportation
  79400. if (webVRController == null
  79401. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79402. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79403. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79404. if (this._teleportationAllowed) {
  79405. this._teleportationAllowed = false;
  79406. this._teleportCamera();
  79407. }
  79408. this._teleportationRequestInitiated = false;
  79409. }
  79410. }
  79411. }
  79412. };
  79413. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79414. this._pointerDownOnMeshAsked = true;
  79415. if (this._currentMeshSelected && this._currentHit) {
  79416. this._scene.simulatePointerDown(this._currentHit);
  79417. }
  79418. };
  79419. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79420. if (this._currentMeshSelected && this._currentHit) {
  79421. this._scene.simulatePointerUp(this._currentHit);
  79422. }
  79423. this._pointerDownOnMeshAsked = false;
  79424. };
  79425. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79426. // Only rotate when user is not currently selecting a teleportation location
  79427. if (this._teleportationRequestInitiated) {
  79428. return;
  79429. }
  79430. if (!this._rotationLeftAsked) {
  79431. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79432. this._rotationLeftAsked = true;
  79433. if (this._rotationAllowed) {
  79434. this._rotateCamera(false);
  79435. }
  79436. }
  79437. }
  79438. else {
  79439. if (stateObject.x > -this._padSensibilityDown) {
  79440. this._rotationLeftAsked = false;
  79441. }
  79442. }
  79443. if (!this._rotationRightAsked) {
  79444. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79445. this._rotationRightAsked = true;
  79446. if (this._rotationAllowed) {
  79447. this._rotateCamera(true);
  79448. }
  79449. }
  79450. }
  79451. else {
  79452. if (stateObject.x < this._padSensibilityDown) {
  79453. this._rotationRightAsked = false;
  79454. }
  79455. }
  79456. };
  79457. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79458. // Only teleport backwards when user is not currently selecting a teleportation location
  79459. if (this._teleportationRequestInitiated) {
  79460. return;
  79461. }
  79462. // Teleport backwards
  79463. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79464. if (!this._teleportationBackRequestInitiated) {
  79465. if (!this.currentVRCamera) {
  79466. return;
  79467. }
  79468. // Get rotation and position of the current camera
  79469. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79470. var position = this.currentVRCamera.position;
  79471. // If the camera has device position, use that instead
  79472. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79473. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79474. position = this.currentVRCamera.devicePosition;
  79475. }
  79476. // Get matrix with only the y rotation of the device rotation
  79477. rotation.toEulerAnglesToRef(this._workingVector);
  79478. this._workingVector.z = 0;
  79479. this._workingVector.x = 0;
  79480. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79481. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79482. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79483. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79484. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79485. var ray = new BABYLON.Ray(position, this._workingVector);
  79486. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79487. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79488. this._teleportCamera(hit.pickedPoint);
  79489. }
  79490. this._teleportationBackRequestInitiated = true;
  79491. }
  79492. }
  79493. else {
  79494. this._teleportationBackRequestInitiated = false;
  79495. }
  79496. };
  79497. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79498. var _this = this;
  79499. var controllerMesh = webVRController.mesh;
  79500. if (controllerMesh) {
  79501. if (webVRController.hand === "left") {
  79502. if (!this._interactionsEnabledOnLeftController) {
  79503. this._enableInteractionOnController(webVRController);
  79504. }
  79505. this._teleportationEnabledOnLeftController = true;
  79506. }
  79507. else {
  79508. if (!this._interactionsEnabledOnRightController) {
  79509. this._enableInteractionOnController(webVRController);
  79510. }
  79511. this._teleportationEnabledOnRightController = true;
  79512. }
  79513. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79514. this._dpadPressed = false;
  79515. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79516. _this._dpadPressed = stateObject.pressed;
  79517. if (!_this._dpadPressed) {
  79518. _this._rotationLeftAsked = false;
  79519. _this._rotationRightAsked = false;
  79520. _this._teleportationBackRequestInitiated = false;
  79521. }
  79522. });
  79523. }
  79524. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79525. if (_this.teleportationEnabled) {
  79526. _this._checkTeleportBackwards(stateObject);
  79527. _this._checkTeleportWithRay(stateObject, webVRController);
  79528. }
  79529. _this._checkRotate(stateObject);
  79530. });
  79531. }
  79532. };
  79533. // Gaze support used to point to teleport or to interact with an object
  79534. VRExperienceHelper.prototype._createGazeTracker = function () {
  79535. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79536. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79537. this._gazeTracker.isPickable = false;
  79538. this._gazeTracker.isVisible = false;
  79539. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79540. targetMat.specularColor = BABYLON.Color3.Black();
  79541. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79542. targetMat.backFaceCulling = false;
  79543. this._gazeTracker.material = targetMat;
  79544. };
  79545. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79546. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79547. this._teleportationTarget.isPickable = false;
  79548. var length = 512;
  79549. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79550. dynamicTexture.hasAlpha = true;
  79551. var context = dynamicTexture.getContext();
  79552. var centerX = length / 2;
  79553. var centerY = length / 2;
  79554. var radius = 200;
  79555. context.beginPath();
  79556. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79557. context.fillStyle = this._teleportationFillColor;
  79558. context.fill();
  79559. context.lineWidth = 10;
  79560. context.strokeStyle = this._teleportationBorderColor;
  79561. context.stroke();
  79562. context.closePath();
  79563. dynamicTexture.update();
  79564. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79565. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79566. this._teleportationTarget.material = teleportationCircleMaterial;
  79567. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79568. torus.isPickable = false;
  79569. torus.parent = this._teleportationTarget;
  79570. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79571. var keys = [];
  79572. keys.push({
  79573. frame: 0,
  79574. value: 0
  79575. });
  79576. keys.push({
  79577. frame: 30,
  79578. value: 0.4
  79579. });
  79580. keys.push({
  79581. frame: 60,
  79582. value: 0
  79583. });
  79584. animationInnerCircle.setKeys(keys);
  79585. var easingFunction = new BABYLON.SineEase();
  79586. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79587. animationInnerCircle.setEasingFunction(easingFunction);
  79588. torus.animations = [];
  79589. torus.animations.push(animationInnerCircle);
  79590. this._scene.beginAnimation(torus, 0, 60, true);
  79591. this._hideTeleportationTarget();
  79592. };
  79593. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79594. if (this._teleportationInitialized) {
  79595. this._teleportationTarget.isVisible = true;
  79596. if (this._isDefaultTeleportationTarget) {
  79597. this._teleportationTarget.getChildren()[0].isVisible = true;
  79598. }
  79599. }
  79600. };
  79601. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79602. if (this._teleportationInitialized) {
  79603. this._teleportationTarget.isVisible = false;
  79604. if (this._isDefaultTeleportationTarget) {
  79605. this._teleportationTarget.getChildren()[0].isVisible = false;
  79606. }
  79607. }
  79608. };
  79609. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79610. var _this = this;
  79611. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79612. return;
  79613. }
  79614. if (right) {
  79615. this._rotationAngle++;
  79616. }
  79617. else {
  79618. this._rotationAngle--;
  79619. }
  79620. this.currentVRCamera.animations = [];
  79621. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79622. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79623. var animationRotationKeys = [];
  79624. animationRotationKeys.push({
  79625. frame: 0,
  79626. value: this.currentVRCamera.rotationQuaternion
  79627. });
  79628. animationRotationKeys.push({
  79629. frame: 6,
  79630. value: target
  79631. });
  79632. animationRotation.setKeys(animationRotationKeys);
  79633. animationRotation.setEasingFunction(this._circleEase);
  79634. this.currentVRCamera.animations.push(animationRotation);
  79635. this._postProcessMove.animations = [];
  79636. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79637. var vignetteWeightKeys = [];
  79638. vignetteWeightKeys.push({
  79639. frame: 0,
  79640. value: 0
  79641. });
  79642. vignetteWeightKeys.push({
  79643. frame: 3,
  79644. value: 4
  79645. });
  79646. vignetteWeightKeys.push({
  79647. frame: 6,
  79648. value: 0
  79649. });
  79650. animationPP.setKeys(vignetteWeightKeys);
  79651. animationPP.setEasingFunction(this._circleEase);
  79652. this._postProcessMove.animations.push(animationPP);
  79653. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79654. var vignetteStretchKeys = [];
  79655. vignetteStretchKeys.push({
  79656. frame: 0,
  79657. value: 0
  79658. });
  79659. vignetteStretchKeys.push({
  79660. frame: 3,
  79661. value: 10
  79662. });
  79663. vignetteStretchKeys.push({
  79664. frame: 6,
  79665. value: 0
  79666. });
  79667. animationPP2.setKeys(vignetteStretchKeys);
  79668. animationPP2.setEasingFunction(this._circleEase);
  79669. this._postProcessMove.animations.push(animationPP2);
  79670. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79671. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79672. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79673. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79674. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79675. });
  79676. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79677. };
  79678. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79679. if (hit.pickedPoint) {
  79680. this._teleportationAllowed = true;
  79681. if (this._teleportationRequestInitiated) {
  79682. this._displayTeleportationTarget();
  79683. }
  79684. else {
  79685. this._hideTeleportationTarget();
  79686. }
  79687. this._haloCenter.copyFrom(hit.pickedPoint);
  79688. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79689. var pickNormal = hit.getNormal(true, false);
  79690. if (pickNormal) {
  79691. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79692. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79693. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79694. }
  79695. this._teleportationTarget.position.y += 0.1;
  79696. }
  79697. };
  79698. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79699. var _this = this;
  79700. if (location === void 0) { location = null; }
  79701. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79702. return;
  79703. }
  79704. if (!location) {
  79705. location = this._haloCenter;
  79706. }
  79707. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79708. // offset of the headset from the anchor.
  79709. if (this.webVRCamera.leftCamera) {
  79710. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79711. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79712. location.subtractToRef(this._workingVector, this._workingVector);
  79713. }
  79714. else {
  79715. this._workingVector.copyFrom(location);
  79716. }
  79717. // Add height to account for user's height offset
  79718. if (this.isInVRMode) {
  79719. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79720. }
  79721. else {
  79722. this._workingVector.y += this._defaultHeight;
  79723. }
  79724. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79725. // Create animation from the camera's position to the new location
  79726. this.currentVRCamera.animations = [];
  79727. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79728. var animationCameraTeleportationKeys = [{
  79729. frame: 0,
  79730. value: this.currentVRCamera.position
  79731. },
  79732. {
  79733. frame: 11,
  79734. value: this._workingVector
  79735. }
  79736. ];
  79737. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79738. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79739. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79740. this._postProcessMove.animations = [];
  79741. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79742. var vignetteWeightKeys = [];
  79743. vignetteWeightKeys.push({
  79744. frame: 0,
  79745. value: 0
  79746. });
  79747. vignetteWeightKeys.push({
  79748. frame: 5,
  79749. value: 8
  79750. });
  79751. vignetteWeightKeys.push({
  79752. frame: 11,
  79753. value: 0
  79754. });
  79755. animationPP.setKeys(vignetteWeightKeys);
  79756. this._postProcessMove.animations.push(animationPP);
  79757. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79758. var vignetteStretchKeys = [];
  79759. vignetteStretchKeys.push({
  79760. frame: 0,
  79761. value: 0
  79762. });
  79763. vignetteStretchKeys.push({
  79764. frame: 5,
  79765. value: 10
  79766. });
  79767. vignetteStretchKeys.push({
  79768. frame: 11,
  79769. value: 0
  79770. });
  79771. animationPP2.setKeys(vignetteStretchKeys);
  79772. this._postProcessMove.animations.push(animationPP2);
  79773. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79774. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79775. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79776. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79777. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79778. });
  79779. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79780. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79781. });
  79782. };
  79783. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79784. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79785. return;
  79786. }
  79787. var ray;
  79788. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79789. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79790. }
  79791. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79792. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79793. }
  79794. else {
  79795. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79796. }
  79797. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79798. // Moving the gazeTracker on the mesh face targetted
  79799. if (hit && hit.pickedPoint) {
  79800. if (this._displayGaze) {
  79801. var multiplier = 1;
  79802. this._gazeTracker.isVisible = true;
  79803. if (this._isActionableMesh) {
  79804. multiplier = 3;
  79805. }
  79806. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79807. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79808. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79809. var pickNormal = hit.getNormal();
  79810. // To avoid z-fighting
  79811. var deltaFighting = 0.002;
  79812. if (pickNormal) {
  79813. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79814. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79815. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79816. }
  79817. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79818. if (this._gazeTracker.position.x < 0) {
  79819. this._gazeTracker.position.x += deltaFighting;
  79820. }
  79821. else {
  79822. this._gazeTracker.position.x -= deltaFighting;
  79823. }
  79824. if (this._gazeTracker.position.y < 0) {
  79825. this._gazeTracker.position.y += deltaFighting;
  79826. }
  79827. else {
  79828. this._gazeTracker.position.y -= deltaFighting;
  79829. }
  79830. if (this._gazeTracker.position.z < 0) {
  79831. this._gazeTracker.position.z += deltaFighting;
  79832. }
  79833. else {
  79834. this._gazeTracker.position.z -= deltaFighting;
  79835. }
  79836. }
  79837. // Changing the size of the laser pointer based on the distance from the targetted point
  79838. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79839. this._rightLaserPointer.scaling.y = hit.distance;
  79840. this._rightLaserPointer.position.z = -hit.distance / 2;
  79841. }
  79842. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79843. this._leftLaserPointer.scaling.y = hit.distance;
  79844. this._leftLaserPointer.position.z = -hit.distance / 2;
  79845. }
  79846. }
  79847. else {
  79848. this._gazeTracker.isVisible = false;
  79849. }
  79850. if (hit && hit.pickedMesh) {
  79851. this._currentHit = hit;
  79852. if (this._pointerDownOnMeshAsked) {
  79853. this._scene.simulatePointerMove(this._currentHit);
  79854. }
  79855. // The object selected is the floor, we're in a teleportation scenario
  79856. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79857. // Moving the teleportation area to this targetted point
  79858. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79859. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79860. this._notifySelectedMeshUnselected();
  79861. }
  79862. this._currentMeshSelected = null;
  79863. this._moveTeleportationSelectorTo(hit);
  79864. return;
  79865. }
  79866. // If not, we're in a selection scenario
  79867. this._hideTeleportationTarget();
  79868. this._teleportationAllowed = false;
  79869. if (hit.pickedMesh !== this._currentMeshSelected) {
  79870. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79871. this.onNewMeshPicked.notifyObservers(hit);
  79872. this._currentMeshSelected = hit.pickedMesh;
  79873. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79874. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79875. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79876. this._isActionableMesh = true;
  79877. }
  79878. else {
  79879. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79880. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79881. this._isActionableMesh = false;
  79882. }
  79883. try {
  79884. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79885. }
  79886. catch (err) {
  79887. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79888. }
  79889. }
  79890. else {
  79891. this._notifySelectedMeshUnselected();
  79892. this._currentMeshSelected = null;
  79893. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79894. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79895. }
  79896. }
  79897. }
  79898. else {
  79899. this._currentHit = null;
  79900. this._notifySelectedMeshUnselected();
  79901. this._currentMeshSelected = null;
  79902. this._teleportationAllowed = false;
  79903. this._hideTeleportationTarget();
  79904. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79905. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79906. }
  79907. };
  79908. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  79909. if (this._currentMeshSelected) {
  79910. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  79911. }
  79912. };
  79913. /**
  79914. * Sets the color of the laser ray from the vr controllers.
  79915. * @param color new color for the ray.
  79916. */
  79917. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  79918. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  79919. this._leftLaserPointer.material.emissiveColor = color;
  79920. }
  79921. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  79922. this._rightLaserPointer.material.emissiveColor = color;
  79923. }
  79924. };
  79925. /**
  79926. * Sets the color of the ray from the vr headsets gaze.
  79927. * @param color new color for the ray.
  79928. */
  79929. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  79930. if (this._gazeTracker.material) {
  79931. this._gazeTracker.material.emissiveColor = color;
  79932. }
  79933. };
  79934. /**
  79935. * Exits VR and disposes of the vr experience helper
  79936. */
  79937. VRExperienceHelper.prototype.dispose = function () {
  79938. if (this.isInVRMode) {
  79939. this.exitVR();
  79940. }
  79941. if (this._passProcessMove) {
  79942. this._passProcessMove.dispose();
  79943. }
  79944. if (this._postProcessMove) {
  79945. this._postProcessMove.dispose();
  79946. }
  79947. if (this._webVRCamera) {
  79948. this._webVRCamera.dispose();
  79949. }
  79950. if (this._vrDeviceOrientationCamera) {
  79951. this._vrDeviceOrientationCamera.dispose();
  79952. }
  79953. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  79954. document.body.removeChild(this._btnVR);
  79955. }
  79956. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  79957. this._deviceOrientationCamera.dispose();
  79958. }
  79959. if (this._gazeTracker) {
  79960. this._gazeTracker.dispose();
  79961. }
  79962. if (this._teleportationTarget) {
  79963. this._teleportationTarget.dispose();
  79964. }
  79965. this._floorMeshesCollection = [];
  79966. document.removeEventListener("keydown", this._onKeyDown);
  79967. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79968. window.removeEventListener("resize", this._onResize);
  79969. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  79970. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  79971. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  79972. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  79973. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  79974. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  79975. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  79976. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79977. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  79978. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  79979. this._scene.unregisterBeforeRender(this.beforeRender);
  79980. };
  79981. /**
  79982. * Gets the name of the VRExperienceHelper class
  79983. * @returns "VRExperienceHelper"
  79984. */
  79985. VRExperienceHelper.prototype.getClassName = function () {
  79986. return "VRExperienceHelper";
  79987. };
  79988. return VRExperienceHelper;
  79989. }());
  79990. BABYLON.VRExperienceHelper = VRExperienceHelper;
  79991. })(BABYLON || (BABYLON = {}));
  79992. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  79993. // Mainly based on these 2 articles :
  79994. // 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
  79995. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  79996. var BABYLON;
  79997. (function (BABYLON) {
  79998. var JoystickAxis;
  79999. (function (JoystickAxis) {
  80000. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  80001. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  80002. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  80003. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  80004. var VirtualJoystick = /** @class */ (function () {
  80005. function VirtualJoystick(leftJoystick) {
  80006. var _this = this;
  80007. if (leftJoystick) {
  80008. this._leftJoystick = true;
  80009. }
  80010. else {
  80011. this._leftJoystick = false;
  80012. }
  80013. VirtualJoystick._globalJoystickIndex++;
  80014. // By default left & right arrow keys are moving the X
  80015. // and up & down keys are moving the Y
  80016. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80017. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80018. this.reverseLeftRight = false;
  80019. this.reverseUpDown = false;
  80020. // collections of pointers
  80021. this._touches = new BABYLON.StringDictionary();
  80022. this.deltaPosition = BABYLON.Vector3.Zero();
  80023. this._joystickSensibility = 25;
  80024. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80025. this._onResize = function (evt) {
  80026. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80027. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80028. if (VirtualJoystick.vjCanvas) {
  80029. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  80030. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  80031. }
  80032. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  80033. };
  80034. // injecting a canvas element on top of the canvas 3D game
  80035. if (!VirtualJoystick.vjCanvas) {
  80036. window.addEventListener("resize", this._onResize, false);
  80037. VirtualJoystick.vjCanvas = document.createElement("canvas");
  80038. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80039. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80040. VirtualJoystick.vjCanvas.width = window.innerWidth;
  80041. VirtualJoystick.vjCanvas.height = window.innerHeight;
  80042. VirtualJoystick.vjCanvas.style.width = "100%";
  80043. VirtualJoystick.vjCanvas.style.height = "100%";
  80044. VirtualJoystick.vjCanvas.style.position = "absolute";
  80045. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  80046. VirtualJoystick.vjCanvas.style.top = "0px";
  80047. VirtualJoystick.vjCanvas.style.left = "0px";
  80048. VirtualJoystick.vjCanvas.style.zIndex = "5";
  80049. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  80050. // Support for jQuery PEP polyfill
  80051. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  80052. var context = VirtualJoystick.vjCanvas.getContext('2d');
  80053. if (!context) {
  80054. throw new Error("Unable to create canvas for virtual joystick");
  80055. }
  80056. VirtualJoystick.vjCanvasContext = context;
  80057. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  80058. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80059. document.body.appendChild(VirtualJoystick.vjCanvas);
  80060. }
  80061. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  80062. this.pressed = false;
  80063. // default joystick color
  80064. this._joystickColor = "cyan";
  80065. this._joystickPointerID = -1;
  80066. // current joystick position
  80067. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80068. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80069. // origin joystick position
  80070. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80071. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80072. this._onPointerDownHandlerRef = function (evt) {
  80073. _this._onPointerDown(evt);
  80074. };
  80075. this._onPointerMoveHandlerRef = function (evt) {
  80076. _this._onPointerMove(evt);
  80077. };
  80078. this._onPointerUpHandlerRef = function (evt) {
  80079. _this._onPointerUp(evt);
  80080. };
  80081. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80082. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80083. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80084. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80085. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80086. evt.preventDefault(); // Disables system menu
  80087. }, false);
  80088. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80089. }
  80090. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80091. this._joystickSensibility = newJoystickSensibility;
  80092. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80093. };
  80094. VirtualJoystick.prototype._onPointerDown = function (e) {
  80095. var positionOnScreenCondition;
  80096. e.preventDefault();
  80097. if (this._leftJoystick === true) {
  80098. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80099. }
  80100. else {
  80101. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80102. }
  80103. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80104. // First contact will be dedicated to the virtual joystick
  80105. this._joystickPointerID = e.pointerId;
  80106. this._joystickPointerStartPos.x = e.clientX;
  80107. this._joystickPointerStartPos.y = e.clientY;
  80108. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80109. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80110. this._deltaJoystickVector.x = 0;
  80111. this._deltaJoystickVector.y = 0;
  80112. this.pressed = true;
  80113. this._touches.add(e.pointerId.toString(), e);
  80114. }
  80115. else {
  80116. // You can only trigger the action buttons with a joystick declared
  80117. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80118. this._action();
  80119. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80120. }
  80121. }
  80122. };
  80123. VirtualJoystick.prototype._onPointerMove = function (e) {
  80124. // If the current pointer is the one associated to the joystick (first touch contact)
  80125. if (this._joystickPointerID == e.pointerId) {
  80126. this._joystickPointerPos.x = e.clientX;
  80127. this._joystickPointerPos.y = e.clientY;
  80128. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80129. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80130. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80131. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80132. switch (this._axisTargetedByLeftAndRight) {
  80133. case JoystickAxis.X:
  80134. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80135. break;
  80136. case JoystickAxis.Y:
  80137. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80138. break;
  80139. case JoystickAxis.Z:
  80140. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80141. break;
  80142. }
  80143. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80144. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80145. switch (this._axisTargetedByUpAndDown) {
  80146. case JoystickAxis.X:
  80147. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80148. break;
  80149. case JoystickAxis.Y:
  80150. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80151. break;
  80152. case JoystickAxis.Z:
  80153. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80154. break;
  80155. }
  80156. }
  80157. else {
  80158. var data = this._touches.get(e.pointerId.toString());
  80159. if (data) {
  80160. data.x = e.clientX;
  80161. data.y = e.clientY;
  80162. }
  80163. }
  80164. };
  80165. VirtualJoystick.prototype._onPointerUp = function (e) {
  80166. if (this._joystickPointerID == e.pointerId) {
  80167. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80168. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80169. this._joystickPointerID = -1;
  80170. this.pressed = false;
  80171. }
  80172. else {
  80173. var touch = this._touches.get(e.pointerId.toString());
  80174. if (touch) {
  80175. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80176. }
  80177. }
  80178. this._deltaJoystickVector.x = 0;
  80179. this._deltaJoystickVector.y = 0;
  80180. this._touches.remove(e.pointerId.toString());
  80181. };
  80182. /**
  80183. * Change the color of the virtual joystick
  80184. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80185. */
  80186. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80187. this._joystickColor = newColor;
  80188. };
  80189. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80190. this._action = action;
  80191. };
  80192. // Define which axis you'd like to control for left & right
  80193. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80194. switch (axis) {
  80195. case JoystickAxis.X:
  80196. case JoystickAxis.Y:
  80197. case JoystickAxis.Z:
  80198. this._axisTargetedByLeftAndRight = axis;
  80199. break;
  80200. default:
  80201. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80202. break;
  80203. }
  80204. };
  80205. // Define which axis you'd like to control for up & down
  80206. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80207. switch (axis) {
  80208. case JoystickAxis.X:
  80209. case JoystickAxis.Y:
  80210. case JoystickAxis.Z:
  80211. this._axisTargetedByUpAndDown = axis;
  80212. break;
  80213. default:
  80214. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80215. break;
  80216. }
  80217. };
  80218. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80219. var _this = this;
  80220. if (this.pressed) {
  80221. this._touches.forEach(function (key, touch) {
  80222. if (touch.pointerId === _this._joystickPointerID) {
  80223. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80224. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80225. VirtualJoystick.vjCanvasContext.beginPath();
  80226. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80227. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80228. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80229. VirtualJoystick.vjCanvasContext.stroke();
  80230. VirtualJoystick.vjCanvasContext.closePath();
  80231. VirtualJoystick.vjCanvasContext.beginPath();
  80232. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80233. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80234. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80235. VirtualJoystick.vjCanvasContext.stroke();
  80236. VirtualJoystick.vjCanvasContext.closePath();
  80237. VirtualJoystick.vjCanvasContext.beginPath();
  80238. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80239. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80240. VirtualJoystick.vjCanvasContext.stroke();
  80241. VirtualJoystick.vjCanvasContext.closePath();
  80242. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80243. }
  80244. else {
  80245. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80246. VirtualJoystick.vjCanvasContext.beginPath();
  80247. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80248. VirtualJoystick.vjCanvasContext.beginPath();
  80249. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80250. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80251. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80252. VirtualJoystick.vjCanvasContext.stroke();
  80253. VirtualJoystick.vjCanvasContext.closePath();
  80254. touch.prevX = touch.x;
  80255. touch.prevY = touch.y;
  80256. }
  80257. ;
  80258. });
  80259. }
  80260. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80261. };
  80262. VirtualJoystick.prototype.releaseCanvas = function () {
  80263. if (VirtualJoystick.vjCanvas) {
  80264. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80265. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80266. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80267. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80268. window.removeEventListener("resize", this._onResize);
  80269. document.body.removeChild(VirtualJoystick.vjCanvas);
  80270. VirtualJoystick.vjCanvas = null;
  80271. }
  80272. };
  80273. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80274. VirtualJoystick._globalJoystickIndex = 0;
  80275. return VirtualJoystick;
  80276. }());
  80277. BABYLON.VirtualJoystick = VirtualJoystick;
  80278. })(BABYLON || (BABYLON = {}));
  80279. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80280. var BABYLON;
  80281. (function (BABYLON) {
  80282. // We're mainly based on the logic defined into the FreeCamera code
  80283. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80284. __extends(VirtualJoysticksCamera, _super);
  80285. function VirtualJoysticksCamera(name, position, scene) {
  80286. var _this = _super.call(this, name, position, scene) || this;
  80287. _this.inputs.addVirtualJoystick();
  80288. return _this;
  80289. }
  80290. VirtualJoysticksCamera.prototype.getClassName = function () {
  80291. return "VirtualJoysticksCamera";
  80292. };
  80293. return VirtualJoysticksCamera;
  80294. }(BABYLON.FreeCamera));
  80295. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80296. })(BABYLON || (BABYLON = {}));
  80297. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80298. var BABYLON;
  80299. (function (BABYLON) {
  80300. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80301. function FreeCameraVirtualJoystickInput() {
  80302. }
  80303. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80304. return this._leftjoystick;
  80305. };
  80306. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80307. return this._rightjoystick;
  80308. };
  80309. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80310. if (this._leftjoystick) {
  80311. var camera = this.camera;
  80312. var speed = camera._computeLocalCameraSpeed() * 50;
  80313. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80314. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80315. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80316. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80317. if (!this._leftjoystick.pressed) {
  80318. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80319. }
  80320. if (!this._rightjoystick.pressed) {
  80321. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80322. }
  80323. }
  80324. };
  80325. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80326. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80327. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80328. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80329. this._leftjoystick.setJoystickSensibility(0.15);
  80330. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80331. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80332. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80333. this._rightjoystick.reverseUpDown = true;
  80334. this._rightjoystick.setJoystickSensibility(0.05);
  80335. this._rightjoystick.setJoystickColor("yellow");
  80336. };
  80337. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80338. this._leftjoystick.releaseCanvas();
  80339. this._rightjoystick.releaseCanvas();
  80340. };
  80341. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80342. return "FreeCameraVirtualJoystickInput";
  80343. };
  80344. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80345. return "virtualJoystick";
  80346. };
  80347. return FreeCameraVirtualJoystickInput;
  80348. }());
  80349. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80350. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80351. })(BABYLON || (BABYLON = {}));
  80352. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80353. var BABYLON;
  80354. (function (BABYLON) {
  80355. var SimplificationSettings = /** @class */ (function () {
  80356. function SimplificationSettings(quality, distance, optimizeMesh) {
  80357. this.quality = quality;
  80358. this.distance = distance;
  80359. this.optimizeMesh = optimizeMesh;
  80360. }
  80361. return SimplificationSettings;
  80362. }());
  80363. BABYLON.SimplificationSettings = SimplificationSettings;
  80364. var SimplificationQueue = /** @class */ (function () {
  80365. function SimplificationQueue() {
  80366. this.running = false;
  80367. this._simplificationArray = [];
  80368. }
  80369. SimplificationQueue.prototype.addTask = function (task) {
  80370. this._simplificationArray.push(task);
  80371. };
  80372. SimplificationQueue.prototype.executeNext = function () {
  80373. var task = this._simplificationArray.pop();
  80374. if (task) {
  80375. this.running = true;
  80376. this.runSimplification(task);
  80377. }
  80378. else {
  80379. this.running = false;
  80380. }
  80381. };
  80382. SimplificationQueue.prototype.runSimplification = function (task) {
  80383. var _this = this;
  80384. if (task.parallelProcessing) {
  80385. //parallel simplifier
  80386. task.settings.forEach(function (setting) {
  80387. var simplifier = _this.getSimplifier(task);
  80388. simplifier.simplify(setting, function (newMesh) {
  80389. task.mesh.addLODLevel(setting.distance, newMesh);
  80390. newMesh.isVisible = true;
  80391. //check if it is the last
  80392. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80393. //all done, run the success callback.
  80394. task.successCallback();
  80395. }
  80396. _this.executeNext();
  80397. });
  80398. });
  80399. }
  80400. else {
  80401. //single simplifier.
  80402. var simplifier = this.getSimplifier(task);
  80403. var runDecimation = function (setting, callback) {
  80404. simplifier.simplify(setting, function (newMesh) {
  80405. task.mesh.addLODLevel(setting.distance, newMesh);
  80406. newMesh.isVisible = true;
  80407. //run the next quality level
  80408. callback();
  80409. });
  80410. };
  80411. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80412. runDecimation(task.settings[loop.index], function () {
  80413. loop.executeNext();
  80414. });
  80415. }, function () {
  80416. //execution ended, run the success callback.
  80417. if (task.successCallback) {
  80418. task.successCallback();
  80419. }
  80420. _this.executeNext();
  80421. });
  80422. }
  80423. };
  80424. SimplificationQueue.prototype.getSimplifier = function (task) {
  80425. switch (task.simplificationType) {
  80426. case SimplificationType.QUADRATIC:
  80427. default:
  80428. return new QuadraticErrorSimplification(task.mesh);
  80429. }
  80430. };
  80431. return SimplificationQueue;
  80432. }());
  80433. BABYLON.SimplificationQueue = SimplificationQueue;
  80434. /**
  80435. * The implemented types of simplification.
  80436. * At the moment only Quadratic Error Decimation is implemented.
  80437. */
  80438. var SimplificationType;
  80439. (function (SimplificationType) {
  80440. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80441. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80442. var DecimationTriangle = /** @class */ (function () {
  80443. function DecimationTriangle(vertices) {
  80444. this.vertices = vertices;
  80445. this.error = new Array(4);
  80446. this.deleted = false;
  80447. this.isDirty = false;
  80448. this.deletePending = false;
  80449. this.borderFactor = 0;
  80450. }
  80451. return DecimationTriangle;
  80452. }());
  80453. BABYLON.DecimationTriangle = DecimationTriangle;
  80454. var DecimationVertex = /** @class */ (function () {
  80455. function DecimationVertex(position, id) {
  80456. this.position = position;
  80457. this.id = id;
  80458. this.isBorder = true;
  80459. this.q = new QuadraticMatrix();
  80460. this.triangleCount = 0;
  80461. this.triangleStart = 0;
  80462. this.originalOffsets = [];
  80463. }
  80464. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80465. this.position.copyFrom(newPosition);
  80466. };
  80467. return DecimationVertex;
  80468. }());
  80469. BABYLON.DecimationVertex = DecimationVertex;
  80470. var QuadraticMatrix = /** @class */ (function () {
  80471. function QuadraticMatrix(data) {
  80472. this.data = new Array(10);
  80473. for (var i = 0; i < 10; ++i) {
  80474. if (data && data[i]) {
  80475. this.data[i] = data[i];
  80476. }
  80477. else {
  80478. this.data[i] = 0;
  80479. }
  80480. }
  80481. }
  80482. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80483. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80484. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80485. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80486. return det;
  80487. };
  80488. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80489. for (var i = 0; i < 10; ++i) {
  80490. this.data[i] += matrix.data[i];
  80491. }
  80492. };
  80493. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80494. for (var i = 0; i < 10; ++i) {
  80495. this.data[i] += data[i];
  80496. }
  80497. };
  80498. QuadraticMatrix.prototype.add = function (matrix) {
  80499. var m = new QuadraticMatrix();
  80500. for (var i = 0; i < 10; ++i) {
  80501. m.data[i] = this.data[i] + matrix.data[i];
  80502. }
  80503. return m;
  80504. };
  80505. QuadraticMatrix.FromData = function (a, b, c, d) {
  80506. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80507. };
  80508. //returning an array to avoid garbage collection
  80509. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80510. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80511. };
  80512. return QuadraticMatrix;
  80513. }());
  80514. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80515. var Reference = /** @class */ (function () {
  80516. function Reference(vertexId, triangleId) {
  80517. this.vertexId = vertexId;
  80518. this.triangleId = triangleId;
  80519. }
  80520. return Reference;
  80521. }());
  80522. BABYLON.Reference = Reference;
  80523. /**
  80524. * An implementation of the Quadratic Error simplification algorithm.
  80525. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80526. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80527. * @author RaananW
  80528. */
  80529. var QuadraticErrorSimplification = /** @class */ (function () {
  80530. function QuadraticErrorSimplification(_mesh) {
  80531. this._mesh = _mesh;
  80532. this.syncIterations = 5000;
  80533. this.aggressiveness = 7;
  80534. this.decimationIterations = 100;
  80535. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80536. }
  80537. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80538. var _this = this;
  80539. this.initDecimatedMesh();
  80540. //iterating through the submeshes array, one after the other.
  80541. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80542. _this.initWithMesh(loop.index, function () {
  80543. _this.runDecimation(settings, loop.index, function () {
  80544. loop.executeNext();
  80545. });
  80546. }, settings.optimizeMesh);
  80547. }, function () {
  80548. setTimeout(function () {
  80549. successCallback(_this._reconstructedMesh);
  80550. }, 0);
  80551. });
  80552. };
  80553. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80554. var _this = this;
  80555. var targetCount = ~~(this.triangles.length * settings.quality);
  80556. var deletedTriangles = 0;
  80557. var triangleCount = this.triangles.length;
  80558. var iterationFunction = function (iteration, callback) {
  80559. setTimeout(function () {
  80560. if (iteration % 5 === 0) {
  80561. _this.updateMesh(iteration === 0);
  80562. }
  80563. for (var i = 0; i < _this.triangles.length; ++i) {
  80564. _this.triangles[i].isDirty = false;
  80565. }
  80566. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80567. var trianglesIterator = function (i) {
  80568. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80569. var t = _this.triangles[tIdx];
  80570. if (!t)
  80571. return;
  80572. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80573. return;
  80574. }
  80575. for (var j = 0; j < 3; ++j) {
  80576. if (t.error[j] < threshold) {
  80577. var deleted0 = [];
  80578. var deleted1 = [];
  80579. var v0 = t.vertices[j];
  80580. var v1 = t.vertices[(j + 1) % 3];
  80581. if (v0.isBorder || v1.isBorder)
  80582. continue;
  80583. var p = BABYLON.Vector3.Zero();
  80584. var n = BABYLON.Vector3.Zero();
  80585. var uv = BABYLON.Vector2.Zero();
  80586. var color = new BABYLON.Color4(0, 0, 0, 1);
  80587. _this.calculateError(v0, v1, p, n, uv, color);
  80588. var delTr = new Array();
  80589. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80590. continue;
  80591. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80592. continue;
  80593. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80594. continue;
  80595. var uniqueArray = new Array();
  80596. delTr.forEach(function (deletedT) {
  80597. if (uniqueArray.indexOf(deletedT) === -1) {
  80598. deletedT.deletePending = true;
  80599. uniqueArray.push(deletedT);
  80600. }
  80601. });
  80602. if (uniqueArray.length % 2 !== 0) {
  80603. continue;
  80604. }
  80605. v0.q = v1.q.add(v0.q);
  80606. v0.updatePosition(p);
  80607. var tStart = _this.references.length;
  80608. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80609. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80610. var tCount = _this.references.length - tStart;
  80611. if (tCount <= v0.triangleCount) {
  80612. if (tCount) {
  80613. for (var c = 0; c < tCount; c++) {
  80614. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80615. }
  80616. }
  80617. }
  80618. else {
  80619. v0.triangleStart = tStart;
  80620. }
  80621. v0.triangleCount = tCount;
  80622. break;
  80623. }
  80624. }
  80625. };
  80626. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80627. }, 0);
  80628. };
  80629. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80630. if (triangleCount - deletedTriangles <= targetCount)
  80631. loop.breakLoop();
  80632. else {
  80633. iterationFunction(loop.index, function () {
  80634. loop.executeNext();
  80635. });
  80636. }
  80637. }, function () {
  80638. setTimeout(function () {
  80639. //reconstruct this part of the mesh
  80640. _this.reconstructMesh(submeshIndex);
  80641. successCallback();
  80642. }, 0);
  80643. });
  80644. };
  80645. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80646. var _this = this;
  80647. this.vertices = [];
  80648. this.triangles = [];
  80649. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80650. var indices = this._mesh.getIndices();
  80651. var submesh = this._mesh.subMeshes[submeshIndex];
  80652. var findInVertices = function (positionToSearch) {
  80653. if (optimizeMesh) {
  80654. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80655. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80656. return _this.vertices[ii];
  80657. }
  80658. }
  80659. }
  80660. return null;
  80661. };
  80662. var vertexReferences = [];
  80663. var vertexInit = function (i) {
  80664. if (!positionData) {
  80665. return;
  80666. }
  80667. var offset = i + submesh.verticesStart;
  80668. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80669. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80670. vertex.originalOffsets.push(offset);
  80671. if (vertex.id === _this.vertices.length) {
  80672. _this.vertices.push(vertex);
  80673. }
  80674. vertexReferences.push(vertex.id);
  80675. };
  80676. //var totalVertices = mesh.getTotalVertices();
  80677. var totalVertices = submesh.verticesCount;
  80678. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80679. var indicesInit = function (i) {
  80680. if (!indices) {
  80681. return;
  80682. }
  80683. var offset = (submesh.indexStart / 3) + i;
  80684. var pos = (offset * 3);
  80685. var i0 = indices[pos + 0];
  80686. var i1 = indices[pos + 1];
  80687. var i2 = indices[pos + 2];
  80688. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80689. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80690. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80691. var triangle = new DecimationTriangle([v0, v1, v2]);
  80692. triangle.originalOffset = pos;
  80693. _this.triangles.push(triangle);
  80694. };
  80695. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80696. _this.init(callback);
  80697. });
  80698. });
  80699. };
  80700. QuadraticErrorSimplification.prototype.init = function (callback) {
  80701. var _this = this;
  80702. var triangleInit1 = function (i) {
  80703. var t = _this.triangles[i];
  80704. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80705. for (var j = 0; j < 3; j++) {
  80706. 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))));
  80707. }
  80708. };
  80709. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80710. var triangleInit2 = function (i) {
  80711. var t = _this.triangles[i];
  80712. for (var j = 0; j < 3; ++j) {
  80713. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80714. }
  80715. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80716. };
  80717. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80718. callback();
  80719. });
  80720. });
  80721. };
  80722. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80723. var newTriangles = [];
  80724. var i;
  80725. for (i = 0; i < this.vertices.length; ++i) {
  80726. this.vertices[i].triangleCount = 0;
  80727. }
  80728. var t;
  80729. var j;
  80730. for (i = 0; i < this.triangles.length; ++i) {
  80731. if (!this.triangles[i].deleted) {
  80732. t = this.triangles[i];
  80733. for (j = 0; j < 3; ++j) {
  80734. t.vertices[j].triangleCount = 1;
  80735. }
  80736. newTriangles.push(t);
  80737. }
  80738. }
  80739. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80740. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80741. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80742. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80743. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80744. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80745. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80746. var vertexCount = 0;
  80747. for (i = 0; i < this.vertices.length; ++i) {
  80748. var vertex = this.vertices[i];
  80749. vertex.id = vertexCount;
  80750. if (vertex.triangleCount) {
  80751. vertex.originalOffsets.forEach(function (originalOffset) {
  80752. if (!normalData) {
  80753. return;
  80754. }
  80755. newPositionData.push(vertex.position.x);
  80756. newPositionData.push(vertex.position.y);
  80757. newPositionData.push(vertex.position.z);
  80758. newNormalData.push(normalData[originalOffset * 3]);
  80759. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80760. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80761. if (uvs && uvs.length) {
  80762. newUVsData.push(uvs[(originalOffset * 2)]);
  80763. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80764. }
  80765. else if (colorsData && colorsData.length) {
  80766. newColorsData.push(colorsData[(originalOffset * 4)]);
  80767. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80768. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80769. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80770. }
  80771. ++vertexCount;
  80772. });
  80773. }
  80774. }
  80775. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80776. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80777. var submeshesArray = this._reconstructedMesh.subMeshes;
  80778. this._reconstructedMesh.subMeshes = [];
  80779. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80780. var originalIndices = this._mesh.getIndices();
  80781. for (i = 0; i < newTriangles.length; ++i) {
  80782. t = newTriangles[i]; //now get the new referencing point for each vertex
  80783. [0, 1, 2].forEach(function (idx) {
  80784. var id = originalIndices[t.originalOffset + idx];
  80785. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80786. if (offset < 0)
  80787. offset = 0;
  80788. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80789. });
  80790. }
  80791. //overwriting the old vertex buffers and indices.
  80792. this._reconstructedMesh.setIndices(newIndicesArray);
  80793. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80794. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80795. if (newUVsData.length > 0)
  80796. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80797. if (newColorsData.length > 0)
  80798. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80799. //create submesh
  80800. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80801. if (submeshIndex > 0) {
  80802. this._reconstructedMesh.subMeshes = [];
  80803. submeshesArray.forEach(function (submesh) {
  80804. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80805. });
  80806. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80807. }
  80808. };
  80809. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80810. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80811. this._reconstructedMesh.material = this._mesh.material;
  80812. this._reconstructedMesh.parent = this._mesh.parent;
  80813. this._reconstructedMesh.isVisible = false;
  80814. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80815. };
  80816. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80817. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80818. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80819. if (t.deleted)
  80820. continue;
  80821. var s = this.references[vertex1.triangleStart + i].vertexId;
  80822. var v1 = t.vertices[(s + 1) % 3];
  80823. var v2 = t.vertices[(s + 2) % 3];
  80824. if ((v1 === vertex2 || v2 === vertex2)) {
  80825. deletedArray[i] = true;
  80826. delTr.push(t);
  80827. continue;
  80828. }
  80829. var d1 = v1.position.subtract(point);
  80830. d1 = d1.normalize();
  80831. var d2 = v2.position.subtract(point);
  80832. d2 = d2.normalize();
  80833. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80834. return true;
  80835. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80836. deletedArray[i] = false;
  80837. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80838. return true;
  80839. }
  80840. return false;
  80841. };
  80842. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80843. var newDeleted = deletedTriangles;
  80844. for (var i = 0; i < vertex.triangleCount; ++i) {
  80845. var ref = this.references[vertex.triangleStart + i];
  80846. var t = this.triangles[ref.triangleId];
  80847. if (t.deleted)
  80848. continue;
  80849. if (deletedArray[i] && t.deletePending) {
  80850. t.deleted = true;
  80851. newDeleted++;
  80852. continue;
  80853. }
  80854. t.vertices[ref.vertexId] = origVertex;
  80855. t.isDirty = true;
  80856. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80857. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80858. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80859. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80860. this.references.push(ref);
  80861. }
  80862. return newDeleted;
  80863. };
  80864. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80865. for (var i = 0; i < this.vertices.length; ++i) {
  80866. var vCount = [];
  80867. var vId = [];
  80868. var v = this.vertices[i];
  80869. var j;
  80870. for (j = 0; j < v.triangleCount; ++j) {
  80871. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80872. for (var ii = 0; ii < 3; ii++) {
  80873. var ofs = 0;
  80874. var vv = triangle.vertices[ii];
  80875. while (ofs < vCount.length) {
  80876. if (vId[ofs] === vv.id)
  80877. break;
  80878. ++ofs;
  80879. }
  80880. if (ofs === vCount.length) {
  80881. vCount.push(1);
  80882. vId.push(vv.id);
  80883. }
  80884. else {
  80885. vCount[ofs]++;
  80886. }
  80887. }
  80888. }
  80889. for (j = 0; j < vCount.length; ++j) {
  80890. if (vCount[j] === 1) {
  80891. this.vertices[vId[j]].isBorder = true;
  80892. }
  80893. else {
  80894. this.vertices[vId[j]].isBorder = false;
  80895. }
  80896. }
  80897. }
  80898. };
  80899. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80900. if (identifyBorders === void 0) { identifyBorders = false; }
  80901. var i;
  80902. if (!identifyBorders) {
  80903. var newTrianglesVector = [];
  80904. for (i = 0; i < this.triangles.length; ++i) {
  80905. if (!this.triangles[i].deleted) {
  80906. newTrianglesVector.push(this.triangles[i]);
  80907. }
  80908. }
  80909. this.triangles = newTrianglesVector;
  80910. }
  80911. for (i = 0; i < this.vertices.length; ++i) {
  80912. this.vertices[i].triangleCount = 0;
  80913. this.vertices[i].triangleStart = 0;
  80914. }
  80915. var t;
  80916. var j;
  80917. var v;
  80918. for (i = 0; i < this.triangles.length; ++i) {
  80919. t = this.triangles[i];
  80920. for (j = 0; j < 3; ++j) {
  80921. v = t.vertices[j];
  80922. v.triangleCount++;
  80923. }
  80924. }
  80925. var tStart = 0;
  80926. for (i = 0; i < this.vertices.length; ++i) {
  80927. this.vertices[i].triangleStart = tStart;
  80928. tStart += this.vertices[i].triangleCount;
  80929. this.vertices[i].triangleCount = 0;
  80930. }
  80931. var newReferences = new Array(this.triangles.length * 3);
  80932. for (i = 0; i < this.triangles.length; ++i) {
  80933. t = this.triangles[i];
  80934. for (j = 0; j < 3; ++j) {
  80935. v = t.vertices[j];
  80936. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  80937. v.triangleCount++;
  80938. }
  80939. }
  80940. this.references = newReferences;
  80941. if (identifyBorders) {
  80942. this.identifyBorder();
  80943. }
  80944. };
  80945. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  80946. var x = point.x;
  80947. var y = point.y;
  80948. var z = point.z;
  80949. 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
  80950. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  80951. };
  80952. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  80953. var q = vertex1.q.add(vertex2.q);
  80954. var border = vertex1.isBorder && vertex2.isBorder;
  80955. var error = 0;
  80956. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  80957. if (qDet !== 0 && !border) {
  80958. if (!pointResult) {
  80959. pointResult = BABYLON.Vector3.Zero();
  80960. }
  80961. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  80962. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  80963. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  80964. error = this.vertexError(q, pointResult);
  80965. }
  80966. else {
  80967. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  80968. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  80969. var error1 = this.vertexError(q, vertex1.position);
  80970. var error2 = this.vertexError(q, vertex2.position);
  80971. var error3 = this.vertexError(q, p3);
  80972. error = Math.min(error1, error2, error3);
  80973. if (error === error1) {
  80974. if (pointResult) {
  80975. pointResult.copyFrom(vertex1.position);
  80976. }
  80977. }
  80978. else if (error === error2) {
  80979. if (pointResult) {
  80980. pointResult.copyFrom(vertex2.position);
  80981. }
  80982. }
  80983. else {
  80984. if (pointResult) {
  80985. pointResult.copyFrom(p3);
  80986. }
  80987. }
  80988. }
  80989. return error;
  80990. };
  80991. return QuadraticErrorSimplification;
  80992. }());
  80993. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  80994. })(BABYLON || (BABYLON = {}));
  80995. //# sourceMappingURL=babylon.meshSimplification.js.map
  80996. var BABYLON;
  80997. (function (BABYLON) {
  80998. var MeshLODLevel = /** @class */ (function () {
  80999. function MeshLODLevel(distance, mesh) {
  81000. this.distance = distance;
  81001. this.mesh = mesh;
  81002. }
  81003. return MeshLODLevel;
  81004. }());
  81005. BABYLON.MeshLODLevel = MeshLODLevel;
  81006. })(BABYLON || (BABYLON = {}));
  81007. //# sourceMappingURL=babylon.meshLODLevel.js.map
  81008. var BABYLON;
  81009. (function (BABYLON) {
  81010. /**
  81011. * Defines the root class used to create scene optimization to use with SceneOptimizer
  81012. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81013. */
  81014. var SceneOptimization = /** @class */ (function () {
  81015. /**
  81016. * Creates the SceneOptimization object
  81017. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81018. * @param desc defines the description associated with the optimization
  81019. */
  81020. function SceneOptimization(
  81021. /**
  81022. * Defines the priority of this optimization (0 by default which means first in the list)
  81023. */
  81024. priority) {
  81025. if (priority === void 0) { priority = 0; }
  81026. this.priority = priority;
  81027. }
  81028. /**
  81029. * Gets a string describing the action executed by the current optimization
  81030. * @returns description string
  81031. */
  81032. SceneOptimization.prototype.getDescription = function () {
  81033. return "";
  81034. };
  81035. /**
  81036. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81037. * @param scene defines the current scene where to apply this optimization
  81038. * @param optimizer defines the current optimizer
  81039. * @returns true if everything that can be done was applied
  81040. */
  81041. SceneOptimization.prototype.apply = function (scene, optimizer) {
  81042. return true;
  81043. };
  81044. ;
  81045. return SceneOptimization;
  81046. }());
  81047. BABYLON.SceneOptimization = SceneOptimization;
  81048. /**
  81049. * Defines an optimization used to reduce the size of render target textures
  81050. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81051. */
  81052. var TextureOptimization = /** @class */ (function (_super) {
  81053. __extends(TextureOptimization, _super);
  81054. /**
  81055. * Creates the TextureOptimization object
  81056. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81057. * @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
  81058. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81059. */
  81060. function TextureOptimization(
  81061. /**
  81062. * Defines the priority of this optimization (0 by default which means first in the list)
  81063. */
  81064. priority,
  81065. /**
  81066. * 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
  81067. */
  81068. maximumSize,
  81069. /**
  81070. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81071. */
  81072. step) {
  81073. if (priority === void 0) { priority = 0; }
  81074. if (maximumSize === void 0) { maximumSize = 1024; }
  81075. if (step === void 0) { step = 0.5; }
  81076. var _this = _super.call(this, priority) || this;
  81077. _this.priority = priority;
  81078. _this.maximumSize = maximumSize;
  81079. _this.step = step;
  81080. return _this;
  81081. }
  81082. /**
  81083. * Gets a string describing the action executed by the current optimization
  81084. * @returns description string
  81085. */
  81086. TextureOptimization.prototype.getDescription = function () {
  81087. return "Reducing render target texture size to " + this.maximumSize;
  81088. };
  81089. /**
  81090. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81091. * @param scene defines the current scene where to apply this optimization
  81092. * @param optimizer defines the current optimizer
  81093. * @returns true if everything that can be done was applied
  81094. */
  81095. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81096. var allDone = true;
  81097. for (var index = 0; index < scene.textures.length; index++) {
  81098. var texture = scene.textures[index];
  81099. if (!texture.canRescale || texture.getContext) {
  81100. continue;
  81101. }
  81102. var currentSize = texture.getSize();
  81103. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81104. if (maxDimension > this.maximumSize) {
  81105. texture.scale(this.step);
  81106. allDone = false;
  81107. }
  81108. }
  81109. return allDone;
  81110. };
  81111. return TextureOptimization;
  81112. }(SceneOptimization));
  81113. BABYLON.TextureOptimization = TextureOptimization;
  81114. /**
  81115. * Defines an optimization used to increase or decrease the rendering resolution
  81116. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81117. */
  81118. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81119. __extends(HardwareScalingOptimization, _super);
  81120. /**
  81121. * Creates the HardwareScalingOptimization object
  81122. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81123. * @param maximumScale defines the maximum scale to use (2 by default)
  81124. * @param step defines the step to use between two passes (0.5 by default)
  81125. */
  81126. function HardwareScalingOptimization(
  81127. /**
  81128. * Defines the priority of this optimization (0 by default which means first in the list)
  81129. */
  81130. priority,
  81131. /**
  81132. * Defines the maximum scale to use (2 by default)
  81133. */
  81134. maximumScale,
  81135. /**
  81136. * Defines the step to use between two passes (0.5 by default)
  81137. */
  81138. step) {
  81139. if (priority === void 0) { priority = 0; }
  81140. if (maximumScale === void 0) { maximumScale = 2; }
  81141. if (step === void 0) { step = 0.25; }
  81142. var _this = _super.call(this, priority) || this;
  81143. _this.priority = priority;
  81144. _this.maximumScale = maximumScale;
  81145. _this.step = step;
  81146. _this._currentScale = -1;
  81147. _this._directionOffset = 1;
  81148. return _this;
  81149. }
  81150. /**
  81151. * Gets a string describing the action executed by the current optimization
  81152. * @return description string
  81153. */
  81154. HardwareScalingOptimization.prototype.getDescription = function () {
  81155. return "Setting hardware scaling level to " + this._currentScale;
  81156. };
  81157. /**
  81158. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81159. * @param scene defines the current scene where to apply this optimization
  81160. * @param optimizer defines the current optimizer
  81161. * @returns true if everything that can be done was applied
  81162. */
  81163. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81164. if (this._currentScale === -1) {
  81165. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81166. if (this._currentScale > this.maximumScale) {
  81167. this._directionOffset = -1;
  81168. }
  81169. }
  81170. this._currentScale += this._directionOffset * this.step;
  81171. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81172. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81173. };
  81174. ;
  81175. return HardwareScalingOptimization;
  81176. }(SceneOptimization));
  81177. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81178. /**
  81179. * Defines an optimization used to remove shadows
  81180. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81181. */
  81182. var ShadowsOptimization = /** @class */ (function (_super) {
  81183. __extends(ShadowsOptimization, _super);
  81184. function ShadowsOptimization() {
  81185. return _super !== null && _super.apply(this, arguments) || this;
  81186. }
  81187. /**
  81188. * Gets a string describing the action executed by the current optimization
  81189. * @return description string
  81190. */
  81191. ShadowsOptimization.prototype.getDescription = function () {
  81192. return "Turning shadows on/off";
  81193. };
  81194. /**
  81195. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81196. * @param scene defines the current scene where to apply this optimization
  81197. * @param optimizer defines the current optimizer
  81198. * @returns true if everything that can be done was applied
  81199. */
  81200. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81201. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81202. return true;
  81203. };
  81204. ;
  81205. return ShadowsOptimization;
  81206. }(SceneOptimization));
  81207. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81208. /**
  81209. * Defines an optimization used to turn post-processes off
  81210. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81211. */
  81212. var PostProcessesOptimization = /** @class */ (function (_super) {
  81213. __extends(PostProcessesOptimization, _super);
  81214. function PostProcessesOptimization() {
  81215. return _super !== null && _super.apply(this, arguments) || this;
  81216. }
  81217. /**
  81218. * Gets a string describing the action executed by the current optimization
  81219. * @return description string
  81220. */
  81221. PostProcessesOptimization.prototype.getDescription = function () {
  81222. return "Turning post-processes on/off";
  81223. };
  81224. /**
  81225. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81226. * @param scene defines the current scene where to apply this optimization
  81227. * @param optimizer defines the current optimizer
  81228. * @returns true if everything that can be done was applied
  81229. */
  81230. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81231. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81232. return true;
  81233. };
  81234. ;
  81235. return PostProcessesOptimization;
  81236. }(SceneOptimization));
  81237. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81238. /**
  81239. * Defines an optimization used to turn lens flares off
  81240. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81241. */
  81242. var LensFlaresOptimization = /** @class */ (function (_super) {
  81243. __extends(LensFlaresOptimization, _super);
  81244. function LensFlaresOptimization() {
  81245. return _super !== null && _super.apply(this, arguments) || this;
  81246. }
  81247. /**
  81248. * Gets a string describing the action executed by the current optimization
  81249. * @return description string
  81250. */
  81251. LensFlaresOptimization.prototype.getDescription = function () {
  81252. return "Turning lens flares on/off";
  81253. };
  81254. /**
  81255. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81256. * @param scene defines the current scene where to apply this optimization
  81257. * @param optimizer defines the current optimizer
  81258. * @returns true if everything that can be done was applied
  81259. */
  81260. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81261. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81262. return true;
  81263. };
  81264. ;
  81265. return LensFlaresOptimization;
  81266. }(SceneOptimization));
  81267. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81268. /**
  81269. * Defines an optimization based on user defined callback.
  81270. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81271. */
  81272. var CustomOptimization = /** @class */ (function (_super) {
  81273. __extends(CustomOptimization, _super);
  81274. function CustomOptimization() {
  81275. return _super !== null && _super.apply(this, arguments) || this;
  81276. }
  81277. /**
  81278. * Gets a string describing the action executed by the current optimization
  81279. * @returns description string
  81280. */
  81281. CustomOptimization.prototype.getDescription = function () {
  81282. if (this.onGetDescription) {
  81283. return this.onGetDescription();
  81284. }
  81285. return "Running user defined callback";
  81286. };
  81287. /**
  81288. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81289. * @param scene defines the current scene where to apply this optimization
  81290. * @param optimizer defines the current optimizer
  81291. * @returns true if everything that can be done was applied
  81292. */
  81293. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81294. if (this.onApply) {
  81295. return this.onApply(scene, optimizer);
  81296. }
  81297. return true;
  81298. };
  81299. ;
  81300. return CustomOptimization;
  81301. }(SceneOptimization));
  81302. BABYLON.CustomOptimization = CustomOptimization;
  81303. /**
  81304. * Defines an optimization used to turn particles off
  81305. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81306. */
  81307. var ParticlesOptimization = /** @class */ (function (_super) {
  81308. __extends(ParticlesOptimization, _super);
  81309. function ParticlesOptimization() {
  81310. return _super !== null && _super.apply(this, arguments) || this;
  81311. }
  81312. /**
  81313. * Gets a string describing the action executed by the current optimization
  81314. * @return description string
  81315. */
  81316. ParticlesOptimization.prototype.getDescription = function () {
  81317. return "Turning particles on/off";
  81318. };
  81319. /**
  81320. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81321. * @param scene defines the current scene where to apply this optimization
  81322. * @param optimizer defines the current optimizer
  81323. * @returns true if everything that can be done was applied
  81324. */
  81325. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81326. scene.particlesEnabled = optimizer.isInImprovementMode;
  81327. return true;
  81328. };
  81329. ;
  81330. return ParticlesOptimization;
  81331. }(SceneOptimization));
  81332. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81333. /**
  81334. * Defines an optimization used to turn render targets off
  81335. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81336. */
  81337. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81338. __extends(RenderTargetsOptimization, _super);
  81339. function RenderTargetsOptimization() {
  81340. return _super !== null && _super.apply(this, arguments) || this;
  81341. }
  81342. /**
  81343. * Gets a string describing the action executed by the current optimization
  81344. * @return description string
  81345. */
  81346. RenderTargetsOptimization.prototype.getDescription = function () {
  81347. return "Turning render targets off";
  81348. };
  81349. /**
  81350. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81351. * @param scene defines the current scene where to apply this optimization
  81352. * @param optimizer defines the current optimizer
  81353. * @returns true if everything that can be done was applied
  81354. */
  81355. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81356. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81357. return true;
  81358. };
  81359. ;
  81360. return RenderTargetsOptimization;
  81361. }(SceneOptimization));
  81362. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81363. /**
  81364. * Defines an optimization used to merge meshes with compatible materials
  81365. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81366. */
  81367. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81368. __extends(MergeMeshesOptimization, _super);
  81369. function MergeMeshesOptimization() {
  81370. var _this = _super !== null && _super.apply(this, arguments) || this;
  81371. _this._canBeMerged = function (abstractMesh) {
  81372. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81373. return false;
  81374. }
  81375. var mesh = abstractMesh;
  81376. if (!mesh.isVisible || !mesh.isEnabled()) {
  81377. return false;
  81378. }
  81379. if (mesh.instances.length > 0) {
  81380. return false;
  81381. }
  81382. if (mesh.skeleton || mesh.hasLODLevels) {
  81383. return false;
  81384. }
  81385. if (mesh.parent) {
  81386. return false;
  81387. }
  81388. return true;
  81389. };
  81390. return _this;
  81391. }
  81392. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81393. /**
  81394. * Gets or sets a boolean which defines if optimization octree has to be updated
  81395. */
  81396. get: function () {
  81397. return MergeMeshesOptimization._UpdateSelectionTree;
  81398. },
  81399. /**
  81400. * Gets or sets a boolean which defines if optimization octree has to be updated
  81401. */
  81402. set: function (value) {
  81403. MergeMeshesOptimization._UpdateSelectionTree = value;
  81404. },
  81405. enumerable: true,
  81406. configurable: true
  81407. });
  81408. /**
  81409. * Gets a string describing the action executed by the current optimization
  81410. * @return description string
  81411. */
  81412. MergeMeshesOptimization.prototype.getDescription = function () {
  81413. return "Merging similar meshes together";
  81414. };
  81415. /**
  81416. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81417. * @param scene defines the current scene where to apply this optimization
  81418. * @param optimizer defines the current optimizer
  81419. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81420. * @returns true if everything that can be done was applied
  81421. */
  81422. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81423. var globalPool = scene.meshes.slice(0);
  81424. var globalLength = globalPool.length;
  81425. for (var index = 0; index < globalLength; index++) {
  81426. var currentPool = new Array();
  81427. var current = globalPool[index];
  81428. // Checks
  81429. if (!this._canBeMerged(current)) {
  81430. continue;
  81431. }
  81432. currentPool.push(current);
  81433. // Find compatible meshes
  81434. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81435. var otherMesh = globalPool[subIndex];
  81436. if (!this._canBeMerged(otherMesh)) {
  81437. continue;
  81438. }
  81439. if (otherMesh.material !== current.material) {
  81440. continue;
  81441. }
  81442. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81443. continue;
  81444. }
  81445. currentPool.push(otherMesh);
  81446. globalLength--;
  81447. globalPool.splice(subIndex, 1);
  81448. subIndex--;
  81449. }
  81450. if (currentPool.length < 2) {
  81451. continue;
  81452. }
  81453. // Merge meshes
  81454. BABYLON.Mesh.MergeMeshes(currentPool);
  81455. }
  81456. if (updateSelectionTree != undefined) {
  81457. if (updateSelectionTree) {
  81458. scene.createOrUpdateSelectionOctree();
  81459. }
  81460. }
  81461. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81462. scene.createOrUpdateSelectionOctree();
  81463. }
  81464. return true;
  81465. };
  81466. ;
  81467. MergeMeshesOptimization._UpdateSelectionTree = false;
  81468. return MergeMeshesOptimization;
  81469. }(SceneOptimization));
  81470. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81471. /**
  81472. * Defines a list of options used by SceneOptimizer
  81473. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81474. */
  81475. var SceneOptimizerOptions = /** @class */ (function () {
  81476. /**
  81477. * Creates a new list of options used by SceneOptimizer
  81478. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81479. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81480. */
  81481. function SceneOptimizerOptions(
  81482. /**
  81483. * Defines the target frame rate to reach (60 by default)
  81484. */
  81485. targetFrameRate,
  81486. /**
  81487. * Defines the interval between two checkes (2000ms by default)
  81488. */
  81489. trackerDuration) {
  81490. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81491. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81492. this.targetFrameRate = targetFrameRate;
  81493. this.trackerDuration = trackerDuration;
  81494. /**
  81495. * Gets the list of optimizations to apply
  81496. */
  81497. this.optimizations = new Array();
  81498. }
  81499. /**
  81500. * Add a new optimization
  81501. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81502. * @returns the current SceneOptimizerOptions
  81503. */
  81504. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81505. this.optimizations.push(optimization);
  81506. return this;
  81507. };
  81508. /**
  81509. * Add a new custom optimization
  81510. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81511. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81512. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81513. * @returns the current SceneOptimizerOptions
  81514. */
  81515. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81516. if (priority === void 0) { priority = 0; }
  81517. var optimization = new CustomOptimization(priority);
  81518. optimization.onApply = onApply;
  81519. optimization.onGetDescription = onGetDescription;
  81520. this.optimizations.push(optimization);
  81521. return this;
  81522. };
  81523. /**
  81524. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81525. * @param targetFrameRate defines the target frame rate (60 by default)
  81526. * @returns a SceneOptimizerOptions object
  81527. */
  81528. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81529. var result = new SceneOptimizerOptions(targetFrameRate);
  81530. var priority = 0;
  81531. result.addOptimization(new MergeMeshesOptimization(priority));
  81532. result.addOptimization(new ShadowsOptimization(priority));
  81533. result.addOptimization(new LensFlaresOptimization(priority));
  81534. // Next priority
  81535. priority++;
  81536. result.addOptimization(new PostProcessesOptimization(priority));
  81537. result.addOptimization(new ParticlesOptimization(priority));
  81538. // Next priority
  81539. priority++;
  81540. result.addOptimization(new TextureOptimization(priority, 1024));
  81541. return result;
  81542. };
  81543. /**
  81544. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81545. * @param targetFrameRate defines the target frame rate (60 by default)
  81546. * @returns a SceneOptimizerOptions object
  81547. */
  81548. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81549. var result = new SceneOptimizerOptions(targetFrameRate);
  81550. var priority = 0;
  81551. result.addOptimization(new MergeMeshesOptimization(priority));
  81552. result.addOptimization(new ShadowsOptimization(priority));
  81553. result.addOptimization(new LensFlaresOptimization(priority));
  81554. // Next priority
  81555. priority++;
  81556. result.addOptimization(new PostProcessesOptimization(priority));
  81557. result.addOptimization(new ParticlesOptimization(priority));
  81558. // Next priority
  81559. priority++;
  81560. result.addOptimization(new TextureOptimization(priority, 512));
  81561. // Next priority
  81562. priority++;
  81563. result.addOptimization(new RenderTargetsOptimization(priority));
  81564. // Next priority
  81565. priority++;
  81566. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81567. return result;
  81568. };
  81569. /**
  81570. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81571. * @param targetFrameRate defines the target frame rate (60 by default)
  81572. * @returns a SceneOptimizerOptions object
  81573. */
  81574. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81575. var result = new SceneOptimizerOptions(targetFrameRate);
  81576. var priority = 0;
  81577. result.addOptimization(new MergeMeshesOptimization(priority));
  81578. result.addOptimization(new ShadowsOptimization(priority));
  81579. result.addOptimization(new LensFlaresOptimization(priority));
  81580. // Next priority
  81581. priority++;
  81582. result.addOptimization(new PostProcessesOptimization(priority));
  81583. result.addOptimization(new ParticlesOptimization(priority));
  81584. // Next priority
  81585. priority++;
  81586. result.addOptimization(new TextureOptimization(priority, 256));
  81587. // Next priority
  81588. priority++;
  81589. result.addOptimization(new RenderTargetsOptimization(priority));
  81590. // Next priority
  81591. priority++;
  81592. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81593. return result;
  81594. };
  81595. return SceneOptimizerOptions;
  81596. }());
  81597. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81598. /**
  81599. * Class used to run optimizations in order to reach a target frame rate
  81600. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81601. */
  81602. var SceneOptimizer = /** @class */ (function () {
  81603. /**
  81604. * Creates a new SceneOptimizer
  81605. * @param scene defines the scene to work on
  81606. * @param options defines the options to use with the SceneOptimizer
  81607. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81608. * @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)
  81609. */
  81610. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81611. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81612. if (improvementMode === void 0) { improvementMode = false; }
  81613. var _this = this;
  81614. this._isRunning = false;
  81615. this._currentPriorityLevel = 0;
  81616. this._targetFrameRate = 60;
  81617. this._trackerDuration = 2000;
  81618. this._currentFrameRate = 0;
  81619. this._improvementMode = false;
  81620. /**
  81621. * Defines an observable called when the optimizer reaches the target frame rate
  81622. */
  81623. this.onSuccessObservable = new BABYLON.Observable();
  81624. /**
  81625. * Defines an observable called when the optimizer enables an optimization
  81626. */
  81627. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81628. /**
  81629. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81630. */
  81631. this.onFailureObservable = new BABYLON.Observable();
  81632. if (!options) {
  81633. this._options = new SceneOptimizerOptions();
  81634. }
  81635. else {
  81636. this._options = options;
  81637. }
  81638. if (this._options.targetFrameRate) {
  81639. this._targetFrameRate = this._options.targetFrameRate;
  81640. }
  81641. if (this._options.trackerDuration) {
  81642. this._trackerDuration = this._options.trackerDuration;
  81643. }
  81644. if (autoGeneratePriorities) {
  81645. var priority = 0;
  81646. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81647. var optim = _a[_i];
  81648. optim.priority = priority++;
  81649. }
  81650. }
  81651. this._improvementMode = improvementMode;
  81652. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81653. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81654. _this._sceneDisposeObserver = null;
  81655. _this.dispose();
  81656. });
  81657. }
  81658. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81659. /**
  81660. * Gets a boolean indicating if the optimizer is in improvement mode
  81661. */
  81662. get: function () {
  81663. return this._improvementMode;
  81664. },
  81665. enumerable: true,
  81666. configurable: true
  81667. });
  81668. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81669. /**
  81670. * Gets the current priority level (0 at start)
  81671. */
  81672. get: function () {
  81673. return this._currentPriorityLevel;
  81674. },
  81675. enumerable: true,
  81676. configurable: true
  81677. });
  81678. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81679. /**
  81680. * Gets the current frame rate checked by the SceneOptimizer
  81681. */
  81682. get: function () {
  81683. return this._currentFrameRate;
  81684. },
  81685. enumerable: true,
  81686. configurable: true
  81687. });
  81688. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81689. /**
  81690. * Gets or sets the current target frame rate (60 by default)
  81691. */
  81692. get: function () {
  81693. return this._targetFrameRate;
  81694. },
  81695. /**
  81696. * Gets or sets the current target frame rate (60 by default)
  81697. */
  81698. set: function (value) {
  81699. this._targetFrameRate = value;
  81700. },
  81701. enumerable: true,
  81702. configurable: true
  81703. });
  81704. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81705. /**
  81706. * Gets or sets the current interval between two checks (every 2000ms by default)
  81707. */
  81708. get: function () {
  81709. return this._trackerDuration;
  81710. },
  81711. /**
  81712. * Gets or sets the current interval between two checks (every 2000ms by default)
  81713. */
  81714. set: function (value) {
  81715. this._trackerDuration = value;
  81716. },
  81717. enumerable: true,
  81718. configurable: true
  81719. });
  81720. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81721. /**
  81722. * Gets the list of active optimizations
  81723. */
  81724. get: function () {
  81725. return this._options.optimizations;
  81726. },
  81727. enumerable: true,
  81728. configurable: true
  81729. });
  81730. /**
  81731. * Stops the current optimizer
  81732. */
  81733. SceneOptimizer.prototype.stop = function () {
  81734. this._isRunning = false;
  81735. };
  81736. /**
  81737. * Reset the optimizer to initial step (current priority level = 0)
  81738. */
  81739. SceneOptimizer.prototype.reset = function () {
  81740. this._currentPriorityLevel = 0;
  81741. };
  81742. /**
  81743. * Start the optimizer. By default it will try to reach a specific framerate
  81744. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81745. */
  81746. SceneOptimizer.prototype.start = function () {
  81747. var _this = this;
  81748. if (this._isRunning) {
  81749. return;
  81750. }
  81751. this._isRunning = true;
  81752. // Let's wait for the scene to be ready before running our check
  81753. this._scene.executeWhenReady(function () {
  81754. setTimeout(function () {
  81755. _this._checkCurrentState();
  81756. }, _this._trackerDuration);
  81757. });
  81758. };
  81759. SceneOptimizer.prototype._checkCurrentState = function () {
  81760. var _this = this;
  81761. if (!this._isRunning) {
  81762. return;
  81763. }
  81764. var scene = this._scene;
  81765. var options = this._options;
  81766. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81767. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81768. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81769. this._isRunning = false;
  81770. this.onSuccessObservable.notifyObservers(this);
  81771. return;
  81772. }
  81773. // Apply current level of optimizations
  81774. var allDone = true;
  81775. var noOptimizationApplied = true;
  81776. for (var index = 0; index < options.optimizations.length; index++) {
  81777. var optimization = options.optimizations[index];
  81778. if (optimization.priority === this._currentPriorityLevel) {
  81779. noOptimizationApplied = false;
  81780. allDone = allDone && optimization.apply(scene, this);
  81781. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81782. }
  81783. }
  81784. // If no optimization was applied, this is a failure :(
  81785. if (noOptimizationApplied) {
  81786. this._isRunning = false;
  81787. this.onFailureObservable.notifyObservers(this);
  81788. return;
  81789. }
  81790. // If all optimizations were done, move to next level
  81791. if (allDone) {
  81792. this._currentPriorityLevel++;
  81793. }
  81794. // Let's the system running for a specific amount of time before checking FPS
  81795. scene.executeWhenReady(function () {
  81796. setTimeout(function () {
  81797. _this._checkCurrentState();
  81798. }, _this._trackerDuration);
  81799. });
  81800. };
  81801. /**
  81802. * Release all resources
  81803. */
  81804. SceneOptimizer.prototype.dispose = function () {
  81805. this.stop();
  81806. this.onSuccessObservable.clear();
  81807. this.onFailureObservable.clear();
  81808. this.onNewOptimizationAppliedObservable.clear();
  81809. if (this._sceneDisposeObserver) {
  81810. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81811. }
  81812. };
  81813. /**
  81814. * Helper function to create a SceneOptimizer with one single line of code
  81815. * @param scene defines the scene to work on
  81816. * @param options defines the options to use with the SceneOptimizer
  81817. * @param onSuccess defines a callback to call on success
  81818. * @param onFailure defines a callback to call on failure
  81819. * @returns the new SceneOptimizer object
  81820. */
  81821. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81822. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81823. if (onSuccess) {
  81824. optimizer.onSuccessObservable.add(function () {
  81825. onSuccess();
  81826. });
  81827. }
  81828. if (onFailure) {
  81829. optimizer.onFailureObservable.add(function () {
  81830. onFailure();
  81831. });
  81832. }
  81833. optimizer.start();
  81834. return optimizer;
  81835. };
  81836. return SceneOptimizer;
  81837. }());
  81838. BABYLON.SceneOptimizer = SceneOptimizer;
  81839. })(BABYLON || (BABYLON = {}));
  81840. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81841. var BABYLON;
  81842. (function (BABYLON) {
  81843. var OutlineRenderer = /** @class */ (function () {
  81844. function OutlineRenderer(scene) {
  81845. this.zOffset = 1;
  81846. this._scene = scene;
  81847. }
  81848. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81849. var _this = this;
  81850. if (useOverlay === void 0) { useOverlay = false; }
  81851. var scene = this._scene;
  81852. var engine = this._scene.getEngine();
  81853. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81854. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81855. return;
  81856. }
  81857. var mesh = subMesh.getRenderingMesh();
  81858. var material = subMesh.getMaterial();
  81859. if (!material || !scene.activeCamera) {
  81860. return;
  81861. }
  81862. engine.enableEffect(this._effect);
  81863. // Logarithmic depth
  81864. if (material.useLogarithmicDepth) {
  81865. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81866. }
  81867. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81868. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81869. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81870. // Bones
  81871. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81872. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81873. }
  81874. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81875. // Alpha test
  81876. if (material && material.needAlphaTesting()) {
  81877. var alphaTexture = material.getAlphaTestTexture();
  81878. if (alphaTexture) {
  81879. this._effect.setTexture("diffuseSampler", alphaTexture);
  81880. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81881. }
  81882. }
  81883. engine.setZOffset(-this.zOffset);
  81884. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81885. engine.setZOffset(0);
  81886. };
  81887. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81888. var defines = [];
  81889. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81890. var mesh = subMesh.getMesh();
  81891. var material = subMesh.getMaterial();
  81892. if (material) {
  81893. // Alpha test
  81894. if (material.needAlphaTesting()) {
  81895. defines.push("#define ALPHATEST");
  81896. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81897. attribs.push(BABYLON.VertexBuffer.UVKind);
  81898. defines.push("#define UV1");
  81899. }
  81900. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81901. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81902. defines.push("#define UV2");
  81903. }
  81904. }
  81905. //Logarithmic depth
  81906. if (material.useLogarithmicDepth) {
  81907. defines.push("#define LOGARITHMICDEPTH");
  81908. }
  81909. }
  81910. // Bones
  81911. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81912. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81913. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81914. if (mesh.numBoneInfluencers > 4) {
  81915. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81916. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81917. }
  81918. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81919. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81920. }
  81921. else {
  81922. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81923. }
  81924. // Instances
  81925. if (useInstances) {
  81926. defines.push("#define INSTANCES");
  81927. attribs.push("world0");
  81928. attribs.push("world1");
  81929. attribs.push("world2");
  81930. attribs.push("world3");
  81931. }
  81932. // Get correct effect
  81933. var join = defines.join("\n");
  81934. if (this._cachedDefines !== join) {
  81935. this._cachedDefines = join;
  81936. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  81937. }
  81938. return this._effect.isReady();
  81939. };
  81940. return OutlineRenderer;
  81941. }());
  81942. BABYLON.OutlineRenderer = OutlineRenderer;
  81943. })(BABYLON || (BABYLON = {}));
  81944. //# sourceMappingURL=babylon.outlineRenderer.js.map
  81945. var BABYLON;
  81946. (function (BABYLON) {
  81947. var FaceAdjacencies = /** @class */ (function () {
  81948. function FaceAdjacencies() {
  81949. this.edges = new Array();
  81950. this.edgesConnectedCount = 0;
  81951. }
  81952. return FaceAdjacencies;
  81953. }());
  81954. var EdgesRenderer = /** @class */ (function () {
  81955. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  81956. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  81957. if (epsilon === void 0) { epsilon = 0.95; }
  81958. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  81959. this.edgesWidthScalerForOrthographic = 1000.0;
  81960. this.edgesWidthScalerForPerspective = 50.0;
  81961. this._linesPositions = new Array();
  81962. this._linesNormals = new Array();
  81963. this._linesIndices = new Array();
  81964. this._buffers = {};
  81965. this._checkVerticesInsteadOfIndices = false;
  81966. this._source = source;
  81967. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  81968. this._epsilon = epsilon;
  81969. this._prepareRessources();
  81970. this._generateEdgesLines();
  81971. }
  81972. EdgesRenderer.prototype._prepareRessources = function () {
  81973. if (this._lineShader) {
  81974. return;
  81975. }
  81976. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  81977. attributes: ["position", "normal"],
  81978. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  81979. });
  81980. this._lineShader.disableDepthWrite = true;
  81981. this._lineShader.backFaceCulling = false;
  81982. };
  81983. EdgesRenderer.prototype._rebuild = function () {
  81984. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81985. if (buffer) {
  81986. buffer._rebuild();
  81987. }
  81988. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81989. if (buffer) {
  81990. buffer._rebuild();
  81991. }
  81992. var scene = this._source.getScene();
  81993. var engine = scene.getEngine();
  81994. this._ib = engine.createIndexBuffer(this._linesIndices);
  81995. };
  81996. EdgesRenderer.prototype.dispose = function () {
  81997. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81998. if (buffer) {
  81999. buffer.dispose();
  82000. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  82001. }
  82002. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82003. if (buffer) {
  82004. buffer.dispose();
  82005. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  82006. }
  82007. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  82008. this._lineShader.dispose();
  82009. };
  82010. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  82011. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  82012. return 0;
  82013. }
  82014. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  82015. return 1;
  82016. }
  82017. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  82018. return 2;
  82019. }
  82020. return -1;
  82021. };
  82022. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  82023. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  82024. return 0;
  82025. }
  82026. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  82027. return 1;
  82028. }
  82029. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  82030. return 2;
  82031. }
  82032. return -1;
  82033. };
  82034. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  82035. var needToCreateLine;
  82036. if (edge === undefined) {
  82037. needToCreateLine = true;
  82038. }
  82039. else {
  82040. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  82041. needToCreateLine = dotProduct < this._epsilon;
  82042. }
  82043. if (needToCreateLine) {
  82044. var offset = this._linesPositions.length / 3;
  82045. var normal = p0.subtract(p1);
  82046. normal.normalize();
  82047. // Positions
  82048. this._linesPositions.push(p0.x);
  82049. this._linesPositions.push(p0.y);
  82050. this._linesPositions.push(p0.z);
  82051. this._linesPositions.push(p0.x);
  82052. this._linesPositions.push(p0.y);
  82053. this._linesPositions.push(p0.z);
  82054. this._linesPositions.push(p1.x);
  82055. this._linesPositions.push(p1.y);
  82056. this._linesPositions.push(p1.z);
  82057. this._linesPositions.push(p1.x);
  82058. this._linesPositions.push(p1.y);
  82059. this._linesPositions.push(p1.z);
  82060. // Normals
  82061. this._linesNormals.push(p1.x);
  82062. this._linesNormals.push(p1.y);
  82063. this._linesNormals.push(p1.z);
  82064. this._linesNormals.push(-1);
  82065. this._linesNormals.push(p1.x);
  82066. this._linesNormals.push(p1.y);
  82067. this._linesNormals.push(p1.z);
  82068. this._linesNormals.push(1);
  82069. this._linesNormals.push(p0.x);
  82070. this._linesNormals.push(p0.y);
  82071. this._linesNormals.push(p0.z);
  82072. this._linesNormals.push(-1);
  82073. this._linesNormals.push(p0.x);
  82074. this._linesNormals.push(p0.y);
  82075. this._linesNormals.push(p0.z);
  82076. this._linesNormals.push(1);
  82077. // Indices
  82078. this._linesIndices.push(offset);
  82079. this._linesIndices.push(offset + 1);
  82080. this._linesIndices.push(offset + 2);
  82081. this._linesIndices.push(offset);
  82082. this._linesIndices.push(offset + 2);
  82083. this._linesIndices.push(offset + 3);
  82084. }
  82085. };
  82086. EdgesRenderer.prototype._generateEdgesLines = function () {
  82087. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82088. var indices = this._source.getIndices();
  82089. if (!indices || !positions) {
  82090. return;
  82091. }
  82092. // First let's find adjacencies
  82093. var adjacencies = new Array();
  82094. var faceNormals = new Array();
  82095. var index;
  82096. var faceAdjacencies;
  82097. // Prepare faces
  82098. for (index = 0; index < indices.length; index += 3) {
  82099. faceAdjacencies = new FaceAdjacencies();
  82100. var p0Index = indices[index];
  82101. var p1Index = indices[index + 1];
  82102. var p2Index = indices[index + 2];
  82103. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82104. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82105. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82106. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82107. faceNormal.normalize();
  82108. faceNormals.push(faceNormal);
  82109. adjacencies.push(faceAdjacencies);
  82110. }
  82111. // Scan
  82112. for (index = 0; index < adjacencies.length; index++) {
  82113. faceAdjacencies = adjacencies[index];
  82114. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82115. var otherFaceAdjacencies = adjacencies[otherIndex];
  82116. if (faceAdjacencies.edgesConnectedCount === 3) {
  82117. break;
  82118. }
  82119. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82120. continue;
  82121. }
  82122. var otherP0 = indices[otherIndex * 3];
  82123. var otherP1 = indices[otherIndex * 3 + 1];
  82124. var otherP2 = indices[otherIndex * 3 + 2];
  82125. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82126. var otherEdgeIndex = 0;
  82127. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82128. continue;
  82129. }
  82130. switch (edgeIndex) {
  82131. case 0:
  82132. if (this._checkVerticesInsteadOfIndices) {
  82133. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82134. }
  82135. else {
  82136. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82137. }
  82138. break;
  82139. case 1:
  82140. if (this._checkVerticesInsteadOfIndices) {
  82141. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82142. }
  82143. else {
  82144. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82145. }
  82146. break;
  82147. case 2:
  82148. if (this._checkVerticesInsteadOfIndices) {
  82149. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82150. }
  82151. else {
  82152. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82153. }
  82154. break;
  82155. }
  82156. if (otherEdgeIndex === -1) {
  82157. continue;
  82158. }
  82159. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82160. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82161. faceAdjacencies.edgesConnectedCount++;
  82162. otherFaceAdjacencies.edgesConnectedCount++;
  82163. if (faceAdjacencies.edgesConnectedCount === 3) {
  82164. break;
  82165. }
  82166. }
  82167. }
  82168. }
  82169. // Create lines
  82170. for (index = 0; index < adjacencies.length; index++) {
  82171. // 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
  82172. var current = adjacencies[index];
  82173. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82174. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82175. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82176. }
  82177. // Merge into a single mesh
  82178. var engine = this._source.getScene().getEngine();
  82179. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82180. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82181. this._ib = engine.createIndexBuffer(this._linesIndices);
  82182. this._indicesCount = this._linesIndices.length;
  82183. };
  82184. EdgesRenderer.prototype.render = function () {
  82185. var scene = this._source.getScene();
  82186. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82187. return;
  82188. }
  82189. var engine = scene.getEngine();
  82190. this._lineShader._preBind();
  82191. // VBOs
  82192. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82193. scene.resetCachedMaterial();
  82194. this._lineShader.setColor4("color", this._source.edgesColor);
  82195. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82196. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82197. }
  82198. else {
  82199. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82200. }
  82201. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82202. this._lineShader.bind(this._source.getWorldMatrix());
  82203. // Draw order
  82204. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82205. this._lineShader.unbind();
  82206. engine.setDepthWrite(true);
  82207. };
  82208. return EdgesRenderer;
  82209. }());
  82210. BABYLON.EdgesRenderer = EdgesRenderer;
  82211. })(BABYLON || (BABYLON = {}));
  82212. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82213. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82214. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82215. s = arguments[i];
  82216. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82217. t[p] = s[p];
  82218. }
  82219. return t;
  82220. };
  82221. var BABYLON;
  82222. (function (BABYLON) {
  82223. /**
  82224. * The effect layer Helps adding post process effect blended with the main pass.
  82225. *
  82226. * This can be for instance use to generate glow or higlight effects on the scene.
  82227. *
  82228. * The effect layer class can not be used directly and is intented to inherited from to be
  82229. * customized per effects.
  82230. */
  82231. var EffectLayer = /** @class */ (function () {
  82232. /**
  82233. * Instantiates a new effect Layer and references it in the scene.
  82234. * @param name The name of the layer
  82235. * @param scene The scene to use the layer in
  82236. */
  82237. function EffectLayer(
  82238. /** The Friendly of the effect in the scene */
  82239. name, scene) {
  82240. this.name = name;
  82241. this._vertexBuffers = {};
  82242. this._maxSize = 0;
  82243. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82244. this._shouldRender = true;
  82245. this._postProcesses = [];
  82246. this._textures = [];
  82247. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82248. /**
  82249. * The clear color of the texture used to generate the glow map.
  82250. */
  82251. this.neutralColor = new BABYLON.Color4();
  82252. /**
  82253. * Specifies wether the highlight layer is enabled or not.
  82254. */
  82255. this.isEnabled = true;
  82256. /**
  82257. * An event triggered when the effect layer has been disposed.
  82258. */
  82259. this.onDisposeObservable = new BABYLON.Observable();
  82260. /**
  82261. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82262. */
  82263. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82264. /**
  82265. * An event triggered when the generated texture is being merged in the scene.
  82266. */
  82267. this.onBeforeComposeObservable = new BABYLON.Observable();
  82268. /**
  82269. * An event triggered when the generated texture has been merged in the scene.
  82270. */
  82271. this.onAfterComposeObservable = new BABYLON.Observable();
  82272. /**
  82273. * An event triggered when the efffect layer changes its size.
  82274. */
  82275. this.onSizeChangedObservable = new BABYLON.Observable();
  82276. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82277. this._engine = scene.getEngine();
  82278. this._maxSize = this._engine.getCaps().maxTextureSize;
  82279. this._scene.effectLayers.push(this);
  82280. // Generate Buffers
  82281. this._generateIndexBuffer();
  82282. this._genrateVertexBuffer();
  82283. }
  82284. Object.defineProperty(EffectLayer.prototype, "camera", {
  82285. /**
  82286. * Gets the camera attached to the layer.
  82287. */
  82288. get: function () {
  82289. return this._effectLayerOptions.camera;
  82290. },
  82291. enumerable: true,
  82292. configurable: true
  82293. });
  82294. /**
  82295. * Initializes the effect layer with the required options.
  82296. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82297. */
  82298. EffectLayer.prototype._init = function (options) {
  82299. // Adapt options
  82300. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82301. this._setMainTextureSize();
  82302. this._createMainTexture();
  82303. this._createTextureAndPostProcesses();
  82304. this._mergeEffect = this._createMergeEffect();
  82305. };
  82306. /**
  82307. * Generates the index buffer of the full screen quad blending to the main canvas.
  82308. */
  82309. EffectLayer.prototype._generateIndexBuffer = function () {
  82310. // Indices
  82311. var indices = [];
  82312. indices.push(0);
  82313. indices.push(1);
  82314. indices.push(2);
  82315. indices.push(0);
  82316. indices.push(2);
  82317. indices.push(3);
  82318. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82319. };
  82320. /**
  82321. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82322. */
  82323. EffectLayer.prototype._genrateVertexBuffer = function () {
  82324. // VBO
  82325. var vertices = [];
  82326. vertices.push(1, 1);
  82327. vertices.push(-1, 1);
  82328. vertices.push(-1, -1);
  82329. vertices.push(1, -1);
  82330. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82331. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82332. };
  82333. /**
  82334. * Sets the main texture desired size which is the closest power of two
  82335. * of the engine canvas size.
  82336. */
  82337. EffectLayer.prototype._setMainTextureSize = function () {
  82338. if (this._effectLayerOptions.mainTextureFixedSize) {
  82339. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82340. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82341. }
  82342. else {
  82343. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82344. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82345. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82346. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82347. }
  82348. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82349. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82350. };
  82351. /**
  82352. * Creates the main texture for the effect layer.
  82353. */
  82354. EffectLayer.prototype._createMainTexture = function () {
  82355. var _this = this;
  82356. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82357. width: this._mainTextureDesiredSize.width,
  82358. height: this._mainTextureDesiredSize.height
  82359. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82360. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82361. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82362. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82363. this._mainTexture.anisotropicFilteringLevel = 1;
  82364. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82365. this._mainTexture.renderParticles = false;
  82366. this._mainTexture.renderList = null;
  82367. this._mainTexture.ignoreCameraViewport = true;
  82368. // Custom render function
  82369. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82370. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82371. var index;
  82372. var engine = _this._scene.getEngine();
  82373. if (depthOnlySubMeshes.length) {
  82374. engine.setColorWrite(false);
  82375. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82376. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82377. }
  82378. engine.setColorWrite(true);
  82379. }
  82380. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82381. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82382. }
  82383. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82384. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82385. }
  82386. for (index = 0; index < transparentSubMeshes.length; index++) {
  82387. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82388. }
  82389. };
  82390. this._mainTexture.onClearObservable.add(function (engine) {
  82391. engine.clear(_this.neutralColor, true, true, true);
  82392. });
  82393. };
  82394. /**
  82395. * Checks for the readiness of the element composing the layer.
  82396. * @param subMesh the mesh to check for
  82397. * @param useInstances specify wether or not to use instances to render the mesh
  82398. * @param emissiveTexture the associated emissive texture used to generate the glow
  82399. * @return true if ready otherwise, false
  82400. */
  82401. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82402. var material = subMesh.getMaterial();
  82403. if (!material) {
  82404. return false;
  82405. }
  82406. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82407. return false;
  82408. }
  82409. var defines = [];
  82410. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82411. var mesh = subMesh.getMesh();
  82412. var uv1 = false;
  82413. var uv2 = false;
  82414. // Alpha test
  82415. if (material && material.needAlphaTesting()) {
  82416. var alphaTexture = material.getAlphaTestTexture();
  82417. if (alphaTexture) {
  82418. defines.push("#define ALPHATEST");
  82419. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82420. alphaTexture.coordinatesIndex === 1) {
  82421. defines.push("#define DIFFUSEUV2");
  82422. uv2 = true;
  82423. }
  82424. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82425. defines.push("#define DIFFUSEUV1");
  82426. uv1 = true;
  82427. }
  82428. }
  82429. }
  82430. // Emissive
  82431. if (emissiveTexture) {
  82432. defines.push("#define EMISSIVE");
  82433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82434. emissiveTexture.coordinatesIndex === 1) {
  82435. defines.push("#define EMISSIVEUV2");
  82436. uv2 = true;
  82437. }
  82438. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82439. defines.push("#define EMISSIVEUV1");
  82440. uv1 = true;
  82441. }
  82442. }
  82443. if (uv1) {
  82444. attribs.push(BABYLON.VertexBuffer.UVKind);
  82445. defines.push("#define UV1");
  82446. }
  82447. if (uv2) {
  82448. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82449. defines.push("#define UV2");
  82450. }
  82451. // Bones
  82452. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82453. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82454. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82455. if (mesh.numBoneInfluencers > 4) {
  82456. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82457. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82458. }
  82459. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82460. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82461. }
  82462. else {
  82463. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82464. }
  82465. // Instances
  82466. if (useInstances) {
  82467. defines.push("#define INSTANCES");
  82468. attribs.push("world0");
  82469. attribs.push("world1");
  82470. attribs.push("world2");
  82471. attribs.push("world3");
  82472. }
  82473. // Get correct effect
  82474. var join = defines.join("\n");
  82475. if (this._cachedDefines !== join) {
  82476. this._cachedDefines = join;
  82477. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82478. }
  82479. return this._effectLayerMapGenerationEffect.isReady();
  82480. };
  82481. /**
  82482. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82483. */
  82484. EffectLayer.prototype.render = function () {
  82485. var currentEffect = this._mergeEffect;
  82486. // Check
  82487. if (!currentEffect.isReady())
  82488. return;
  82489. for (var i = 0; i < this._postProcesses.length; i++) {
  82490. if (!this._postProcesses[i].isReady()) {
  82491. return;
  82492. }
  82493. }
  82494. var engine = this._scene.getEngine();
  82495. this.onBeforeComposeObservable.notifyObservers(this);
  82496. // Render
  82497. engine.enableEffect(currentEffect);
  82498. engine.setState(false);
  82499. // VBOs
  82500. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82501. // Cache
  82502. var previousAlphaMode = engine.getAlphaMode();
  82503. // Go Blend.
  82504. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82505. // Blends the map on the main canvas.
  82506. this._internalRender(currentEffect);
  82507. // Restore Alpha
  82508. engine.setAlphaMode(previousAlphaMode);
  82509. this.onAfterComposeObservable.notifyObservers(this);
  82510. // Handle size changes.
  82511. var size = this._mainTexture.getSize();
  82512. this._setMainTextureSize();
  82513. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82514. // Recreate RTT and post processes on size change.
  82515. this.onSizeChangedObservable.notifyObservers(this);
  82516. this._disposeTextureAndPostProcesses();
  82517. this._createMainTexture();
  82518. this._createTextureAndPostProcesses();
  82519. }
  82520. };
  82521. /**
  82522. * Determine if a given mesh will be used in the current effect.
  82523. * @param mesh mesh to test
  82524. * @returns true if the mesh will be used
  82525. */
  82526. EffectLayer.prototype.hasMesh = function (mesh) {
  82527. return true;
  82528. };
  82529. /**
  82530. * Returns true if the layer contains information to display, otherwise false.
  82531. * @returns true if the glow layer should be rendered
  82532. */
  82533. EffectLayer.prototype.shouldRender = function () {
  82534. return this.isEnabled && this._shouldRender;
  82535. };
  82536. /**
  82537. * Returns true if the mesh should render, otherwise false.
  82538. * @param mesh The mesh to render
  82539. * @returns true if it should render otherwise false
  82540. */
  82541. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82542. return true;
  82543. };
  82544. /**
  82545. * Returns true if the mesh should render, otherwise false.
  82546. * @param mesh The mesh to render
  82547. * @returns true if it should render otherwise false
  82548. */
  82549. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82550. return true;
  82551. };
  82552. /**
  82553. * Renders the submesh passed in parameter to the generation map.
  82554. */
  82555. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82556. var _this = this;
  82557. if (!this.shouldRender()) {
  82558. return;
  82559. }
  82560. var material = subMesh.getMaterial();
  82561. var mesh = subMesh.getRenderingMesh();
  82562. var scene = this._scene;
  82563. var engine = scene.getEngine();
  82564. if (!material) {
  82565. return;
  82566. }
  82567. // Do not block in blend mode.
  82568. if (material.needAlphaBlendingForMesh(mesh)) {
  82569. return;
  82570. }
  82571. // Culling
  82572. engine.setState(material.backFaceCulling);
  82573. // Managing instances
  82574. var batch = mesh._getInstancesRenderList(subMesh._id);
  82575. if (batch.mustReturn) {
  82576. return;
  82577. }
  82578. // Early Exit per mesh
  82579. if (!this._shouldRenderMesh(mesh)) {
  82580. return;
  82581. }
  82582. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82583. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82584. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82585. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82586. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82587. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82588. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82589. // Alpha test
  82590. if (material && material.needAlphaTesting()) {
  82591. var alphaTexture = material.getAlphaTestTexture();
  82592. if (alphaTexture) {
  82593. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82594. var textureMatrix = alphaTexture.getTextureMatrix();
  82595. if (textureMatrix) {
  82596. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82597. }
  82598. }
  82599. }
  82600. // Glow emissive only
  82601. if (this._emissiveTextureAndColor.texture) {
  82602. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82603. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82604. }
  82605. // Bones
  82606. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82607. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82608. }
  82609. // Draw
  82610. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82611. }
  82612. else {
  82613. // Need to reset refresh rate of the shadowMap
  82614. this._mainTexture.resetRefreshCounter();
  82615. }
  82616. };
  82617. /**
  82618. * Rebuild the required buffers.
  82619. * @ignore Internal use only.
  82620. */
  82621. EffectLayer.prototype._rebuild = function () {
  82622. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82623. if (vb) {
  82624. vb._rebuild();
  82625. }
  82626. this._generateIndexBuffer();
  82627. };
  82628. /**
  82629. * Dispose only the render target textures and post process.
  82630. */
  82631. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82632. this._mainTexture.dispose();
  82633. for (var i = 0; i < this._postProcesses.length; i++) {
  82634. if (this._postProcesses[i]) {
  82635. this._postProcesses[i].dispose();
  82636. }
  82637. }
  82638. this._postProcesses = [];
  82639. for (var i = 0; i < this._textures.length; i++) {
  82640. if (this._textures[i]) {
  82641. this._textures[i].dispose();
  82642. }
  82643. }
  82644. this._textures = [];
  82645. };
  82646. /**
  82647. * Dispose the highlight layer and free resources.
  82648. */
  82649. EffectLayer.prototype.dispose = function () {
  82650. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82651. if (vertexBuffer) {
  82652. vertexBuffer.dispose();
  82653. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82654. }
  82655. if (this._indexBuffer) {
  82656. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82657. this._indexBuffer = null;
  82658. }
  82659. // Clean textures and post processes
  82660. this._disposeTextureAndPostProcesses();
  82661. // Remove from scene
  82662. var index = this._scene.effectLayers.indexOf(this, 0);
  82663. if (index > -1) {
  82664. this._scene.effectLayers.splice(index, 1);
  82665. }
  82666. // Callback
  82667. this.onDisposeObservable.notifyObservers(this);
  82668. this.onDisposeObservable.clear();
  82669. this.onBeforeRenderMainTextureObservable.clear();
  82670. this.onBeforeComposeObservable.clear();
  82671. this.onAfterComposeObservable.clear();
  82672. this.onSizeChangedObservable.clear();
  82673. };
  82674. return EffectLayer;
  82675. }());
  82676. BABYLON.EffectLayer = EffectLayer;
  82677. })(BABYLON || (BABYLON = {}));
  82678. //# sourceMappingURL=babylon.effectLayer.js.map
  82679. var BABYLON;
  82680. (function (BABYLON) {
  82681. /**
  82682. * Special Glow Blur post process only blurring the alpha channel
  82683. * It enforces keeping the most luminous color in the color channel.
  82684. */
  82685. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82686. __extends(GlowBlurPostProcess, _super);
  82687. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82689. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82690. _this.direction = direction;
  82691. _this.kernel = kernel;
  82692. _this.onApplyObservable.add(function (effect) {
  82693. effect.setFloat2("screenSize", _this.width, _this.height);
  82694. effect.setVector2("direction", _this.direction);
  82695. effect.setFloat("blurWidth", _this.kernel);
  82696. });
  82697. return _this;
  82698. }
  82699. return GlowBlurPostProcess;
  82700. }(BABYLON.PostProcess));
  82701. /**
  82702. * The highlight layer Helps adding a glow effect around a mesh.
  82703. *
  82704. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82705. * glowy meshes to your scene.
  82706. *
  82707. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82708. */
  82709. var HighlightLayer = /** @class */ (function (_super) {
  82710. __extends(HighlightLayer, _super);
  82711. /**
  82712. * Instantiates a new highlight Layer and references it to the scene..
  82713. * @param name The name of the layer
  82714. * @param scene The scene to use the layer in
  82715. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82716. */
  82717. function HighlightLayer(name, scene, options) {
  82718. var _this = _super.call(this, name, scene) || this;
  82719. _this.name = name;
  82720. /**
  82721. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82722. */
  82723. _this.innerGlow = true;
  82724. /**
  82725. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82726. */
  82727. _this.outerGlow = true;
  82728. /**
  82729. * An event triggered when the highlight layer is being blurred.
  82730. */
  82731. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82732. /**
  82733. * An event triggered when the highlight layer has been blurred.
  82734. */
  82735. _this.onAfterBlurObservable = new BABYLON.Observable();
  82736. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82737. _this._meshes = {};
  82738. _this._excludedMeshes = {};
  82739. _this.neutralColor = HighlightLayer.NeutralColor;
  82740. // Warn on stencil
  82741. if (!_this._engine.isStencilEnable) {
  82742. 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 }");
  82743. }
  82744. // Adapt options
  82745. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82746. // Initialize the layer
  82747. _this._init({
  82748. alphaBlendingMode: _this._options.alphaBlendingMode,
  82749. camera: _this._options.camera,
  82750. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82751. mainTextureRatio: _this._options.mainTextureRatio
  82752. });
  82753. // Do not render as long as no meshes have been added
  82754. _this._shouldRender = false;
  82755. return _this;
  82756. }
  82757. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82758. /**
  82759. * Gets the horizontal size of the blur.
  82760. */
  82761. get: function () {
  82762. return this._horizontalBlurPostprocess.kernel;
  82763. },
  82764. /**
  82765. * Specifies the horizontal size of the blur.
  82766. */
  82767. set: function (value) {
  82768. this._horizontalBlurPostprocess.kernel = value;
  82769. },
  82770. enumerable: true,
  82771. configurable: true
  82772. });
  82773. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  82774. /**
  82775. * Gets the vertical size of the blur.
  82776. */
  82777. get: function () {
  82778. return this._verticalBlurPostprocess.kernel;
  82779. },
  82780. /**
  82781. * Specifies the vertical size of the blur.
  82782. */
  82783. set: function (value) {
  82784. this._verticalBlurPostprocess.kernel = value;
  82785. },
  82786. enumerable: true,
  82787. configurable: true
  82788. });
  82789. /**
  82790. * Get the effect name of the layer.
  82791. * @return The effect name
  82792. */
  82793. HighlightLayer.prototype.getEffectName = function () {
  82794. return HighlightLayer.EffectName;
  82795. };
  82796. /**
  82797. * Create the merge effect. This is the shader use to blit the information back
  82798. * to the main canvas at the end of the scene rendering.
  82799. */
  82800. HighlightLayer.prototype._createMergeEffect = function () {
  82801. // Effect
  82802. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  82803. };
  82804. /**
  82805. * Creates the render target textures and post processes used in the highlight layer.
  82806. */
  82807. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  82808. var _this = this;
  82809. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  82810. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  82811. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  82812. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  82813. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  82814. width: blurTextureWidth,
  82815. height: blurTextureHeight
  82816. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82817. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82818. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82819. this._blurTexture.anisotropicFilteringLevel = 16;
  82820. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82821. this._blurTexture.renderParticles = false;
  82822. this._blurTexture.ignoreCameraViewport = true;
  82823. this._textures = [this._blurTexture];
  82824. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  82825. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82826. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  82827. effect.setTexture("textureSampler", _this._mainTexture);
  82828. });
  82829. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82830. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82831. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82832. });
  82833. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82834. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  82835. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82836. });
  82837. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82838. }
  82839. else {
  82840. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  82841. width: blurTextureWidth,
  82842. height: blurTextureHeight
  82843. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82844. this._horizontalBlurPostprocess.width = blurTextureWidth;
  82845. this._horizontalBlurPostprocess.height = blurTextureHeight;
  82846. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82847. effect.setTexture("textureSampler", _this._mainTexture);
  82848. });
  82849. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  82850. width: blurTextureWidth,
  82851. height: blurTextureHeight
  82852. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82853. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82854. }
  82855. this._mainTexture.onAfterUnbindObservable.add(function () {
  82856. _this.onBeforeBlurObservable.notifyObservers(_this);
  82857. var internalTexture = _this._blurTexture.getInternalTexture();
  82858. if (internalTexture) {
  82859. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  82860. }
  82861. _this.onAfterBlurObservable.notifyObservers(_this);
  82862. });
  82863. // Prevent autoClear.
  82864. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  82865. };
  82866. /**
  82867. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  82868. */
  82869. HighlightLayer.prototype.needStencil = function () {
  82870. return true;
  82871. };
  82872. /**
  82873. * Checks for the readiness of the element composing the layer.
  82874. * @param subMesh the mesh to check for
  82875. * @param useInstances specify wether or not to use instances to render the mesh
  82876. * @param emissiveTexture the associated emissive texture used to generate the glow
  82877. * @return true if ready otherwise, false
  82878. */
  82879. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  82880. var material = subMesh.getMaterial();
  82881. var mesh = subMesh.getRenderingMesh();
  82882. if (!material || !mesh || !this._meshes) {
  82883. return false;
  82884. }
  82885. var emissiveTexture = null;
  82886. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82887. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82888. emissiveTexture = material.emissiveTexture;
  82889. }
  82890. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  82891. };
  82892. /**
  82893. * Implementation specific of rendering the generating effect on the main canvas.
  82894. * @param effect The effect used to render through
  82895. */
  82896. HighlightLayer.prototype._internalRender = function (effect) {
  82897. // Texture
  82898. effect.setTexture("textureSampler", this._blurTexture);
  82899. // Cache
  82900. var engine = this._engine;
  82901. var previousStencilBuffer = engine.getStencilBuffer();
  82902. var previousStencilFunction = engine.getStencilFunction();
  82903. var previousStencilMask = engine.getStencilMask();
  82904. var previousStencilOperationPass = engine.getStencilOperationPass();
  82905. var previousStencilOperationFail = engine.getStencilOperationFail();
  82906. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  82907. var previousStencilReference = engine.getStencilFunctionReference();
  82908. // Stencil operations
  82909. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  82910. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  82911. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  82912. // Draw order
  82913. engine.setStencilMask(0x00);
  82914. engine.setStencilBuffer(true);
  82915. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  82916. // 2 passes inner outer
  82917. if (this.outerGlow) {
  82918. effect.setFloat("offset", 0);
  82919. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  82920. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82921. }
  82922. if (this.innerGlow) {
  82923. effect.setFloat("offset", 1);
  82924. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  82925. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82926. }
  82927. // Restore Cache
  82928. engine.setStencilFunction(previousStencilFunction);
  82929. engine.setStencilMask(previousStencilMask);
  82930. engine.setStencilBuffer(previousStencilBuffer);
  82931. engine.setStencilOperationPass(previousStencilOperationPass);
  82932. engine.setStencilOperationFail(previousStencilOperationFail);
  82933. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  82934. engine.setStencilFunctionReference(previousStencilReference);
  82935. };
  82936. /**
  82937. * Returns true if the layer contains information to display, otherwise false.
  82938. */
  82939. HighlightLayer.prototype.shouldRender = function () {
  82940. if (_super.prototype.shouldRender.call(this)) {
  82941. return this._meshes ? true : false;
  82942. }
  82943. return false;
  82944. };
  82945. /**
  82946. * Returns true if the mesh should render, otherwise false.
  82947. * @param mesh The mesh to render
  82948. * @returns true if it should render otherwise false
  82949. */
  82950. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  82951. // Excluded Mesh
  82952. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  82953. return false;
  82954. }
  82955. ;
  82956. return true;
  82957. };
  82958. /**
  82959. * Sets the required values for both the emissive texture and and the main color.
  82960. */
  82961. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  82962. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82963. if (highlightLayerMesh) {
  82964. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  82965. }
  82966. else {
  82967. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  82968. }
  82969. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82970. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  82971. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  82972. }
  82973. else {
  82974. this._emissiveTextureAndColor.texture = null;
  82975. }
  82976. };
  82977. /**
  82978. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  82979. * @param mesh The mesh to exclude from the highlight layer
  82980. */
  82981. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  82982. if (!this._excludedMeshes) {
  82983. return;
  82984. }
  82985. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82986. if (!meshExcluded) {
  82987. this._excludedMeshes[mesh.uniqueId] = {
  82988. mesh: mesh,
  82989. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  82990. mesh.getEngine().setStencilBuffer(false);
  82991. }),
  82992. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  82993. mesh.getEngine().setStencilBuffer(true);
  82994. }),
  82995. };
  82996. }
  82997. };
  82998. /**
  82999. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  83000. * @param mesh The mesh to highlight
  83001. */
  83002. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  83003. if (!this._excludedMeshes) {
  83004. return;
  83005. }
  83006. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83007. if (meshExcluded) {
  83008. if (meshExcluded.beforeRender) {
  83009. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  83010. }
  83011. if (meshExcluded.afterRender) {
  83012. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  83013. }
  83014. }
  83015. this._excludedMeshes[mesh.uniqueId] = null;
  83016. };
  83017. /**
  83018. * Determine if a given mesh will be highlighted by the current HighlightLayer
  83019. * @param mesh mesh to test
  83020. * @returns true if the mesh will be highlighted by the current HighlightLayer
  83021. */
  83022. HighlightLayer.prototype.hasMesh = function (mesh) {
  83023. if (!this._meshes) {
  83024. return false;
  83025. }
  83026. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  83027. };
  83028. /**
  83029. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  83030. * @param mesh The mesh to highlight
  83031. * @param color The color of the highlight
  83032. * @param glowEmissiveOnly Extract the glow from the emissive texture
  83033. */
  83034. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  83035. var _this = this;
  83036. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  83037. if (!this._meshes) {
  83038. return;
  83039. }
  83040. var meshHighlight = this._meshes[mesh.uniqueId];
  83041. if (meshHighlight) {
  83042. meshHighlight.color = color;
  83043. }
  83044. else {
  83045. this._meshes[mesh.uniqueId] = {
  83046. mesh: mesh,
  83047. color: color,
  83048. // Lambda required for capture due to Observable this context
  83049. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  83050. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  83051. _this._defaultStencilReference(mesh);
  83052. }
  83053. else {
  83054. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  83055. }
  83056. }),
  83057. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  83058. glowEmissiveOnly: glowEmissiveOnly
  83059. };
  83060. }
  83061. this._shouldRender = true;
  83062. };
  83063. /**
  83064. * Remove a mesh from the highlight layer in order to make it stop glowing.
  83065. * @param mesh The mesh to highlight
  83066. */
  83067. HighlightLayer.prototype.removeMesh = function (mesh) {
  83068. if (!this._meshes) {
  83069. return;
  83070. }
  83071. var meshHighlight = this._meshes[mesh.uniqueId];
  83072. if (meshHighlight) {
  83073. if (meshHighlight.observerHighlight) {
  83074. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83075. }
  83076. if (meshHighlight.observerDefault) {
  83077. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83078. }
  83079. delete this._meshes[mesh.uniqueId];
  83080. }
  83081. this._shouldRender = false;
  83082. for (var meshHighlightToCheck in this._meshes) {
  83083. if (this._meshes[meshHighlightToCheck]) {
  83084. this._shouldRender = true;
  83085. break;
  83086. }
  83087. }
  83088. };
  83089. /**
  83090. * Force the stencil to the normal expected value for none glowing parts
  83091. */
  83092. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83093. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83094. };
  83095. /**
  83096. * Free any resources and references associated to a mesh.
  83097. * Internal use
  83098. * @param mesh The mesh to free.
  83099. */
  83100. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83101. this.removeMesh(mesh);
  83102. this.removeExcludedMesh(mesh);
  83103. };
  83104. /**
  83105. * Dispose the highlight layer and free resources.
  83106. */
  83107. HighlightLayer.prototype.dispose = function () {
  83108. if (this._meshes) {
  83109. // Clean mesh references
  83110. for (var id in this._meshes) {
  83111. var meshHighlight = this._meshes[id];
  83112. if (meshHighlight && meshHighlight.mesh) {
  83113. if (meshHighlight.observerHighlight) {
  83114. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83115. }
  83116. if (meshHighlight.observerDefault) {
  83117. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83118. }
  83119. }
  83120. }
  83121. this._meshes = null;
  83122. }
  83123. if (this._excludedMeshes) {
  83124. for (var id in this._excludedMeshes) {
  83125. var meshHighlight = this._excludedMeshes[id];
  83126. if (meshHighlight) {
  83127. if (meshHighlight.beforeRender) {
  83128. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83129. }
  83130. if (meshHighlight.afterRender) {
  83131. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83132. }
  83133. }
  83134. }
  83135. this._excludedMeshes = null;
  83136. }
  83137. _super.prototype.dispose.call(this);
  83138. };
  83139. /**
  83140. * Effect Name of the highlight layer.
  83141. */
  83142. HighlightLayer.EffectName = "HighlightLayer";
  83143. /**
  83144. * The neutral color used during the preparation of the glow effect.
  83145. * This is black by default as the blend operation is a blend operation.
  83146. */
  83147. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83148. /**
  83149. * Stencil value used for glowing meshes.
  83150. */
  83151. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83152. /**
  83153. * Stencil value used for the other meshes in the scene.
  83154. */
  83155. HighlightLayer.NormalMeshStencilReference = 0x01;
  83156. return HighlightLayer;
  83157. }(BABYLON.EffectLayer));
  83158. BABYLON.HighlightLayer = HighlightLayer;
  83159. })(BABYLON || (BABYLON = {}));
  83160. //# sourceMappingURL=babylon.highlightLayer.js.map
  83161. var BABYLON;
  83162. (function (BABYLON) {
  83163. /**
  83164. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83165. *
  83166. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83167. * glowy meshes to your scene.
  83168. *
  83169. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83170. */
  83171. var GlowLayer = /** @class */ (function (_super) {
  83172. __extends(GlowLayer, _super);
  83173. /**
  83174. * Instantiates a new glow Layer and references it to the scene.
  83175. * @param name The name of the layer
  83176. * @param scene The scene to use the layer in
  83177. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83178. */
  83179. function GlowLayer(name, scene, options) {
  83180. var _this = _super.call(this, name, scene) || this;
  83181. _this.name = name;
  83182. _this._intensity = 1.0;
  83183. _this._includedOnlyMeshes = [];
  83184. _this._excludedMeshes = [];
  83185. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83186. // Adapt options
  83187. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83188. // Initialize the layer
  83189. _this._init({
  83190. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83191. camera: _this._options.camera,
  83192. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83193. mainTextureRatio: _this._options.mainTextureRatio
  83194. });
  83195. return _this;
  83196. }
  83197. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83198. /**
  83199. * Gets the kernel size of the blur.
  83200. */
  83201. get: function () {
  83202. return this._horizontalBlurPostprocess1.kernel;
  83203. },
  83204. /**
  83205. * Sets the kernel size of the blur.
  83206. */
  83207. set: function (value) {
  83208. this._horizontalBlurPostprocess1.kernel = value;
  83209. this._verticalBlurPostprocess1.kernel = value;
  83210. this._horizontalBlurPostprocess2.kernel = value;
  83211. this._verticalBlurPostprocess2.kernel = value;
  83212. },
  83213. enumerable: true,
  83214. configurable: true
  83215. });
  83216. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83217. /**
  83218. * Gets the glow intensity.
  83219. */
  83220. get: function () {
  83221. return this._intensity;
  83222. },
  83223. /**
  83224. * Sets the glow intensity.
  83225. */
  83226. set: function (value) {
  83227. this._intensity = value;
  83228. },
  83229. enumerable: true,
  83230. configurable: true
  83231. });
  83232. /**
  83233. * Get the effect name of the layer.
  83234. * @return The effect name
  83235. */
  83236. GlowLayer.prototype.getEffectName = function () {
  83237. return GlowLayer.EffectName;
  83238. };
  83239. /**
  83240. * Create the merge effect. This is the shader use to blit the information back
  83241. * to the main canvas at the end of the scene rendering.
  83242. */
  83243. GlowLayer.prototype._createMergeEffect = function () {
  83244. // Effect
  83245. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83246. };
  83247. /**
  83248. * Creates the render target textures and post processes used in the glow layer.
  83249. */
  83250. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83251. var _this = this;
  83252. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83253. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83254. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83255. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83256. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83257. width: blurTextureWidth,
  83258. height: blurTextureHeight
  83259. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83260. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83261. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83262. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83263. this._blurTexture1.renderParticles = false;
  83264. this._blurTexture1.ignoreCameraViewport = true;
  83265. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83266. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83267. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83268. width: blurTextureWidth2,
  83269. height: blurTextureHeight2
  83270. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83271. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83272. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83273. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83274. this._blurTexture2.renderParticles = false;
  83275. this._blurTexture2.ignoreCameraViewport = true;
  83276. this._textures = [this._blurTexture1, this._blurTexture2];
  83277. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83278. width: blurTextureWidth,
  83279. height: blurTextureHeight
  83280. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83281. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83282. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83283. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83284. effect.setTexture("textureSampler", _this._mainTexture);
  83285. });
  83286. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83287. width: blurTextureWidth,
  83288. height: blurTextureHeight
  83289. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83290. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83291. width: blurTextureWidth2,
  83292. height: blurTextureHeight2
  83293. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83294. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83295. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83296. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83297. effect.setTexture("textureSampler", _this._blurTexture1);
  83298. });
  83299. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83300. width: blurTextureWidth2,
  83301. height: blurTextureHeight2
  83302. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83303. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83304. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83305. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83306. this._mainTexture.samples = this._options.mainTextureSamples;
  83307. this._mainTexture.onAfterUnbindObservable.add(function () {
  83308. var internalTexture = _this._blurTexture1.getInternalTexture();
  83309. if (internalTexture) {
  83310. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83311. internalTexture = _this._blurTexture2.getInternalTexture();
  83312. if (internalTexture) {
  83313. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83314. }
  83315. }
  83316. });
  83317. // Prevent autoClear.
  83318. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83319. };
  83320. /**
  83321. * Checks for the readiness of the element composing the layer.
  83322. * @param subMesh the mesh to check for
  83323. * @param useInstances specify wether or not to use instances to render the mesh
  83324. * @param emissiveTexture the associated emissive texture used to generate the glow
  83325. * @return true if ready otherwise, false
  83326. */
  83327. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83328. var material = subMesh.getMaterial();
  83329. var mesh = subMesh.getRenderingMesh();
  83330. if (!material || !mesh) {
  83331. return false;
  83332. }
  83333. var emissiveTexture = material.emissiveTexture;
  83334. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83335. };
  83336. /**
  83337. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83338. */
  83339. GlowLayer.prototype.needStencil = function () {
  83340. return false;
  83341. };
  83342. /**
  83343. * Implementation specific of rendering the generating effect on the main canvas.
  83344. * @param effect The effect used to render through
  83345. */
  83346. GlowLayer.prototype._internalRender = function (effect) {
  83347. // Texture
  83348. effect.setTexture("textureSampler", this._blurTexture1);
  83349. effect.setTexture("textureSampler2", this._blurTexture2);
  83350. effect.setFloat("offset", this._intensity);
  83351. // Cache
  83352. var engine = this._engine;
  83353. var previousStencilBuffer = engine.getStencilBuffer();
  83354. // Draw order
  83355. engine.setStencilBuffer(false);
  83356. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83357. // Draw order
  83358. engine.setStencilBuffer(previousStencilBuffer);
  83359. };
  83360. /**
  83361. * Sets the required values for both the emissive texture and and the main color.
  83362. */
  83363. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83364. var textureLevel = 1.0;
  83365. if (this.customEmissiveTextureSelector) {
  83366. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83367. }
  83368. else {
  83369. if (material) {
  83370. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83371. if (this._emissiveTextureAndColor.texture) {
  83372. textureLevel = this._emissiveTextureAndColor.texture.level;
  83373. }
  83374. }
  83375. else {
  83376. this._emissiveTextureAndColor.texture = null;
  83377. }
  83378. }
  83379. if (this.customEmissiveColorSelector) {
  83380. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83381. }
  83382. else {
  83383. if (material.emissiveColor) {
  83384. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83385. }
  83386. else {
  83387. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83388. }
  83389. }
  83390. };
  83391. /**
  83392. * Returns true if the mesh should render, otherwise false.
  83393. * @param mesh The mesh to render
  83394. * @returns true if it should render otherwise false
  83395. */
  83396. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83397. return this.hasMesh(mesh);
  83398. };
  83399. /**
  83400. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83401. * @param mesh The mesh to exclude from the glow layer
  83402. */
  83403. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83404. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83405. this._excludedMeshes.push(mesh.uniqueId);
  83406. }
  83407. };
  83408. /**
  83409. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83410. * @param mesh The mesh to remove
  83411. */
  83412. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83413. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83414. if (index !== -1) {
  83415. this._excludedMeshes.splice(index, 1);
  83416. }
  83417. };
  83418. /**
  83419. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83420. * @param mesh The mesh to include in the glow layer
  83421. */
  83422. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83423. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83424. this._includedOnlyMeshes.push(mesh.uniqueId);
  83425. }
  83426. };
  83427. /**
  83428. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83429. * @param mesh The mesh to remove
  83430. */
  83431. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83432. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83433. if (index !== -1) {
  83434. this._includedOnlyMeshes.splice(index, 1);
  83435. }
  83436. };
  83437. /**
  83438. * Determine if a given mesh will be used in the glow layer
  83439. * @param mesh The mesh to test
  83440. * @returns true if the mesh will be highlighted by the current glow layer
  83441. */
  83442. GlowLayer.prototype.hasMesh = function (mesh) {
  83443. // Included Mesh
  83444. if (this._includedOnlyMeshes.length) {
  83445. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83446. }
  83447. ;
  83448. // Excluded Mesh
  83449. if (this._excludedMeshes.length) {
  83450. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83451. }
  83452. ;
  83453. return true;
  83454. };
  83455. /**
  83456. * Free any resources and references associated to a mesh.
  83457. * Internal use
  83458. * @param mesh The mesh to free.
  83459. */
  83460. GlowLayer.prototype._disposeMesh = function (mesh) {
  83461. this.removeIncludedOnlyMesh(mesh);
  83462. this.removeExcludedMesh(mesh);
  83463. };
  83464. /**
  83465. * Effect Name of the layer.
  83466. */
  83467. GlowLayer.EffectName = "GlowLayer";
  83468. /**
  83469. * The default blur kernel size used for the glow.
  83470. */
  83471. GlowLayer.DefaultBlurKernelSize = 32;
  83472. /**
  83473. * The default texture size ratio used for the glow.
  83474. */
  83475. GlowLayer.DefaultTextureRatio = 0.5;
  83476. return GlowLayer;
  83477. }(BABYLON.EffectLayer));
  83478. BABYLON.GlowLayer = GlowLayer;
  83479. })(BABYLON || (BABYLON = {}));
  83480. //# sourceMappingURL=babylon.glowLayer.js.map
  83481. var BABYLON;
  83482. (function (BABYLON) {
  83483. /**
  83484. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83485. */
  83486. var AssetTaskState;
  83487. (function (AssetTaskState) {
  83488. /**
  83489. * Initialization
  83490. */
  83491. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83492. /**
  83493. * Running
  83494. */
  83495. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83496. /**
  83497. * Done
  83498. */
  83499. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83500. /**
  83501. * Error
  83502. */
  83503. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83504. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83505. /**
  83506. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83507. */
  83508. var AbstractAssetTask = /** @class */ (function () {
  83509. /**
  83510. * Creates a new {BABYLON.AssetsManager}
  83511. * @param name defines the name of the task
  83512. */
  83513. function AbstractAssetTask(
  83514. /**
  83515. * Task name
  83516. */ name) {
  83517. this.name = name;
  83518. this._isCompleted = false;
  83519. this._taskState = AssetTaskState.INIT;
  83520. }
  83521. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83522. /**
  83523. * Get if the task is completed
  83524. */
  83525. get: function () {
  83526. return this._isCompleted;
  83527. },
  83528. enumerable: true,
  83529. configurable: true
  83530. });
  83531. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83532. /**
  83533. * Gets the current state of the task
  83534. */
  83535. get: function () {
  83536. return this._taskState;
  83537. },
  83538. enumerable: true,
  83539. configurable: true
  83540. });
  83541. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83542. /**
  83543. * Gets the current error object (if task is in error)
  83544. */
  83545. get: function () {
  83546. return this._errorObject;
  83547. },
  83548. enumerable: true,
  83549. configurable: true
  83550. });
  83551. /**
  83552. * Internal only
  83553. * @ignore
  83554. */
  83555. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83556. if (this._errorObject) {
  83557. return;
  83558. }
  83559. this._errorObject = {
  83560. message: message,
  83561. exception: exception
  83562. };
  83563. };
  83564. /**
  83565. * Execute the current task
  83566. * @param scene defines the scene where you want your assets to be loaded
  83567. * @param onSuccess is a callback called when the task is successfully executed
  83568. * @param onError is a callback called if an error occurs
  83569. */
  83570. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83571. var _this = this;
  83572. this._taskState = AssetTaskState.RUNNING;
  83573. this.runTask(scene, function () {
  83574. _this.onDoneCallback(onSuccess, onError);
  83575. }, function (msg, exception) {
  83576. _this.onErrorCallback(onError, msg, exception);
  83577. });
  83578. };
  83579. /**
  83580. * Execute the current task
  83581. * @param scene defines the scene where you want your assets to be loaded
  83582. * @param onSuccess is a callback called when the task is successfully executed
  83583. * @param onError is a callback called if an error occurs
  83584. */
  83585. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83586. throw new Error("runTask is not implemented");
  83587. };
  83588. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83589. this._taskState = AssetTaskState.ERROR;
  83590. this._errorObject = {
  83591. message: message,
  83592. exception: exception
  83593. };
  83594. if (this.onError) {
  83595. this.onError(this, message, exception);
  83596. }
  83597. onError();
  83598. };
  83599. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83600. try {
  83601. this._taskState = AssetTaskState.DONE;
  83602. this._isCompleted = true;
  83603. if (this.onSuccess) {
  83604. this.onSuccess(this);
  83605. }
  83606. onSuccess();
  83607. }
  83608. catch (e) {
  83609. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83610. }
  83611. };
  83612. return AbstractAssetTask;
  83613. }());
  83614. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83615. /**
  83616. * Class used to share progress information about assets loading
  83617. */
  83618. var AssetsProgressEvent = /** @class */ (function () {
  83619. /**
  83620. * Creates a {BABYLON.AssetsProgressEvent}
  83621. * @param remainingCount defines the number of remaining tasks to process
  83622. * @param totalCount defines the total number of tasks
  83623. * @param task defines the task that was just processed
  83624. */
  83625. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83626. this.remainingCount = remainingCount;
  83627. this.totalCount = totalCount;
  83628. this.task = task;
  83629. }
  83630. return AssetsProgressEvent;
  83631. }());
  83632. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83633. /**
  83634. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83635. */
  83636. var MeshAssetTask = /** @class */ (function (_super) {
  83637. __extends(MeshAssetTask, _super);
  83638. /**
  83639. * Creates a new {BABYLON.MeshAssetTask}
  83640. * @param name defines the name of the task
  83641. * @param meshesNames defines the list of mesh's names you want to load
  83642. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83643. * @param sceneFilename defines the filename of the scene to load from
  83644. */
  83645. function MeshAssetTask(
  83646. /**
  83647. * Defines the name of the task
  83648. */
  83649. name,
  83650. /**
  83651. * Defines the list of mesh's names you want to load
  83652. */
  83653. meshesNames,
  83654. /**
  83655. * Defines the root url to use as a base to load your meshes and associated resources
  83656. */
  83657. rootUrl,
  83658. /**
  83659. * Defines the filename of the scene to load from
  83660. */
  83661. sceneFilename) {
  83662. var _this = _super.call(this, name) || this;
  83663. _this.name = name;
  83664. _this.meshesNames = meshesNames;
  83665. _this.rootUrl = rootUrl;
  83666. _this.sceneFilename = sceneFilename;
  83667. return _this;
  83668. }
  83669. /**
  83670. * Execute the current task
  83671. * @param scene defines the scene where you want your assets to be loaded
  83672. * @param onSuccess is a callback called when the task is successfully executed
  83673. * @param onError is a callback called if an error occurs
  83674. */
  83675. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83676. var _this = this;
  83677. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83678. _this.loadedMeshes = meshes;
  83679. _this.loadedParticleSystems = particleSystems;
  83680. _this.loadedSkeletons = skeletons;
  83681. onSuccess();
  83682. }, null, function (scene, message, exception) {
  83683. onError(message, exception);
  83684. });
  83685. };
  83686. return MeshAssetTask;
  83687. }(AbstractAssetTask));
  83688. BABYLON.MeshAssetTask = MeshAssetTask;
  83689. /**
  83690. * Define a task used by {BABYLON.AssetsManager} to load text content
  83691. */
  83692. var TextFileAssetTask = /** @class */ (function (_super) {
  83693. __extends(TextFileAssetTask, _super);
  83694. /**
  83695. * Creates a new TextFileAssetTask object
  83696. * @param name defines the name of the task
  83697. * @param url defines the location of the file to load
  83698. */
  83699. function TextFileAssetTask(
  83700. /**
  83701. * Defines the name of the task
  83702. */
  83703. name,
  83704. /**
  83705. * Defines the location of the file to load
  83706. */
  83707. url) {
  83708. var _this = _super.call(this, name) || this;
  83709. _this.name = name;
  83710. _this.url = url;
  83711. return _this;
  83712. }
  83713. /**
  83714. * Execute the current task
  83715. * @param scene defines the scene where you want your assets to be loaded
  83716. * @param onSuccess is a callback called when the task is successfully executed
  83717. * @param onError is a callback called if an error occurs
  83718. */
  83719. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83720. var _this = this;
  83721. scene._loadFile(this.url, function (data) {
  83722. _this.text = data;
  83723. onSuccess();
  83724. }, undefined, false, false, function (request, exception) {
  83725. if (request) {
  83726. onError(request.status + " " + request.statusText, exception);
  83727. }
  83728. });
  83729. };
  83730. return TextFileAssetTask;
  83731. }(AbstractAssetTask));
  83732. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83733. /**
  83734. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83735. */
  83736. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83737. __extends(BinaryFileAssetTask, _super);
  83738. /**
  83739. * Creates a new BinaryFileAssetTask object
  83740. * @param name defines the name of the new task
  83741. * @param url defines the location of the file to load
  83742. */
  83743. function BinaryFileAssetTask(
  83744. /**
  83745. * Defines the name of the task
  83746. */
  83747. name,
  83748. /**
  83749. * Defines the location of the file to load
  83750. */
  83751. url) {
  83752. var _this = _super.call(this, name) || this;
  83753. _this.name = name;
  83754. _this.url = url;
  83755. return _this;
  83756. }
  83757. /**
  83758. * Execute the current task
  83759. * @param scene defines the scene where you want your assets to be loaded
  83760. * @param onSuccess is a callback called when the task is successfully executed
  83761. * @param onError is a callback called if an error occurs
  83762. */
  83763. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83764. var _this = this;
  83765. scene._loadFile(this.url, function (data) {
  83766. _this.data = data;
  83767. onSuccess();
  83768. }, undefined, true, true, function (request, exception) {
  83769. if (request) {
  83770. onError(request.status + " " + request.statusText, exception);
  83771. }
  83772. });
  83773. };
  83774. return BinaryFileAssetTask;
  83775. }(AbstractAssetTask));
  83776. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  83777. /**
  83778. * Define a task used by {BABYLON.AssetsManager} to load images
  83779. */
  83780. var ImageAssetTask = /** @class */ (function (_super) {
  83781. __extends(ImageAssetTask, _super);
  83782. /**
  83783. * Creates a new ImageAssetTask
  83784. * @param name defines the name of the task
  83785. * @param url defines the location of the image to load
  83786. */
  83787. function ImageAssetTask(
  83788. /**
  83789. * Defines the name of the task
  83790. */
  83791. name,
  83792. /**
  83793. * Defines the location of the image to load
  83794. */
  83795. url) {
  83796. var _this = _super.call(this, name) || this;
  83797. _this.name = name;
  83798. _this.url = url;
  83799. return _this;
  83800. }
  83801. /**
  83802. * Execute the current task
  83803. * @param scene defines the scene where you want your assets to be loaded
  83804. * @param onSuccess is a callback called when the task is successfully executed
  83805. * @param onError is a callback called if an error occurs
  83806. */
  83807. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83808. var _this = this;
  83809. var img = new Image();
  83810. BABYLON.Tools.SetCorsBehavior(this.url, img);
  83811. img.onload = function () {
  83812. _this.image = img;
  83813. onSuccess();
  83814. };
  83815. img.onerror = function (err) {
  83816. onError("Error loading image", err);
  83817. };
  83818. img.src = this.url;
  83819. };
  83820. return ImageAssetTask;
  83821. }(AbstractAssetTask));
  83822. BABYLON.ImageAssetTask = ImageAssetTask;
  83823. /**
  83824. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  83825. */
  83826. var TextureAssetTask = /** @class */ (function (_super) {
  83827. __extends(TextureAssetTask, _super);
  83828. /**
  83829. * Creates a new TextureAssetTask object
  83830. * @param name defines the name of the task
  83831. * @param url defines the location of the file to load
  83832. * @param noMipmap defines if mipmap should not be generated (default is false)
  83833. * @param invertY defines if texture must be inverted on Y axis (default is false)
  83834. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83835. */
  83836. function TextureAssetTask(
  83837. /**
  83838. * Defines the name of the task
  83839. */
  83840. name,
  83841. /**
  83842. * Defines the location of the file to load
  83843. */
  83844. url,
  83845. /**
  83846. * Defines if mipmap should not be generated (default is false)
  83847. */
  83848. noMipmap,
  83849. /**
  83850. * Defines if texture must be inverted on Y axis (default is false)
  83851. */
  83852. invertY,
  83853. /**
  83854. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83855. */
  83856. samplingMode) {
  83857. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83858. var _this = _super.call(this, name) || this;
  83859. _this.name = name;
  83860. _this.url = url;
  83861. _this.noMipmap = noMipmap;
  83862. _this.invertY = invertY;
  83863. _this.samplingMode = samplingMode;
  83864. return _this;
  83865. }
  83866. /**
  83867. * Execute the current task
  83868. * @param scene defines the scene where you want your assets to be loaded
  83869. * @param onSuccess is a callback called when the task is successfully executed
  83870. * @param onError is a callback called if an error occurs
  83871. */
  83872. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83873. var onload = function () {
  83874. onSuccess();
  83875. };
  83876. var onerror = function (message, exception) {
  83877. onError(message, exception);
  83878. };
  83879. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  83880. };
  83881. return TextureAssetTask;
  83882. }(AbstractAssetTask));
  83883. BABYLON.TextureAssetTask = TextureAssetTask;
  83884. /**
  83885. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  83886. */
  83887. var CubeTextureAssetTask = /** @class */ (function (_super) {
  83888. __extends(CubeTextureAssetTask, _super);
  83889. /**
  83890. * Creates a new CubeTextureAssetTask
  83891. * @param name defines the name of the task
  83892. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83893. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83894. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83895. * @param files defines the explicit list of files (undefined by default)
  83896. */
  83897. function CubeTextureAssetTask(
  83898. /**
  83899. * Defines the name of the task
  83900. */
  83901. name,
  83902. /**
  83903. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83904. */
  83905. url,
  83906. /**
  83907. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83908. */
  83909. extensions,
  83910. /**
  83911. * Defines if mipmaps should not be generated (default is false)
  83912. */
  83913. noMipmap,
  83914. /**
  83915. * Defines the explicit list of files (undefined by default)
  83916. */
  83917. files) {
  83918. var _this = _super.call(this, name) || this;
  83919. _this.name = name;
  83920. _this.url = url;
  83921. _this.extensions = extensions;
  83922. _this.noMipmap = noMipmap;
  83923. _this.files = files;
  83924. return _this;
  83925. }
  83926. /**
  83927. * Execute the current task
  83928. * @param scene defines the scene where you want your assets to be loaded
  83929. * @param onSuccess is a callback called when the task is successfully executed
  83930. * @param onError is a callback called if an error occurs
  83931. */
  83932. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83933. var onload = function () {
  83934. onSuccess();
  83935. };
  83936. var onerror = function (message, exception) {
  83937. onError(message, exception);
  83938. };
  83939. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  83940. };
  83941. return CubeTextureAssetTask;
  83942. }(AbstractAssetTask));
  83943. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  83944. /**
  83945. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  83946. */
  83947. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  83948. __extends(HDRCubeTextureAssetTask, _super);
  83949. /**
  83950. * Creates a new HDRCubeTextureAssetTask object
  83951. * @param name defines the name of the task
  83952. * @param url defines the location of the file to load
  83953. * @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.
  83954. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83955. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83956. * @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)
  83957. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83958. */
  83959. function HDRCubeTextureAssetTask(
  83960. /**
  83961. * Defines the name of the task
  83962. */
  83963. name,
  83964. /**
  83965. * Defines the location of the file to load
  83966. */
  83967. url,
  83968. /**
  83969. * 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.
  83970. */
  83971. size,
  83972. /**
  83973. * Defines if mipmaps should not be generated (default is false)
  83974. */
  83975. noMipmap,
  83976. /**
  83977. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83978. */
  83979. generateHarmonics,
  83980. /**
  83981. * 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)
  83982. */
  83983. useInGammaSpace,
  83984. /**
  83985. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83986. */
  83987. usePMREMGenerator) {
  83988. if (noMipmap === void 0) { noMipmap = false; }
  83989. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83990. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  83991. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  83992. var _this = _super.call(this, name) || this;
  83993. _this.name = name;
  83994. _this.url = url;
  83995. _this.size = size;
  83996. _this.noMipmap = noMipmap;
  83997. _this.generateHarmonics = generateHarmonics;
  83998. _this.useInGammaSpace = useInGammaSpace;
  83999. _this.usePMREMGenerator = usePMREMGenerator;
  84000. return _this;
  84001. }
  84002. /**
  84003. * Execute the current task
  84004. * @param scene defines the scene where you want your assets to be loaded
  84005. * @param onSuccess is a callback called when the task is successfully executed
  84006. * @param onError is a callback called if an error occurs
  84007. */
  84008. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84009. var onload = function () {
  84010. onSuccess();
  84011. };
  84012. var onerror = function (message, exception) {
  84013. onError(message, exception);
  84014. };
  84015. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  84016. };
  84017. return HDRCubeTextureAssetTask;
  84018. }(AbstractAssetTask));
  84019. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  84020. /**
  84021. * This class can be used to easily import assets into a scene
  84022. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  84023. */
  84024. var AssetsManager = /** @class */ (function () {
  84025. /**
  84026. * Creates a new AssetsManager
  84027. * @param scene defines the scene to work on
  84028. */
  84029. function AssetsManager(scene) {
  84030. this._isLoading = false;
  84031. this._tasks = new Array();
  84032. this._waitingTasksCount = 0;
  84033. this._totalTasksCount = 0;
  84034. /**
  84035. * Observable called when all tasks are processed
  84036. */
  84037. this.onTaskSuccessObservable = new BABYLON.Observable();
  84038. /**
  84039. * Observable called when a task had an error
  84040. */
  84041. this.onTaskErrorObservable = new BABYLON.Observable();
  84042. /**
  84043. * Observable called when a task is successful
  84044. */
  84045. this.onTasksDoneObservable = new BABYLON.Observable();
  84046. /**
  84047. * Observable called when a task is done (whatever the result is)
  84048. */
  84049. this.onProgressObservable = new BABYLON.Observable();
  84050. /**
  84051. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  84052. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  84053. */
  84054. this.useDefaultLoadingScreen = true;
  84055. this._scene = scene;
  84056. }
  84057. /**
  84058. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  84059. * @param taskName defines the name of the new task
  84060. * @param meshesNames defines the name of meshes to load
  84061. * @param rootUrl defines the root url to use to locate files
  84062. * @param sceneFilename defines the filename of the scene file
  84063. * @returns a new {BABYLON.MeshAssetTask} object
  84064. */
  84065. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  84066. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  84067. this._tasks.push(task);
  84068. return task;
  84069. };
  84070. /**
  84071. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84072. * @param taskName defines the name of the new task
  84073. * @param url defines the url of the file to load
  84074. * @returns a new {BABYLON.TextFileAssetTask} object
  84075. */
  84076. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84077. var task = new TextFileAssetTask(taskName, url);
  84078. this._tasks.push(task);
  84079. return task;
  84080. };
  84081. /**
  84082. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84083. * @param taskName defines the name of the new task
  84084. * @param url defines the url of the file to load
  84085. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84086. */
  84087. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84088. var task = new BinaryFileAssetTask(taskName, url);
  84089. this._tasks.push(task);
  84090. return task;
  84091. };
  84092. /**
  84093. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84094. * @param taskName defines the name of the new task
  84095. * @param url defines the url of the file to load
  84096. * @returns a new {BABYLON.ImageAssetTask} object
  84097. */
  84098. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84099. var task = new ImageAssetTask(taskName, url);
  84100. this._tasks.push(task);
  84101. return task;
  84102. };
  84103. /**
  84104. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84105. * @param taskName defines the name of the new task
  84106. * @param url defines the url of the file to load
  84107. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84108. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84109. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84110. * @returns a new {BABYLON.TextureAssetTask} object
  84111. */
  84112. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84113. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84114. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84115. this._tasks.push(task);
  84116. return task;
  84117. };
  84118. /**
  84119. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84120. * @param taskName defines the name of the new task
  84121. * @param url defines the url of the file to load
  84122. * @param extensions defines the extension to use to load the cube map (can be null)
  84123. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84124. * @param files defines the list of files to load (can be null)
  84125. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84126. */
  84127. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84128. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84129. this._tasks.push(task);
  84130. return task;
  84131. };
  84132. /**
  84133. *
  84134. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84135. * @param taskName defines the name of the new task
  84136. * @param url defines the url of the file to load
  84137. * @param size defines the size you want for the cubemap (can be null)
  84138. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84139. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84140. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84141. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84142. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84143. */
  84144. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84145. if (noMipmap === void 0) { noMipmap = false; }
  84146. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84147. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84148. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84149. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84150. this._tasks.push(task);
  84151. return task;
  84152. };
  84153. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84154. var _this = this;
  84155. this._waitingTasksCount--;
  84156. try {
  84157. if (task.taskState === AssetTaskState.DONE) {
  84158. // Let's remove successfull tasks
  84159. BABYLON.Tools.SetImmediate(function () {
  84160. var index = _this._tasks.indexOf(task);
  84161. if (index > -1) {
  84162. _this._tasks.splice(index, 1);
  84163. }
  84164. });
  84165. }
  84166. if (this.onProgress) {
  84167. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84168. }
  84169. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84170. }
  84171. catch (e) {
  84172. BABYLON.Tools.Error("Error running progress callbacks.");
  84173. console.log(e);
  84174. }
  84175. if (this._waitingTasksCount === 0) {
  84176. try {
  84177. if (this.onFinish) {
  84178. this.onFinish(this._tasks);
  84179. }
  84180. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84181. }
  84182. catch (e) {
  84183. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84184. console.log(e);
  84185. }
  84186. this._isLoading = false;
  84187. this._scene.getEngine().hideLoadingUI();
  84188. }
  84189. };
  84190. AssetsManager.prototype._runTask = function (task) {
  84191. var _this = this;
  84192. var done = function () {
  84193. try {
  84194. if (_this.onTaskSuccess) {
  84195. _this.onTaskSuccess(task);
  84196. }
  84197. _this.onTaskSuccessObservable.notifyObservers(task);
  84198. _this._decreaseWaitingTasksCount(task);
  84199. }
  84200. catch (e) {
  84201. error("Error executing task success callbacks", e);
  84202. }
  84203. };
  84204. var error = function (message, exception) {
  84205. task._setErrorObject(message, exception);
  84206. if (_this.onTaskError) {
  84207. _this.onTaskError(task);
  84208. }
  84209. _this.onTaskErrorObservable.notifyObservers(task);
  84210. _this._decreaseWaitingTasksCount(task);
  84211. };
  84212. task.run(this._scene, done, error);
  84213. };
  84214. /**
  84215. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84216. * @return the current instance of the {BABYLON.AssetsManager}
  84217. */
  84218. AssetsManager.prototype.reset = function () {
  84219. this._isLoading = false;
  84220. this._tasks = new Array();
  84221. return this;
  84222. };
  84223. /**
  84224. * Start the loading process
  84225. * @return the current instance of the {BABYLON.AssetsManager}
  84226. */
  84227. AssetsManager.prototype.load = function () {
  84228. if (this._isLoading) {
  84229. return this;
  84230. }
  84231. this._isLoading = true;
  84232. this._waitingTasksCount = this._tasks.length;
  84233. this._totalTasksCount = this._tasks.length;
  84234. if (this._waitingTasksCount === 0) {
  84235. if (this.onFinish) {
  84236. this.onFinish(this._tasks);
  84237. }
  84238. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84239. return this;
  84240. }
  84241. if (this.useDefaultLoadingScreen) {
  84242. this._scene.getEngine().displayLoadingUI();
  84243. }
  84244. for (var index = 0; index < this._tasks.length; index++) {
  84245. var task = this._tasks[index];
  84246. this._runTask(task);
  84247. }
  84248. return this;
  84249. };
  84250. return AssetsManager;
  84251. }());
  84252. BABYLON.AssetsManager = AssetsManager;
  84253. })(BABYLON || (BABYLON = {}));
  84254. //# sourceMappingURL=babylon.assetsManager.js.map
  84255. var BABYLON;
  84256. (function (BABYLON) {
  84257. var serializedGeometries = [];
  84258. var serializeGeometry = function (geometry, serializationGeometries) {
  84259. if (serializedGeometries[geometry.id]) {
  84260. return;
  84261. }
  84262. if (geometry.doNotSerialize) {
  84263. return;
  84264. }
  84265. if (geometry instanceof BABYLON.BoxGeometry) {
  84266. serializationGeometries.boxes.push(geometry.serialize());
  84267. }
  84268. else if (geometry instanceof BABYLON.SphereGeometry) {
  84269. serializationGeometries.spheres.push(geometry.serialize());
  84270. }
  84271. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84272. serializationGeometries.cylinders.push(geometry.serialize());
  84273. }
  84274. else if (geometry instanceof BABYLON.TorusGeometry) {
  84275. serializationGeometries.toruses.push(geometry.serialize());
  84276. }
  84277. else if (geometry instanceof BABYLON.GroundGeometry) {
  84278. serializationGeometries.grounds.push(geometry.serialize());
  84279. }
  84280. else if (geometry instanceof BABYLON.Plane) {
  84281. serializationGeometries.planes.push(geometry.serialize());
  84282. }
  84283. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84284. serializationGeometries.torusKnots.push(geometry.serialize());
  84285. }
  84286. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84287. throw new Error("Unknown primitive type");
  84288. }
  84289. else {
  84290. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84291. }
  84292. serializedGeometries[geometry.id] = true;
  84293. };
  84294. var serializeMesh = function (mesh, serializationScene) {
  84295. var serializationObject = {};
  84296. // Geometry
  84297. var geometry = mesh._geometry;
  84298. if (geometry) {
  84299. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84300. // 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
  84301. serializeGeometry(geometry, serializationScene.geometries);
  84302. }
  84303. }
  84304. // Custom
  84305. if (mesh.serialize) {
  84306. mesh.serialize(serializationObject);
  84307. }
  84308. return serializationObject;
  84309. };
  84310. var finalizeSingleMesh = function (mesh, serializationObject) {
  84311. //only works if the mesh is already loaded
  84312. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84313. //serialize material
  84314. if (mesh.material) {
  84315. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84316. serializationObject.materials = serializationObject.materials || [];
  84317. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84318. serializationObject.materials.push(mesh.material.serialize());
  84319. }
  84320. }
  84321. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84322. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84323. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84324. serializationObject.multiMaterials.push(mesh.material.serialize());
  84325. }
  84326. }
  84327. }
  84328. //serialize geometry
  84329. var geometry = mesh._geometry;
  84330. if (geometry) {
  84331. if (!serializationObject.geometries) {
  84332. serializationObject.geometries = {};
  84333. serializationObject.geometries.boxes = [];
  84334. serializationObject.geometries.spheres = [];
  84335. serializationObject.geometries.cylinders = [];
  84336. serializationObject.geometries.toruses = [];
  84337. serializationObject.geometries.grounds = [];
  84338. serializationObject.geometries.planes = [];
  84339. serializationObject.geometries.torusKnots = [];
  84340. serializationObject.geometries.vertexData = [];
  84341. }
  84342. serializeGeometry(geometry, serializationObject.geometries);
  84343. }
  84344. // Skeletons
  84345. if (mesh.skeleton) {
  84346. serializationObject.skeletons = serializationObject.skeletons || [];
  84347. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84348. }
  84349. //serialize the actual mesh
  84350. serializationObject.meshes = serializationObject.meshes || [];
  84351. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84352. }
  84353. };
  84354. var SceneSerializer = /** @class */ (function () {
  84355. function SceneSerializer() {
  84356. }
  84357. SceneSerializer.ClearCache = function () {
  84358. serializedGeometries = [];
  84359. };
  84360. SceneSerializer.Serialize = function (scene) {
  84361. var serializationObject = {};
  84362. SceneSerializer.ClearCache();
  84363. // Scene
  84364. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84365. serializationObject.autoClear = scene.autoClear;
  84366. serializationObject.clearColor = scene.clearColor.asArray();
  84367. serializationObject.ambientColor = scene.ambientColor.asArray();
  84368. serializationObject.gravity = scene.gravity.asArray();
  84369. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84370. serializationObject.workerCollisions = scene.workerCollisions;
  84371. // Fog
  84372. if (scene.fogMode && scene.fogMode !== 0) {
  84373. serializationObject.fogMode = scene.fogMode;
  84374. serializationObject.fogColor = scene.fogColor.asArray();
  84375. serializationObject.fogStart = scene.fogStart;
  84376. serializationObject.fogEnd = scene.fogEnd;
  84377. serializationObject.fogDensity = scene.fogDensity;
  84378. }
  84379. //Physics
  84380. if (scene.isPhysicsEnabled()) {
  84381. var physicEngine = scene.getPhysicsEngine();
  84382. if (physicEngine) {
  84383. serializationObject.physicsEnabled = true;
  84384. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84385. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84386. }
  84387. }
  84388. // Metadata
  84389. if (scene.metadata) {
  84390. serializationObject.metadata = scene.metadata;
  84391. }
  84392. // Morph targets
  84393. serializationObject.morphTargetManagers = [];
  84394. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84395. var abstractMesh = _a[_i];
  84396. var manager = abstractMesh.morphTargetManager;
  84397. if (manager) {
  84398. serializationObject.morphTargetManagers.push(manager.serialize());
  84399. }
  84400. }
  84401. // Lights
  84402. serializationObject.lights = [];
  84403. var index;
  84404. var light;
  84405. for (index = 0; index < scene.lights.length; index++) {
  84406. light = scene.lights[index];
  84407. if (!light.doNotSerialize) {
  84408. serializationObject.lights.push(light.serialize());
  84409. }
  84410. }
  84411. // Cameras
  84412. serializationObject.cameras = [];
  84413. for (index = 0; index < scene.cameras.length; index++) {
  84414. var camera = scene.cameras[index];
  84415. if (!camera.doNotSerialize) {
  84416. serializationObject.cameras.push(camera.serialize());
  84417. }
  84418. }
  84419. if (scene.activeCamera) {
  84420. serializationObject.activeCameraID = scene.activeCamera.id;
  84421. }
  84422. // Animations
  84423. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84424. // Materials
  84425. serializationObject.materials = [];
  84426. serializationObject.multiMaterials = [];
  84427. var material;
  84428. for (index = 0; index < scene.materials.length; index++) {
  84429. material = scene.materials[index];
  84430. if (!material.doNotSerialize) {
  84431. serializationObject.materials.push(material.serialize());
  84432. }
  84433. }
  84434. // MultiMaterials
  84435. serializationObject.multiMaterials = [];
  84436. for (index = 0; index < scene.multiMaterials.length; index++) {
  84437. var multiMaterial = scene.multiMaterials[index];
  84438. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84439. }
  84440. // Environment texture
  84441. if (scene.environmentTexture) {
  84442. serializationObject.environmentTexture = scene.environmentTexture.name;
  84443. }
  84444. // Skeletons
  84445. serializationObject.skeletons = [];
  84446. for (index = 0; index < scene.skeletons.length; index++) {
  84447. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  84448. }
  84449. // Transform nodes
  84450. serializationObject.transformNodes = [];
  84451. for (index = 0; index < scene.transformNodes.length; index++) {
  84452. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84453. }
  84454. // Geometries
  84455. serializationObject.geometries = {};
  84456. serializationObject.geometries.boxes = [];
  84457. serializationObject.geometries.spheres = [];
  84458. serializationObject.geometries.cylinders = [];
  84459. serializationObject.geometries.toruses = [];
  84460. serializationObject.geometries.grounds = [];
  84461. serializationObject.geometries.planes = [];
  84462. serializationObject.geometries.torusKnots = [];
  84463. serializationObject.geometries.vertexData = [];
  84464. serializedGeometries = [];
  84465. var geometries = scene.getGeometries();
  84466. for (index = 0; index < geometries.length; index++) {
  84467. var geometry = geometries[index];
  84468. if (geometry.isReady()) {
  84469. serializeGeometry(geometry, serializationObject.geometries);
  84470. }
  84471. }
  84472. // Meshes
  84473. serializationObject.meshes = [];
  84474. for (index = 0; index < scene.meshes.length; index++) {
  84475. var abstractMesh = scene.meshes[index];
  84476. if (abstractMesh instanceof BABYLON.Mesh) {
  84477. var mesh = abstractMesh;
  84478. if (!mesh.doNotSerialize) {
  84479. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84480. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84481. }
  84482. }
  84483. }
  84484. }
  84485. // Particles Systems
  84486. serializationObject.particleSystems = [];
  84487. for (index = 0; index < scene.particleSystems.length; index++) {
  84488. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84489. }
  84490. // Lens flares
  84491. serializationObject.lensFlareSystems = [];
  84492. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84493. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84494. }
  84495. // Shadows
  84496. serializationObject.shadowGenerators = [];
  84497. for (index = 0; index < scene.lights.length; index++) {
  84498. light = scene.lights[index];
  84499. var shadowGenerator = light.getShadowGenerator();
  84500. if (shadowGenerator) {
  84501. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84502. }
  84503. }
  84504. // Action Manager
  84505. if (scene.actionManager) {
  84506. serializationObject.actions = scene.actionManager.serialize("scene");
  84507. }
  84508. // Audio
  84509. serializationObject.sounds = [];
  84510. for (index = 0; index < scene.soundTracks.length; index++) {
  84511. var soundtrack = scene.soundTracks[index];
  84512. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84513. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84514. }
  84515. }
  84516. return serializationObject;
  84517. };
  84518. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84519. if (withParents === void 0) { withParents = false; }
  84520. if (withChildren === void 0) { withChildren = false; }
  84521. var serializationObject = {};
  84522. SceneSerializer.ClearCache();
  84523. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84524. if (withParents || withChildren) {
  84525. //deliberate for loop! not for each, appended should be processed as well.
  84526. for (var i = 0; i < toSerialize.length; ++i) {
  84527. if (withChildren) {
  84528. toSerialize[i].getDescendants().forEach(function (node) {
  84529. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84530. toSerialize.push(node);
  84531. }
  84532. });
  84533. }
  84534. //make sure the array doesn't contain the object already
  84535. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84536. toSerialize.push(toSerialize[i].parent);
  84537. }
  84538. }
  84539. }
  84540. toSerialize.forEach(function (mesh) {
  84541. finalizeSingleMesh(mesh, serializationObject);
  84542. });
  84543. return serializationObject;
  84544. };
  84545. return SceneSerializer;
  84546. }());
  84547. BABYLON.SceneSerializer = SceneSerializer;
  84548. })(BABYLON || (BABYLON = {}));
  84549. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84550. var BABYLON;
  84551. (function (BABYLON) {
  84552. var ReflectionProbe = /** @class */ (function () {
  84553. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84554. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84555. var _this = this;
  84556. this.name = name;
  84557. this._viewMatrix = BABYLON.Matrix.Identity();
  84558. this._target = BABYLON.Vector3.Zero();
  84559. this._add = BABYLON.Vector3.Zero();
  84560. this.invertYAxis = false;
  84561. this.position = BABYLON.Vector3.Zero();
  84562. this._scene = scene;
  84563. this._scene.reflectionProbes.push(this);
  84564. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84565. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84566. switch (faceIndex) {
  84567. case 0:
  84568. _this._add.copyFromFloats(1, 0, 0);
  84569. break;
  84570. case 1:
  84571. _this._add.copyFromFloats(-1, 0, 0);
  84572. break;
  84573. case 2:
  84574. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84575. break;
  84576. case 3:
  84577. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84578. break;
  84579. case 4:
  84580. _this._add.copyFromFloats(0, 0, 1);
  84581. break;
  84582. case 5:
  84583. _this._add.copyFromFloats(0, 0, -1);
  84584. break;
  84585. }
  84586. if (_this._attachedMesh) {
  84587. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84588. }
  84589. _this.position.addToRef(_this._add, _this._target);
  84590. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84591. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84592. scene._forcedViewPosition = _this.position;
  84593. });
  84594. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84595. scene._forcedViewPosition = null;
  84596. scene.updateTransformMatrix(true);
  84597. });
  84598. if (scene.activeCamera) {
  84599. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84600. }
  84601. }
  84602. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84603. get: function () {
  84604. return this._renderTargetTexture.samples;
  84605. },
  84606. set: function (value) {
  84607. this._renderTargetTexture.samples = value;
  84608. },
  84609. enumerable: true,
  84610. configurable: true
  84611. });
  84612. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84613. get: function () {
  84614. return this._renderTargetTexture.refreshRate;
  84615. },
  84616. set: function (value) {
  84617. this._renderTargetTexture.refreshRate = value;
  84618. },
  84619. enumerable: true,
  84620. configurable: true
  84621. });
  84622. ReflectionProbe.prototype.getScene = function () {
  84623. return this._scene;
  84624. };
  84625. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84626. get: function () {
  84627. return this._renderTargetTexture;
  84628. },
  84629. enumerable: true,
  84630. configurable: true
  84631. });
  84632. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84633. get: function () {
  84634. return this._renderTargetTexture.renderList;
  84635. },
  84636. enumerable: true,
  84637. configurable: true
  84638. });
  84639. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84640. this._attachedMesh = mesh;
  84641. };
  84642. /**
  84643. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84644. *
  84645. * @param renderingGroupId The rendering group id corresponding to its index
  84646. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84647. */
  84648. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84649. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84650. };
  84651. ReflectionProbe.prototype.dispose = function () {
  84652. var index = this._scene.reflectionProbes.indexOf(this);
  84653. if (index !== -1) {
  84654. // Remove from the scene if found
  84655. this._scene.reflectionProbes.splice(index, 1);
  84656. }
  84657. if (this._renderTargetTexture) {
  84658. this._renderTargetTexture.dispose();
  84659. this._renderTargetTexture = null;
  84660. }
  84661. };
  84662. return ReflectionProbe;
  84663. }());
  84664. BABYLON.ReflectionProbe = ReflectionProbe;
  84665. })(BABYLON || (BABYLON = {}));
  84666. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84667. var BABYLON;
  84668. (function (BABYLON) {
  84669. var Layer = /** @class */ (function () {
  84670. function Layer(name, imgUrl, scene, isBackground, color) {
  84671. this.name = name;
  84672. this.scale = new BABYLON.Vector2(1, 1);
  84673. this.offset = new BABYLON.Vector2(0, 0);
  84674. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84675. this.layerMask = 0x0FFFFFFF;
  84676. this._vertexBuffers = {};
  84677. // Events
  84678. /**
  84679. * An event triggered when the layer is disposed.
  84680. * @type {BABYLON.Observable}
  84681. */
  84682. this.onDisposeObservable = new BABYLON.Observable();
  84683. /**
  84684. * An event triggered before rendering the scene
  84685. * @type {BABYLON.Observable}
  84686. */
  84687. this.onBeforeRenderObservable = new BABYLON.Observable();
  84688. /**
  84689. * An event triggered after rendering the scene
  84690. * @type {BABYLON.Observable}
  84691. */
  84692. this.onAfterRenderObservable = new BABYLON.Observable();
  84693. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84694. this.isBackground = isBackground === undefined ? true : isBackground;
  84695. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84696. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84697. this._scene.layers.push(this);
  84698. var engine = this._scene.getEngine();
  84699. // VBO
  84700. var vertices = [];
  84701. vertices.push(1, 1);
  84702. vertices.push(-1, 1);
  84703. vertices.push(-1, -1);
  84704. vertices.push(1, -1);
  84705. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84706. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84707. this._createIndexBuffer();
  84708. // Effects
  84709. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84710. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84711. }
  84712. Object.defineProperty(Layer.prototype, "onDispose", {
  84713. set: function (callback) {
  84714. if (this._onDisposeObserver) {
  84715. this.onDisposeObservable.remove(this._onDisposeObserver);
  84716. }
  84717. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84718. },
  84719. enumerable: true,
  84720. configurable: true
  84721. });
  84722. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84723. set: function (callback) {
  84724. if (this._onBeforeRenderObserver) {
  84725. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84726. }
  84727. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84728. },
  84729. enumerable: true,
  84730. configurable: true
  84731. });
  84732. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84733. set: function (callback) {
  84734. if (this._onAfterRenderObserver) {
  84735. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84736. }
  84737. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84738. },
  84739. enumerable: true,
  84740. configurable: true
  84741. });
  84742. Layer.prototype._createIndexBuffer = function () {
  84743. var engine = this._scene.getEngine();
  84744. // Indices
  84745. var indices = [];
  84746. indices.push(0);
  84747. indices.push(1);
  84748. indices.push(2);
  84749. indices.push(0);
  84750. indices.push(2);
  84751. indices.push(3);
  84752. this._indexBuffer = engine.createIndexBuffer(indices);
  84753. };
  84754. Layer.prototype._rebuild = function () {
  84755. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84756. if (vb) {
  84757. vb._rebuild();
  84758. }
  84759. this._createIndexBuffer();
  84760. };
  84761. Layer.prototype.render = function () {
  84762. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84763. // Check
  84764. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  84765. return;
  84766. var engine = this._scene.getEngine();
  84767. this.onBeforeRenderObservable.notifyObservers(this);
  84768. // Render
  84769. engine.enableEffect(currentEffect);
  84770. engine.setState(false);
  84771. // Texture
  84772. currentEffect.setTexture("textureSampler", this.texture);
  84773. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  84774. // Color
  84775. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  84776. // Scale / offset
  84777. currentEffect.setVector2("offset", this.offset);
  84778. currentEffect.setVector2("scale", this.scale);
  84779. // VBOs
  84780. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84781. // Draw order
  84782. if (!this.alphaTest) {
  84783. engine.setAlphaMode(this.alphaBlendingMode);
  84784. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84785. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84786. }
  84787. else {
  84788. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84789. }
  84790. this.onAfterRenderObservable.notifyObservers(this);
  84791. };
  84792. Layer.prototype.dispose = function () {
  84793. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84794. if (vertexBuffer) {
  84795. vertexBuffer.dispose();
  84796. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84797. }
  84798. if (this._indexBuffer) {
  84799. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84800. this._indexBuffer = null;
  84801. }
  84802. if (this.texture) {
  84803. this.texture.dispose();
  84804. this.texture = null;
  84805. }
  84806. // Remove from scene
  84807. var index = this._scene.layers.indexOf(this);
  84808. this._scene.layers.splice(index, 1);
  84809. // Callback
  84810. this.onDisposeObservable.notifyObservers(this);
  84811. this.onDisposeObservable.clear();
  84812. this.onAfterRenderObservable.clear();
  84813. this.onBeforeRenderObservable.clear();
  84814. };
  84815. return Layer;
  84816. }());
  84817. BABYLON.Layer = Layer;
  84818. })(BABYLON || (BABYLON = {}));
  84819. //# sourceMappingURL=babylon.layer.js.map
  84820. var BABYLON;
  84821. (function (BABYLON) {
  84822. var TextureTools = /** @class */ (function () {
  84823. function TextureTools() {
  84824. }
  84825. /**
  84826. * Uses the GPU to create a copy texture rescaled at a given size
  84827. * @param texture Texture to copy from
  84828. * @param width Desired width
  84829. * @param height Desired height
  84830. * @return Generated texture
  84831. */
  84832. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  84833. if (useBilinearMode === void 0) { useBilinearMode = true; }
  84834. var scene = texture.getScene();
  84835. var engine = scene.getEngine();
  84836. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  84837. rtt.wrapU = texture.wrapU;
  84838. rtt.wrapV = texture.wrapV;
  84839. rtt.uOffset = texture.uOffset;
  84840. rtt.vOffset = texture.vOffset;
  84841. rtt.uScale = texture.uScale;
  84842. rtt.vScale = texture.vScale;
  84843. rtt.uAng = texture.uAng;
  84844. rtt.vAng = texture.vAng;
  84845. rtt.wAng = texture.wAng;
  84846. rtt.coordinatesIndex = texture.coordinatesIndex;
  84847. rtt.level = texture.level;
  84848. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  84849. rtt._texture.isReady = false;
  84850. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84851. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84852. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84853. passPostProcess.getEffect().executeWhenCompiled(function () {
  84854. passPostProcess.onApply = function (effect) {
  84855. effect.setTexture("textureSampler", texture);
  84856. };
  84857. var internalTexture = rtt.getInternalTexture();
  84858. if (internalTexture) {
  84859. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  84860. engine.unBindFramebuffer(internalTexture);
  84861. rtt.disposeFramebufferObjects();
  84862. passPostProcess.dispose();
  84863. internalTexture.isReady = true;
  84864. }
  84865. });
  84866. return rtt;
  84867. };
  84868. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  84869. if (!scene._environmentBRDFTexture) {
  84870. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84871. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84872. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84873. scene._environmentBRDFTexture = texture;
  84874. }
  84875. return scene._environmentBRDFTexture;
  84876. };
  84877. 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=";
  84878. return TextureTools;
  84879. }());
  84880. BABYLON.TextureTools = TextureTools;
  84881. })(BABYLON || (BABYLON = {}));
  84882. //# sourceMappingURL=babylon.textureTools.js.map
  84883. var BABYLON;
  84884. (function (BABYLON) {
  84885. var FramingBehavior = /** @class */ (function () {
  84886. function FramingBehavior() {
  84887. this._mode = FramingBehavior.FitFrustumSidesMode;
  84888. this._radiusScale = 1.0;
  84889. this._positionScale = 0.5;
  84890. this._defaultElevation = 0.3;
  84891. this._elevationReturnTime = 1500;
  84892. this._elevationReturnWaitTime = 1000;
  84893. this._zoomStopsAnimation = false;
  84894. this._framingTime = 1500;
  84895. this._isPointerDown = false;
  84896. this._lastInteractionTime = -Infinity;
  84897. // Framing control
  84898. this._animatables = new Array();
  84899. this._betaIsAnimating = false;
  84900. }
  84901. Object.defineProperty(FramingBehavior.prototype, "name", {
  84902. get: function () {
  84903. return "Framing";
  84904. },
  84905. enumerable: true,
  84906. configurable: true
  84907. });
  84908. Object.defineProperty(FramingBehavior.prototype, "mode", {
  84909. /**
  84910. * Gets current mode used by the behavior.
  84911. */
  84912. get: function () {
  84913. return this._mode;
  84914. },
  84915. /**
  84916. * Sets the current mode used by the behavior
  84917. */
  84918. set: function (mode) {
  84919. this._mode = mode;
  84920. },
  84921. enumerable: true,
  84922. configurable: true
  84923. });
  84924. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  84925. /**
  84926. * Gets the scale applied to the radius
  84927. */
  84928. get: function () {
  84929. return this._radiusScale;
  84930. },
  84931. /**
  84932. * Sets the scale applied to the radius (1 by default)
  84933. */
  84934. set: function (radius) {
  84935. this._radiusScale = radius;
  84936. },
  84937. enumerable: true,
  84938. configurable: true
  84939. });
  84940. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  84941. /**
  84942. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84943. */
  84944. get: function () {
  84945. return this._positionScale;
  84946. },
  84947. /**
  84948. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84949. */
  84950. set: function (scale) {
  84951. this._positionScale = scale;
  84952. },
  84953. enumerable: true,
  84954. configurable: true
  84955. });
  84956. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  84957. /**
  84958. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84959. * behaviour is triggered, in radians.
  84960. */
  84961. get: function () {
  84962. return this._defaultElevation;
  84963. },
  84964. /**
  84965. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84966. * behaviour is triggered, in radians.
  84967. */
  84968. set: function (elevation) {
  84969. this._defaultElevation = elevation;
  84970. },
  84971. enumerable: true,
  84972. configurable: true
  84973. });
  84974. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  84975. /**
  84976. * Gets the time (in milliseconds) taken to return to the default beta position.
  84977. * Negative value indicates camera should not return to default.
  84978. */
  84979. get: function () {
  84980. return this._elevationReturnTime;
  84981. },
  84982. /**
  84983. * Sets the time (in milliseconds) taken to return to the default beta position.
  84984. * Negative value indicates camera should not return to default.
  84985. */
  84986. set: function (speed) {
  84987. this._elevationReturnTime = speed;
  84988. },
  84989. enumerable: true,
  84990. configurable: true
  84991. });
  84992. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  84993. /**
  84994. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84995. */
  84996. get: function () {
  84997. return this._elevationReturnWaitTime;
  84998. },
  84999. /**
  85000. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85001. */
  85002. set: function (time) {
  85003. this._elevationReturnWaitTime = time;
  85004. },
  85005. enumerable: true,
  85006. configurable: true
  85007. });
  85008. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  85009. /**
  85010. * Gets the flag that indicates if user zooming should stop animation.
  85011. */
  85012. get: function () {
  85013. return this._zoomStopsAnimation;
  85014. },
  85015. /**
  85016. * Sets the flag that indicates if user zooming should stop animation.
  85017. */
  85018. set: function (flag) {
  85019. this._zoomStopsAnimation = flag;
  85020. },
  85021. enumerable: true,
  85022. configurable: true
  85023. });
  85024. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  85025. /**
  85026. * Gets the transition time when framing the mesh, in milliseconds
  85027. */
  85028. get: function () {
  85029. return this._framingTime;
  85030. },
  85031. /**
  85032. * Sets the transition time when framing the mesh, in milliseconds
  85033. */
  85034. set: function (time) {
  85035. this._framingTime = time;
  85036. },
  85037. enumerable: true,
  85038. configurable: true
  85039. });
  85040. FramingBehavior.prototype.init = function () {
  85041. // Do notihng
  85042. };
  85043. FramingBehavior.prototype.attach = function (camera) {
  85044. var _this = this;
  85045. this._attachedCamera = camera;
  85046. var scene = this._attachedCamera.getScene();
  85047. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  85048. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85049. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85050. _this._isPointerDown = true;
  85051. return;
  85052. }
  85053. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85054. _this._isPointerDown = false;
  85055. }
  85056. });
  85057. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85058. if (mesh) {
  85059. _this.zoomOnMesh(mesh);
  85060. }
  85061. });
  85062. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85063. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85064. _this._applyUserInteraction();
  85065. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  85066. // back to the default position after a given timeout
  85067. _this._maintainCameraAboveGround();
  85068. });
  85069. };
  85070. FramingBehavior.prototype.detach = function () {
  85071. if (!this._attachedCamera) {
  85072. return;
  85073. }
  85074. var scene = this._attachedCamera.getScene();
  85075. if (this._onPrePointerObservableObserver) {
  85076. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85077. }
  85078. if (this._onAfterCheckInputsObserver) {
  85079. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85080. }
  85081. if (this._onMeshTargetChangedObserver) {
  85082. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85083. }
  85084. this._attachedCamera = null;
  85085. };
  85086. /**
  85087. * Targets the given mesh and updates zoom level accordingly.
  85088. * @param mesh The mesh to target.
  85089. * @param radius Optional. If a cached radius position already exists, overrides default.
  85090. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85091. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85092. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85093. */
  85094. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85095. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85096. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85097. mesh.computeWorldMatrix(true);
  85098. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85099. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85100. };
  85101. /**
  85102. * Targets the given mesh with its children and updates zoom level accordingly.
  85103. * @param mesh The mesh to target.
  85104. * @param radius Optional. If a cached radius position already exists, overrides default.
  85105. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85106. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85107. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85108. */
  85109. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85110. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85111. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85112. mesh.computeWorldMatrix(true);
  85113. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85114. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85115. };
  85116. /**
  85117. * Targets the given meshes with their children and updates zoom level accordingly.
  85118. * @param meshes The mesh to target.
  85119. * @param radius Optional. If a cached radius position already exists, overrides default.
  85120. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85121. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85122. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85123. */
  85124. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85125. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85126. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85127. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85128. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85129. for (var i = 0; i < meshes.length; i++) {
  85130. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85131. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85132. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85133. }
  85134. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85135. };
  85136. /**
  85137. * Targets the given mesh and updates zoom level accordingly.
  85138. * @param mesh The mesh to target.
  85139. * @param radius Optional. If a cached radius position already exists, overrides default.
  85140. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85141. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85142. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85143. */
  85144. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85145. var _this = this;
  85146. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85147. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85148. var zoomTarget;
  85149. if (!this._attachedCamera) {
  85150. return;
  85151. }
  85152. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85153. var bottom = minimumWorld.y;
  85154. var top = maximumWorld.y;
  85155. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85156. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85157. if (focusOnOriginXZ) {
  85158. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85159. }
  85160. else {
  85161. var centerWorld = minimumWorld.add(radiusWorld);
  85162. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85163. }
  85164. if (!this._vectorTransition) {
  85165. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85166. }
  85167. this._betaIsAnimating = true;
  85168. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85169. if (animatable) {
  85170. this._animatables.push(animatable);
  85171. }
  85172. // sets the radius and lower radius bounds
  85173. // Small delta ensures camera is not always at lower zoom limit.
  85174. var radius = 0;
  85175. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85176. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85177. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85178. radius = position;
  85179. }
  85180. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85181. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85182. if (this._attachedCamera.lowerRadiusLimit === null) {
  85183. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85184. }
  85185. }
  85186. // Set sensibilities
  85187. var extend = maximumWorld.subtract(minimumWorld).length();
  85188. this._attachedCamera.panningSensibility = 5000 / extend;
  85189. this._attachedCamera.wheelPrecision = 100 / radius;
  85190. // transition to new radius
  85191. if (!this._radiusTransition) {
  85192. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85193. }
  85194. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85195. if (onAnimationEnd) {
  85196. onAnimationEnd();
  85197. }
  85198. if (_this._attachedCamera) {
  85199. _this._attachedCamera.storeState();
  85200. }
  85201. });
  85202. if (animatable) {
  85203. this._animatables.push(animatable);
  85204. }
  85205. };
  85206. /**
  85207. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85208. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85209. * frustum width.
  85210. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85211. * to fully enclose the mesh in the viewing frustum.
  85212. */
  85213. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85214. var size = maximumWorld.subtract(minimumWorld);
  85215. var boxVectorGlobalDiagonal = size.length();
  85216. var frustumSlope = this._getFrustumSlope();
  85217. // Formula for setting distance
  85218. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85219. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85220. // Horizon distance
  85221. var radius = radiusWithoutFraming * this._radiusScale;
  85222. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85223. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85224. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85225. var camera = this._attachedCamera;
  85226. if (!camera) {
  85227. return 0;
  85228. }
  85229. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85230. // Don't exceed the requested limit
  85231. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85232. }
  85233. // Don't exceed the upper radius limit
  85234. if (camera.upperRadiusLimit) {
  85235. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85236. }
  85237. return distance;
  85238. };
  85239. /**
  85240. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85241. * is automatically returned to its default position (expected to be above ground plane).
  85242. */
  85243. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85244. var _this = this;
  85245. if (this._elevationReturnTime < 0) {
  85246. return;
  85247. }
  85248. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85249. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85250. var limitBeta = Math.PI * 0.5;
  85251. // Bring the camera back up if below the ground plane
  85252. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85253. this._betaIsAnimating = true;
  85254. //Transition to new position
  85255. this.stopAllAnimations();
  85256. if (!this._betaTransition) {
  85257. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85258. }
  85259. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85260. _this._clearAnimationLocks();
  85261. _this.stopAllAnimations();
  85262. });
  85263. if (animatabe) {
  85264. this._animatables.push(animatabe);
  85265. }
  85266. }
  85267. };
  85268. /**
  85269. * Returns the frustum slope based on the canvas ratio and camera FOV
  85270. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85271. */
  85272. FramingBehavior.prototype._getFrustumSlope = function () {
  85273. // Calculate the viewport ratio
  85274. // Aspect Ratio is Height/Width.
  85275. var camera = this._attachedCamera;
  85276. if (!camera) {
  85277. return BABYLON.Vector2.Zero();
  85278. }
  85279. var engine = camera.getScene().getEngine();
  85280. var aspectRatio = engine.getAspectRatio(camera);
  85281. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85282. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85283. var frustumSlopeY = Math.tan(camera.fov / 2);
  85284. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85285. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85286. // along the forward vector.
  85287. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85288. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85289. };
  85290. /**
  85291. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85292. */
  85293. FramingBehavior.prototype._clearAnimationLocks = function () {
  85294. this._betaIsAnimating = false;
  85295. };
  85296. /**
  85297. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85298. */
  85299. FramingBehavior.prototype._applyUserInteraction = function () {
  85300. if (this.isUserIsMoving) {
  85301. this._lastInteractionTime = BABYLON.Tools.Now;
  85302. this.stopAllAnimations();
  85303. this._clearAnimationLocks();
  85304. }
  85305. };
  85306. /**
  85307. * Stops and removes all animations that have been applied to the camera
  85308. */
  85309. FramingBehavior.prototype.stopAllAnimations = function () {
  85310. if (this._attachedCamera) {
  85311. this._attachedCamera.animations = [];
  85312. }
  85313. while (this._animatables.length) {
  85314. if (this._animatables[0]) {
  85315. this._animatables[0].onAnimationEnd = null;
  85316. this._animatables[0].stop();
  85317. }
  85318. this._animatables.shift();
  85319. }
  85320. };
  85321. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85322. /**
  85323. * Gets a value indicating if the user is moving the camera
  85324. */
  85325. get: function () {
  85326. if (!this._attachedCamera) {
  85327. return false;
  85328. }
  85329. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85330. this._attachedCamera.inertialBetaOffset !== 0 ||
  85331. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85332. this._attachedCamera.inertialPanningX !== 0 ||
  85333. this._attachedCamera.inertialPanningY !== 0 ||
  85334. this._isPointerDown;
  85335. },
  85336. enumerable: true,
  85337. configurable: true
  85338. });
  85339. /**
  85340. * The easing function used by animations
  85341. */
  85342. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85343. /**
  85344. * The easing mode used by animations
  85345. */
  85346. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85347. // Statics
  85348. /**
  85349. * The camera can move all the way towards the mesh.
  85350. */
  85351. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85352. /**
  85353. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85354. */
  85355. FramingBehavior.FitFrustumSidesMode = 1;
  85356. return FramingBehavior;
  85357. }());
  85358. BABYLON.FramingBehavior = FramingBehavior;
  85359. })(BABYLON || (BABYLON = {}));
  85360. //# sourceMappingURL=babylon.framingBehavior.js.map
  85361. var BABYLON;
  85362. (function (BABYLON) {
  85363. /**
  85364. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85365. */
  85366. var BouncingBehavior = /** @class */ (function () {
  85367. function BouncingBehavior() {
  85368. /**
  85369. * The duration of the animation, in milliseconds
  85370. */
  85371. this.transitionDuration = 450;
  85372. /**
  85373. * Length of the distance animated by the transition when lower radius is reached
  85374. */
  85375. this.lowerRadiusTransitionRange = 2;
  85376. /**
  85377. * Length of the distance animated by the transition when upper radius is reached
  85378. */
  85379. this.upperRadiusTransitionRange = -2;
  85380. this._autoTransitionRange = false;
  85381. // Animations
  85382. this._radiusIsAnimating = false;
  85383. this._radiusBounceTransition = null;
  85384. this._animatables = new Array();
  85385. }
  85386. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85387. get: function () {
  85388. return "Bouncing";
  85389. },
  85390. enumerable: true,
  85391. configurable: true
  85392. });
  85393. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85394. /**
  85395. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85396. */
  85397. get: function () {
  85398. return this._autoTransitionRange;
  85399. },
  85400. /**
  85401. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85402. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85403. */
  85404. set: function (value) {
  85405. var _this = this;
  85406. if (this._autoTransitionRange === value) {
  85407. return;
  85408. }
  85409. this._autoTransitionRange = value;
  85410. var camera = this._attachedCamera;
  85411. if (!camera) {
  85412. return;
  85413. }
  85414. if (value) {
  85415. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85416. if (!mesh) {
  85417. return;
  85418. }
  85419. mesh.computeWorldMatrix(true);
  85420. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85421. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85422. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85423. });
  85424. }
  85425. else if (this._onMeshTargetChangedObserver) {
  85426. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85427. }
  85428. },
  85429. enumerable: true,
  85430. configurable: true
  85431. });
  85432. BouncingBehavior.prototype.init = function () {
  85433. // Do notihng
  85434. };
  85435. BouncingBehavior.prototype.attach = function (camera) {
  85436. var _this = this;
  85437. this._attachedCamera = camera;
  85438. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85439. if (!_this._attachedCamera) {
  85440. return;
  85441. }
  85442. // Add the bounce animation to the lower radius limit
  85443. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85444. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85445. }
  85446. // Add the bounce animation to the upper radius limit
  85447. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85448. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85449. }
  85450. });
  85451. };
  85452. BouncingBehavior.prototype.detach = function () {
  85453. if (!this._attachedCamera) {
  85454. return;
  85455. }
  85456. if (this._onAfterCheckInputsObserver) {
  85457. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85458. }
  85459. if (this._onMeshTargetChangedObserver) {
  85460. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85461. }
  85462. this._attachedCamera = null;
  85463. };
  85464. /**
  85465. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85466. * @param radiusLimit The limit to check against.
  85467. * @return Bool to indicate if at limit.
  85468. */
  85469. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85470. if (!this._attachedCamera) {
  85471. return false;
  85472. }
  85473. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85474. return true;
  85475. }
  85476. return false;
  85477. };
  85478. /**
  85479. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85480. * @param radiusDelta The delta by which to animate to. Can be negative.
  85481. */
  85482. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85483. var _this = this;
  85484. if (!this._attachedCamera) {
  85485. return;
  85486. }
  85487. if (!this._radiusBounceTransition) {
  85488. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85489. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85490. }
  85491. // Prevent zoom until bounce has completed
  85492. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85493. this._attachedCamera.wheelPrecision = Infinity;
  85494. this._attachedCamera.inertialRadiusOffset = 0;
  85495. // Animate to the radius limit
  85496. this.stopAllAnimations();
  85497. this._radiusIsAnimating = true;
  85498. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85499. if (animatable) {
  85500. this._animatables.push(animatable);
  85501. }
  85502. };
  85503. /**
  85504. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85505. */
  85506. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85507. this._radiusIsAnimating = false;
  85508. if (this._attachedCamera) {
  85509. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85510. }
  85511. };
  85512. /**
  85513. * Stops and removes all animations that have been applied to the camera
  85514. */
  85515. BouncingBehavior.prototype.stopAllAnimations = function () {
  85516. if (this._attachedCamera) {
  85517. this._attachedCamera.animations = [];
  85518. }
  85519. while (this._animatables.length) {
  85520. this._animatables[0].onAnimationEnd = null;
  85521. this._animatables[0].stop();
  85522. this._animatables.shift();
  85523. }
  85524. };
  85525. /**
  85526. * The easing function used by animations
  85527. */
  85528. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85529. /**
  85530. * The easing mode used by animations
  85531. */
  85532. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85533. return BouncingBehavior;
  85534. }());
  85535. BABYLON.BouncingBehavior = BouncingBehavior;
  85536. })(BABYLON || (BABYLON = {}));
  85537. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85538. var BABYLON;
  85539. (function (BABYLON) {
  85540. var AutoRotationBehavior = /** @class */ (function () {
  85541. function AutoRotationBehavior() {
  85542. this._zoomStopsAnimation = false;
  85543. this._idleRotationSpeed = 0.05;
  85544. this._idleRotationWaitTime = 2000;
  85545. this._idleRotationSpinupTime = 2000;
  85546. this._isPointerDown = false;
  85547. this._lastFrameTime = null;
  85548. this._lastInteractionTime = -Infinity;
  85549. this._cameraRotationSpeed = 0;
  85550. this._lastFrameRadius = 0;
  85551. }
  85552. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85553. get: function () {
  85554. return "AutoRotation";
  85555. },
  85556. enumerable: true,
  85557. configurable: true
  85558. });
  85559. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85560. /**
  85561. * Gets the flag that indicates if user zooming should stop animation.
  85562. */
  85563. get: function () {
  85564. return this._zoomStopsAnimation;
  85565. },
  85566. /**
  85567. * Sets the flag that indicates if user zooming should stop animation.
  85568. */
  85569. set: function (flag) {
  85570. this._zoomStopsAnimation = flag;
  85571. },
  85572. enumerable: true,
  85573. configurable: true
  85574. });
  85575. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85576. /**
  85577. * Gets the default speed at which the camera rotates around the model.
  85578. */
  85579. get: function () {
  85580. return this._idleRotationSpeed;
  85581. },
  85582. /**
  85583. * Sets the default speed at which the camera rotates around the model.
  85584. */
  85585. set: function (speed) {
  85586. this._idleRotationSpeed = speed;
  85587. },
  85588. enumerable: true,
  85589. configurable: true
  85590. });
  85591. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85592. /**
  85593. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85594. */
  85595. get: function () {
  85596. return this._idleRotationWaitTime;
  85597. },
  85598. /**
  85599. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85600. */
  85601. set: function (time) {
  85602. this._idleRotationWaitTime = time;
  85603. },
  85604. enumerable: true,
  85605. configurable: true
  85606. });
  85607. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85608. /**
  85609. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85610. */
  85611. get: function () {
  85612. return this._idleRotationSpinupTime;
  85613. },
  85614. /**
  85615. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85616. */
  85617. set: function (time) {
  85618. this._idleRotationSpinupTime = time;
  85619. },
  85620. enumerable: true,
  85621. configurable: true
  85622. });
  85623. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85624. /**
  85625. * Gets a value indicating if the camera is currently rotating because of this behavior
  85626. */
  85627. get: function () {
  85628. return Math.abs(this._cameraRotationSpeed) > 0;
  85629. },
  85630. enumerable: true,
  85631. configurable: true
  85632. });
  85633. AutoRotationBehavior.prototype.init = function () {
  85634. // Do notihng
  85635. };
  85636. AutoRotationBehavior.prototype.attach = function (camera) {
  85637. var _this = this;
  85638. this._attachedCamera = camera;
  85639. var scene = this._attachedCamera.getScene();
  85640. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85641. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85642. _this._isPointerDown = true;
  85643. return;
  85644. }
  85645. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85646. _this._isPointerDown = false;
  85647. }
  85648. });
  85649. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85650. var now = BABYLON.Tools.Now;
  85651. var dt = 0;
  85652. if (_this._lastFrameTime != null) {
  85653. dt = now - _this._lastFrameTime;
  85654. }
  85655. _this._lastFrameTime = now;
  85656. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85657. _this._applyUserInteraction();
  85658. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85659. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85660. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85661. // Step camera rotation by rotation speed
  85662. if (_this._attachedCamera) {
  85663. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85664. }
  85665. });
  85666. };
  85667. AutoRotationBehavior.prototype.detach = function () {
  85668. if (!this._attachedCamera) {
  85669. return;
  85670. }
  85671. var scene = this._attachedCamera.getScene();
  85672. if (this._onPrePointerObservableObserver) {
  85673. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85674. }
  85675. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85676. this._attachedCamera = null;
  85677. };
  85678. /**
  85679. * Returns true if user is scrolling.
  85680. * @return true if user is scrolling.
  85681. */
  85682. AutoRotationBehavior.prototype._userIsZooming = function () {
  85683. if (!this._attachedCamera) {
  85684. return false;
  85685. }
  85686. return this._attachedCamera.inertialRadiusOffset !== 0;
  85687. };
  85688. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85689. if (!this._attachedCamera) {
  85690. return false;
  85691. }
  85692. var zoomHasHitLimit = false;
  85693. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85694. zoomHasHitLimit = true;
  85695. }
  85696. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85697. this._lastFrameRadius = this._attachedCamera.radius;
  85698. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85699. };
  85700. /**
  85701. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85702. */
  85703. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85704. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85705. this._lastInteractionTime = BABYLON.Tools.Now;
  85706. }
  85707. };
  85708. // Tools
  85709. AutoRotationBehavior.prototype._userIsMoving = function () {
  85710. if (!this._attachedCamera) {
  85711. return false;
  85712. }
  85713. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85714. this._attachedCamera.inertialBetaOffset !== 0 ||
  85715. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85716. this._attachedCamera.inertialPanningX !== 0 ||
  85717. this._attachedCamera.inertialPanningY !== 0 ||
  85718. this._isPointerDown;
  85719. };
  85720. return AutoRotationBehavior;
  85721. }());
  85722. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85723. })(BABYLON || (BABYLON = {}));
  85724. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85725. var BABYLON;
  85726. (function (BABYLON) {
  85727. /**
  85728. * This class can be used to get instrumentation data from a Babylon engine
  85729. */
  85730. var EngineInstrumentation = /** @class */ (function () {
  85731. function EngineInstrumentation(engine) {
  85732. this.engine = engine;
  85733. this._captureGPUFrameTime = false;
  85734. this._gpuFrameTime = new BABYLON.PerfCounter();
  85735. this._captureShaderCompilationTime = false;
  85736. this._shaderCompilationTime = new BABYLON.PerfCounter();
  85737. // Observers
  85738. this._onBeginFrameObserver = null;
  85739. this._onEndFrameObserver = null;
  85740. this._onBeforeShaderCompilationObserver = null;
  85741. this._onAfterShaderCompilationObserver = null;
  85742. }
  85743. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  85744. // Properties
  85745. /**
  85746. * Gets the perf counter used for GPU frame time
  85747. */
  85748. get: function () {
  85749. return this._gpuFrameTime;
  85750. },
  85751. enumerable: true,
  85752. configurable: true
  85753. });
  85754. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  85755. /**
  85756. * Gets the GPU frame time capture status
  85757. */
  85758. get: function () {
  85759. return this._captureGPUFrameTime;
  85760. },
  85761. /**
  85762. * Enable or disable the GPU frame time capture
  85763. */
  85764. set: function (value) {
  85765. var _this = this;
  85766. if (value === this._captureGPUFrameTime) {
  85767. return;
  85768. }
  85769. this._captureGPUFrameTime = value;
  85770. if (value) {
  85771. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  85772. if (!_this._gpuFrameTimeToken) {
  85773. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  85774. }
  85775. });
  85776. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  85777. if (!_this._gpuFrameTimeToken) {
  85778. return;
  85779. }
  85780. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  85781. if (time > -1) {
  85782. _this._gpuFrameTimeToken = null;
  85783. _this._gpuFrameTime.fetchNewFrame();
  85784. _this._gpuFrameTime.addCount(time, true);
  85785. }
  85786. });
  85787. }
  85788. else {
  85789. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85790. this._onBeginFrameObserver = null;
  85791. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85792. this._onEndFrameObserver = null;
  85793. }
  85794. },
  85795. enumerable: true,
  85796. configurable: true
  85797. });
  85798. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  85799. /**
  85800. * Gets the perf counter used for shader compilation time
  85801. */
  85802. get: function () {
  85803. return this._shaderCompilationTime;
  85804. },
  85805. enumerable: true,
  85806. configurable: true
  85807. });
  85808. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  85809. /**
  85810. * Gets the shader compilation time capture status
  85811. */
  85812. get: function () {
  85813. return this._captureShaderCompilationTime;
  85814. },
  85815. /**
  85816. * Enable or disable the shader compilation time capture
  85817. */
  85818. set: function (value) {
  85819. var _this = this;
  85820. if (value === this._captureShaderCompilationTime) {
  85821. return;
  85822. }
  85823. this._captureShaderCompilationTime = value;
  85824. if (value) {
  85825. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  85826. _this._shaderCompilationTime.fetchNewFrame();
  85827. _this._shaderCompilationTime.beginMonitoring();
  85828. });
  85829. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  85830. _this._shaderCompilationTime.endMonitoring();
  85831. });
  85832. }
  85833. else {
  85834. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85835. this._onBeforeShaderCompilationObserver = null;
  85836. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85837. this._onAfterShaderCompilationObserver = null;
  85838. }
  85839. },
  85840. enumerable: true,
  85841. configurable: true
  85842. });
  85843. EngineInstrumentation.prototype.dispose = function () {
  85844. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85845. this._onBeginFrameObserver = null;
  85846. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85847. this._onEndFrameObserver = null;
  85848. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85849. this._onBeforeShaderCompilationObserver = null;
  85850. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85851. this._onAfterShaderCompilationObserver = null;
  85852. this.engine = null;
  85853. };
  85854. return EngineInstrumentation;
  85855. }());
  85856. BABYLON.EngineInstrumentation = EngineInstrumentation;
  85857. })(BABYLON || (BABYLON = {}));
  85858. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  85859. var BABYLON;
  85860. (function (BABYLON) {
  85861. /**
  85862. * This class can be used to get instrumentation data from a Babylon engine
  85863. */
  85864. var SceneInstrumentation = /** @class */ (function () {
  85865. function SceneInstrumentation(scene) {
  85866. var _this = this;
  85867. this.scene = scene;
  85868. this._captureActiveMeshesEvaluationTime = false;
  85869. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  85870. this._captureRenderTargetsRenderTime = false;
  85871. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  85872. this._captureFrameTime = false;
  85873. this._frameTime = new BABYLON.PerfCounter();
  85874. this._captureRenderTime = false;
  85875. this._renderTime = new BABYLON.PerfCounter();
  85876. this._captureInterFrameTime = false;
  85877. this._interFrameTime = new BABYLON.PerfCounter();
  85878. this._captureParticlesRenderTime = false;
  85879. this._particlesRenderTime = new BABYLON.PerfCounter();
  85880. this._captureSpritesRenderTime = false;
  85881. this._spritesRenderTime = new BABYLON.PerfCounter();
  85882. this._capturePhysicsTime = false;
  85883. this._physicsTime = new BABYLON.PerfCounter();
  85884. this._captureAnimationsTime = false;
  85885. this._animationsTime = new BABYLON.PerfCounter();
  85886. // Observers
  85887. this._onBeforeActiveMeshesEvaluationObserver = null;
  85888. this._onAfterActiveMeshesEvaluationObserver = null;
  85889. this._onBeforeRenderTargetsRenderObserver = null;
  85890. this._onAfterRenderTargetsRenderObserver = null;
  85891. this._onAfterRenderObserver = null;
  85892. this._onBeforeDrawPhaseObserver = null;
  85893. this._onAfterDrawPhaseObserver = null;
  85894. this._onBeforeAnimationsObserver = null;
  85895. this._onBeforeParticlesRenderingObserver = null;
  85896. this._onAfterParticlesRenderingObserver = null;
  85897. this._onBeforeSpritesRenderingObserver = null;
  85898. this._onAfterSpritesRenderingObserver = null;
  85899. this._onBeforePhysicsObserver = null;
  85900. this._onAfterPhysicsObserver = null;
  85901. this._onAfterAnimationsObserver = null;
  85902. // Before render
  85903. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  85904. if (_this._captureActiveMeshesEvaluationTime) {
  85905. _this._activeMeshesEvaluationTime.fetchNewFrame();
  85906. }
  85907. if (_this._captureRenderTargetsRenderTime) {
  85908. _this._renderTargetsRenderTime.fetchNewFrame();
  85909. }
  85910. if (_this._captureFrameTime) {
  85911. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  85912. _this._frameTime.beginMonitoring();
  85913. }
  85914. if (_this._captureInterFrameTime) {
  85915. _this._interFrameTime.endMonitoring();
  85916. }
  85917. if (_this._captureParticlesRenderTime) {
  85918. _this._particlesRenderTime.fetchNewFrame();
  85919. }
  85920. if (_this._captureSpritesRenderTime) {
  85921. _this._spritesRenderTime.fetchNewFrame();
  85922. }
  85923. if (_this._captureAnimationsTime) {
  85924. _this._animationsTime.beginMonitoring();
  85925. }
  85926. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  85927. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  85928. });
  85929. // After render
  85930. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  85931. if (_this._captureFrameTime) {
  85932. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  85933. _this._frameTime.endMonitoring();
  85934. }
  85935. if (_this._captureRenderTime) {
  85936. _this._renderTime.endMonitoring(false);
  85937. }
  85938. if (_this._captureInterFrameTime) {
  85939. _this._interFrameTime.beginMonitoring();
  85940. }
  85941. });
  85942. }
  85943. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  85944. // Properties
  85945. /**
  85946. * Gets the perf counter used for active meshes evaluation time
  85947. */
  85948. get: function () {
  85949. return this._activeMeshesEvaluationTime;
  85950. },
  85951. enumerable: true,
  85952. configurable: true
  85953. });
  85954. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  85955. /**
  85956. * Gets the active meshes evaluation time capture status
  85957. */
  85958. get: function () {
  85959. return this._captureActiveMeshesEvaluationTime;
  85960. },
  85961. /**
  85962. * Enable or disable the active meshes evaluation time capture
  85963. */
  85964. set: function (value) {
  85965. var _this = this;
  85966. if (value === this._captureActiveMeshesEvaluationTime) {
  85967. return;
  85968. }
  85969. this._captureActiveMeshesEvaluationTime = value;
  85970. if (value) {
  85971. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  85972. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  85973. _this._activeMeshesEvaluationTime.beginMonitoring();
  85974. });
  85975. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  85976. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  85977. _this._activeMeshesEvaluationTime.endMonitoring();
  85978. });
  85979. }
  85980. else {
  85981. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  85982. this._onBeforeActiveMeshesEvaluationObserver = null;
  85983. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  85984. this._onAfterActiveMeshesEvaluationObserver = null;
  85985. }
  85986. },
  85987. enumerable: true,
  85988. configurable: true
  85989. });
  85990. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  85991. /**
  85992. * Gets the perf counter used for render targets render time
  85993. */
  85994. get: function () {
  85995. return this._renderTargetsRenderTime;
  85996. },
  85997. enumerable: true,
  85998. configurable: true
  85999. });
  86000. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  86001. /**
  86002. * Gets the render targets render time capture status
  86003. */
  86004. get: function () {
  86005. return this._captureRenderTargetsRenderTime;
  86006. },
  86007. /**
  86008. * Enable or disable the render targets render time capture
  86009. */
  86010. set: function (value) {
  86011. var _this = this;
  86012. if (value === this._captureRenderTargetsRenderTime) {
  86013. return;
  86014. }
  86015. this._captureRenderTargetsRenderTime = value;
  86016. if (value) {
  86017. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  86018. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  86019. _this._renderTargetsRenderTime.beginMonitoring();
  86020. });
  86021. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  86022. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  86023. _this._renderTargetsRenderTime.endMonitoring(false);
  86024. });
  86025. }
  86026. else {
  86027. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86028. this._onBeforeRenderTargetsRenderObserver = null;
  86029. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86030. this._onAfterRenderTargetsRenderObserver = null;
  86031. }
  86032. },
  86033. enumerable: true,
  86034. configurable: true
  86035. });
  86036. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  86037. /**
  86038. * Gets the perf counter used for particles render time
  86039. */
  86040. get: function () {
  86041. return this._particlesRenderTime;
  86042. },
  86043. enumerable: true,
  86044. configurable: true
  86045. });
  86046. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  86047. /**
  86048. * Gets the particles render time capture status
  86049. */
  86050. get: function () {
  86051. return this._captureParticlesRenderTime;
  86052. },
  86053. /**
  86054. * Enable or disable the particles render time capture
  86055. */
  86056. set: function (value) {
  86057. var _this = this;
  86058. if (value === this._captureParticlesRenderTime) {
  86059. return;
  86060. }
  86061. this._captureParticlesRenderTime = value;
  86062. if (value) {
  86063. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  86064. BABYLON.Tools.StartPerformanceCounter("Particles");
  86065. _this._particlesRenderTime.beginMonitoring();
  86066. });
  86067. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  86068. BABYLON.Tools.EndPerformanceCounter("Particles");
  86069. _this._particlesRenderTime.endMonitoring(false);
  86070. });
  86071. }
  86072. else {
  86073. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86074. this._onBeforeParticlesRenderingObserver = null;
  86075. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86076. this._onAfterParticlesRenderingObserver = null;
  86077. }
  86078. },
  86079. enumerable: true,
  86080. configurable: true
  86081. });
  86082. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  86083. /**
  86084. * Gets the perf counter used for sprites render time
  86085. */
  86086. get: function () {
  86087. return this._spritesRenderTime;
  86088. },
  86089. enumerable: true,
  86090. configurable: true
  86091. });
  86092. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86093. /**
  86094. * Gets the sprites render time capture status
  86095. */
  86096. get: function () {
  86097. return this._captureSpritesRenderTime;
  86098. },
  86099. /**
  86100. * Enable or disable the sprites render time capture
  86101. */
  86102. set: function (value) {
  86103. var _this = this;
  86104. if (value === this._captureSpritesRenderTime) {
  86105. return;
  86106. }
  86107. this._captureSpritesRenderTime = value;
  86108. if (value) {
  86109. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86110. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86111. _this._spritesRenderTime.beginMonitoring();
  86112. });
  86113. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86114. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86115. _this._spritesRenderTime.endMonitoring(false);
  86116. });
  86117. }
  86118. else {
  86119. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86120. this._onBeforeSpritesRenderingObserver = null;
  86121. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86122. this._onAfterSpritesRenderingObserver = null;
  86123. }
  86124. },
  86125. enumerable: true,
  86126. configurable: true
  86127. });
  86128. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86129. /**
  86130. * Gets the perf counter used for physics time
  86131. */
  86132. get: function () {
  86133. return this._physicsTime;
  86134. },
  86135. enumerable: true,
  86136. configurable: true
  86137. });
  86138. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86139. /**
  86140. * Gets the physics time capture status
  86141. */
  86142. get: function () {
  86143. return this._capturePhysicsTime;
  86144. },
  86145. /**
  86146. * Enable or disable the physics time capture
  86147. */
  86148. set: function (value) {
  86149. var _this = this;
  86150. if (value === this._capturePhysicsTime) {
  86151. return;
  86152. }
  86153. this._capturePhysicsTime = value;
  86154. if (value) {
  86155. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86156. BABYLON.Tools.StartPerformanceCounter("Physics");
  86157. _this._physicsTime.beginMonitoring();
  86158. });
  86159. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86160. BABYLON.Tools.EndPerformanceCounter("Physics");
  86161. _this._physicsTime.endMonitoring();
  86162. });
  86163. }
  86164. else {
  86165. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86166. this._onBeforePhysicsObserver = null;
  86167. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86168. this._onAfterPhysicsObserver = null;
  86169. }
  86170. },
  86171. enumerable: true,
  86172. configurable: true
  86173. });
  86174. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86175. /**
  86176. * Gets the perf counter used for animations time
  86177. */
  86178. get: function () {
  86179. return this._animationsTime;
  86180. },
  86181. enumerable: true,
  86182. configurable: true
  86183. });
  86184. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86185. /**
  86186. * Gets the animations time capture status
  86187. */
  86188. get: function () {
  86189. return this._captureAnimationsTime;
  86190. },
  86191. /**
  86192. * Enable or disable the animations time capture
  86193. */
  86194. set: function (value) {
  86195. var _this = this;
  86196. if (value === this._captureAnimationsTime) {
  86197. return;
  86198. }
  86199. this._captureAnimationsTime = value;
  86200. if (value) {
  86201. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86202. _this._animationsTime.endMonitoring();
  86203. });
  86204. }
  86205. else {
  86206. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86207. this._onAfterAnimationsObserver = null;
  86208. }
  86209. },
  86210. enumerable: true,
  86211. configurable: true
  86212. });
  86213. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86214. /**
  86215. * Gets the perf counter used for frame time capture
  86216. */
  86217. get: function () {
  86218. return this._frameTime;
  86219. },
  86220. enumerable: true,
  86221. configurable: true
  86222. });
  86223. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86224. /**
  86225. * Gets the frame time capture status
  86226. */
  86227. get: function () {
  86228. return this._captureFrameTime;
  86229. },
  86230. /**
  86231. * Enable or disable the frame time capture
  86232. */
  86233. set: function (value) {
  86234. this._captureFrameTime = value;
  86235. },
  86236. enumerable: true,
  86237. configurable: true
  86238. });
  86239. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86240. /**
  86241. * Gets the perf counter used for inter-frames time capture
  86242. */
  86243. get: function () {
  86244. return this._interFrameTime;
  86245. },
  86246. enumerable: true,
  86247. configurable: true
  86248. });
  86249. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86250. /**
  86251. * Gets the inter-frames time capture status
  86252. */
  86253. get: function () {
  86254. return this._captureInterFrameTime;
  86255. },
  86256. /**
  86257. * Enable or disable the inter-frames time capture
  86258. */
  86259. set: function (value) {
  86260. this._captureInterFrameTime = value;
  86261. },
  86262. enumerable: true,
  86263. configurable: true
  86264. });
  86265. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86266. /**
  86267. * Gets the perf counter used for render time capture
  86268. */
  86269. get: function () {
  86270. return this._renderTime;
  86271. },
  86272. enumerable: true,
  86273. configurable: true
  86274. });
  86275. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86276. /**
  86277. * Gets the render time capture status
  86278. */
  86279. get: function () {
  86280. return this._captureRenderTime;
  86281. },
  86282. /**
  86283. * Enable or disable the render time capture
  86284. */
  86285. set: function (value) {
  86286. var _this = this;
  86287. if (value === this._captureRenderTime) {
  86288. return;
  86289. }
  86290. this._captureRenderTime = value;
  86291. if (value) {
  86292. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86293. _this._renderTime.beginMonitoring();
  86294. BABYLON.Tools.StartPerformanceCounter("Main render");
  86295. });
  86296. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86297. _this._renderTime.endMonitoring(false);
  86298. BABYLON.Tools.EndPerformanceCounter("Main render");
  86299. });
  86300. }
  86301. else {
  86302. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86303. this._onBeforeDrawPhaseObserver = null;
  86304. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86305. this._onAfterDrawPhaseObserver = null;
  86306. }
  86307. },
  86308. enumerable: true,
  86309. configurable: true
  86310. });
  86311. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86312. /**
  86313. * Gets the perf counter used for draw calls
  86314. */
  86315. get: function () {
  86316. return this.scene.getEngine()._drawCalls;
  86317. },
  86318. enumerable: true,
  86319. configurable: true
  86320. });
  86321. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86322. /**
  86323. * Gets the perf counter used for texture collisions
  86324. */
  86325. get: function () {
  86326. return this.scene.getEngine()._textureCollisions;
  86327. },
  86328. enumerable: true,
  86329. configurable: true
  86330. });
  86331. SceneInstrumentation.prototype.dispose = function () {
  86332. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86333. this._onAfterRenderObserver = null;
  86334. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86335. this._onBeforeActiveMeshesEvaluationObserver = null;
  86336. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86337. this._onAfterActiveMeshesEvaluationObserver = null;
  86338. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86339. this._onBeforeRenderTargetsRenderObserver = null;
  86340. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86341. this._onAfterRenderTargetsRenderObserver = null;
  86342. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86343. this._onBeforeAnimationsObserver = null;
  86344. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86345. this._onBeforeParticlesRenderingObserver = null;
  86346. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86347. this._onAfterParticlesRenderingObserver = null;
  86348. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86349. this._onBeforeSpritesRenderingObserver = null;
  86350. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86351. this._onAfterSpritesRenderingObserver = null;
  86352. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86353. this._onBeforeDrawPhaseObserver = null;
  86354. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86355. this._onAfterDrawPhaseObserver = null;
  86356. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86357. this._onBeforePhysicsObserver = null;
  86358. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86359. this._onAfterPhysicsObserver = null;
  86360. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86361. this._onAfterAnimationsObserver = null;
  86362. this.scene = null;
  86363. };
  86364. return SceneInstrumentation;
  86365. }());
  86366. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86367. })(BABYLON || (BABYLON = {}));
  86368. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86369. var BABYLON;
  86370. (function (BABYLON) {
  86371. var _TimeToken = /** @class */ (function () {
  86372. function _TimeToken() {
  86373. this._timeElapsedQueryEnded = false;
  86374. }
  86375. return _TimeToken;
  86376. }());
  86377. BABYLON._TimeToken = _TimeToken;
  86378. })(BABYLON || (BABYLON = {}));
  86379. //# sourceMappingURL=babylon.timeToken.js.map
  86380. var BABYLON;
  86381. (function (BABYLON) {
  86382. /**
  86383. * Background material defines definition.
  86384. * @ignore Mainly internal Use
  86385. */
  86386. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86387. __extends(BackgroundMaterialDefines, _super);
  86388. /**
  86389. * Constructor of the defines.
  86390. */
  86391. function BackgroundMaterialDefines() {
  86392. var _this = _super.call(this) || this;
  86393. /**
  86394. * True if the diffuse texture is in use.
  86395. */
  86396. _this.DIFFUSE = false;
  86397. /**
  86398. * The direct UV channel to use.
  86399. */
  86400. _this.DIFFUSEDIRECTUV = 0;
  86401. /**
  86402. * True if the diffuse texture is in gamma space.
  86403. */
  86404. _this.GAMMADIFFUSE = false;
  86405. /**
  86406. * True if the diffuse texture has opacity in the alpha channel.
  86407. */
  86408. _this.DIFFUSEHASALPHA = false;
  86409. /**
  86410. * True if you want the material to fade to transparent at grazing angle.
  86411. */
  86412. _this.OPACITYFRESNEL = false;
  86413. /**
  86414. * True if an extra blur needs to be added in the reflection.
  86415. */
  86416. _this.REFLECTIONBLUR = false;
  86417. /**
  86418. * True if you want the material to fade to reflection at grazing angle.
  86419. */
  86420. _this.REFLECTIONFRESNEL = false;
  86421. /**
  86422. * True if you want the material to falloff as far as you move away from the scene center.
  86423. */
  86424. _this.REFLECTIONFALLOFF = false;
  86425. /**
  86426. * False if the current Webgl implementation does not support the texture lod extension.
  86427. */
  86428. _this.TEXTURELODSUPPORT = false;
  86429. /**
  86430. * True to ensure the data are premultiplied.
  86431. */
  86432. _this.PREMULTIPLYALPHA = false;
  86433. /**
  86434. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86435. */
  86436. _this.USERGBCOLOR = false;
  86437. /**
  86438. * True to add noise in order to reduce the banding effect.
  86439. */
  86440. _this.NOISE = false;
  86441. // Image Processing Configuration.
  86442. _this.IMAGEPROCESSING = false;
  86443. _this.VIGNETTE = false;
  86444. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86445. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86446. _this.TONEMAPPING = false;
  86447. _this.CONTRAST = false;
  86448. _this.COLORCURVES = false;
  86449. _this.COLORGRADING = false;
  86450. _this.COLORGRADING3D = false;
  86451. _this.SAMPLER3DGREENDEPTH = false;
  86452. _this.SAMPLER3DBGRMAP = false;
  86453. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86454. _this.EXPOSURE = false;
  86455. // Reflection.
  86456. _this.REFLECTION = false;
  86457. _this.REFLECTIONMAP_3D = false;
  86458. _this.REFLECTIONMAP_SPHERICAL = false;
  86459. _this.REFLECTIONMAP_PLANAR = false;
  86460. _this.REFLECTIONMAP_CUBIC = false;
  86461. _this.REFLECTIONMAP_PROJECTION = false;
  86462. _this.REFLECTIONMAP_SKYBOX = false;
  86463. _this.REFLECTIONMAP_EXPLICIT = false;
  86464. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86465. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86466. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86467. _this.INVERTCUBICMAP = false;
  86468. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86469. _this.LODINREFLECTIONALPHA = false;
  86470. _this.GAMMAREFLECTION = false;
  86471. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86472. // Default BJS.
  86473. _this.MAINUV1 = false;
  86474. _this.MAINUV2 = false;
  86475. _this.UV1 = false;
  86476. _this.UV2 = false;
  86477. _this.CLIPPLANE = false;
  86478. _this.POINTSIZE = false;
  86479. _this.FOG = false;
  86480. _this.NORMAL = false;
  86481. _this.NUM_BONE_INFLUENCERS = 0;
  86482. _this.BonesPerMesh = 0;
  86483. _this.INSTANCES = false;
  86484. _this.SHADOWFLOAT = false;
  86485. _this.rebuild();
  86486. return _this;
  86487. }
  86488. return BackgroundMaterialDefines;
  86489. }(BABYLON.MaterialDefines));
  86490. /**
  86491. * Background material used to create an efficient environement around your scene.
  86492. */
  86493. var BackgroundMaterial = /** @class */ (function (_super) {
  86494. __extends(BackgroundMaterial, _super);
  86495. /**
  86496. * Instantiates a Background Material in the given scene
  86497. * @param name The friendly name of the material
  86498. * @param scene The scene to add the material to
  86499. */
  86500. function BackgroundMaterial(name, scene) {
  86501. var _this = _super.call(this, name, scene) || this;
  86502. /**
  86503. * Key light Color (multiply against the R channel of the environement texture)
  86504. */
  86505. _this.primaryColor = BABYLON.Color3.White();
  86506. /**
  86507. * Key light Level (allowing HDR output of the background)
  86508. */
  86509. _this.primaryLevel = 1;
  86510. /**
  86511. * Secondary light Color (multiply against the G channel of the environement texture)
  86512. */
  86513. _this.secondaryColor = BABYLON.Color3.Gray();
  86514. /**
  86515. * Secondary light Level (allowing HDR output of the background)
  86516. */
  86517. _this.secondaryLevel = 1;
  86518. /**
  86519. * Tertiary light Color (multiply against the B channel of the environement texture)
  86520. */
  86521. _this.tertiaryColor = BABYLON.Color3.Black();
  86522. /**
  86523. * Tertiary light Level (allowing HDR output of the background)
  86524. */
  86525. _this.tertiaryLevel = 1;
  86526. /**
  86527. * Reflection Texture used in the material.
  86528. * Should be author in a specific way for the best result (refer to the documentation).
  86529. */
  86530. _this.reflectionTexture = null;
  86531. /**
  86532. * Reflection Texture level of blur.
  86533. *
  86534. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86535. * texture twice.
  86536. */
  86537. _this.reflectionBlur = 0;
  86538. /**
  86539. * Diffuse Texture used in the material.
  86540. * Should be author in a specific way for the best result (refer to the documentation).
  86541. */
  86542. _this.diffuseTexture = null;
  86543. _this._shadowLights = null;
  86544. /**
  86545. * Specify the list of lights casting shadow on the material.
  86546. * All scene shadow lights will be included if null.
  86547. */
  86548. _this.shadowLights = null;
  86549. /**
  86550. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86551. * soft lighting on the background.
  86552. */
  86553. _this.shadowBlurScale = 1;
  86554. /**
  86555. * Helps adjusting the shadow to a softer level if required.
  86556. * 0 means black shadows and 1 means no shadows.
  86557. */
  86558. _this.shadowLevel = 0;
  86559. /**
  86560. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86561. * It is usually zero but might be interesting to modify according to your setup.
  86562. */
  86563. _this.sceneCenter = BABYLON.Vector3.Zero();
  86564. /**
  86565. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86566. * This helps ensuring a nice transition when the camera goes under the ground.
  86567. */
  86568. _this.opacityFresnel = true;
  86569. /**
  86570. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86571. * This helps adding a mirror texture on the ground.
  86572. */
  86573. _this.reflectionFresnel = false;
  86574. /**
  86575. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86576. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86577. */
  86578. _this.reflectionFalloffDistance = 0.0;
  86579. /**
  86580. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86581. */
  86582. _this.reflectionAmount = 1.0;
  86583. /**
  86584. * This specifies the weight of the reflection at grazing angle.
  86585. */
  86586. _this.reflectionReflectance0 = 0.05;
  86587. /**
  86588. * This specifies the weight of the reflection at a perpendicular point of view.
  86589. */
  86590. _this.reflectionReflectance90 = 0.5;
  86591. /**
  86592. * Helps to directly use the maps channels instead of their level.
  86593. */
  86594. _this.useRGBColor = true;
  86595. /**
  86596. * This helps reducing the banding effect that could occur on the background.
  86597. */
  86598. _this.enableNoise = false;
  86599. _this._fovMultiplier = 1.0;
  86600. /**
  86601. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86602. * @type {boolean}
  86603. */
  86604. _this.useEquirectangularFOV = false;
  86605. _this._maxSimultaneousLights = 4;
  86606. /**
  86607. * Number of Simultaneous lights allowed on the material.
  86608. */
  86609. _this.maxSimultaneousLights = 4;
  86610. /**
  86611. * Keep track of the image processing observer to allow dispose and replace.
  86612. */
  86613. _this._imageProcessingObserver = null;
  86614. // Temp values kept as cache in the material.
  86615. _this._renderTargets = new BABYLON.SmartArray(16);
  86616. _this._reflectionControls = BABYLON.Vector4.Zero();
  86617. // Setup the default processing configuration to the scene.
  86618. _this._attachImageProcessingConfiguration(null);
  86619. _this.getRenderTargetTextures = function () {
  86620. _this._renderTargets.reset();
  86621. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86622. _this._renderTargets.push(_this._diffuseTexture);
  86623. }
  86624. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86625. _this._renderTargets.push(_this._reflectionTexture);
  86626. }
  86627. return _this._renderTargets;
  86628. };
  86629. return _this;
  86630. }
  86631. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86632. /**
  86633. * Sets the reflection reflectance fresnel values according to the default standard
  86634. * empirically know to work well :-)
  86635. */
  86636. set: function (value) {
  86637. var reflectionWeight = value;
  86638. if (reflectionWeight < 0.5) {
  86639. reflectionWeight = reflectionWeight * 2.0;
  86640. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86641. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86642. }
  86643. else {
  86644. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86645. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86646. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86647. }
  86648. },
  86649. enumerable: true,
  86650. configurable: true
  86651. });
  86652. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86653. /**
  86654. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86655. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86656. * Recommended to be keep at 1.0 except for special cases.
  86657. */
  86658. get: function () {
  86659. return this._fovMultiplier;
  86660. },
  86661. set: function (value) {
  86662. if (isNaN(value)) {
  86663. value = 1.0;
  86664. }
  86665. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86666. },
  86667. enumerable: true,
  86668. configurable: true
  86669. });
  86670. /**
  86671. * Attaches a new image processing configuration to the PBR Material.
  86672. * @param configuration (if null the scene configuration will be use)
  86673. */
  86674. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86675. var _this = this;
  86676. if (configuration === this._imageProcessingConfiguration) {
  86677. return;
  86678. }
  86679. // Detaches observer.
  86680. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86681. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86682. }
  86683. // Pick the scene configuration if needed.
  86684. if (!configuration) {
  86685. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86686. }
  86687. else {
  86688. this._imageProcessingConfiguration = configuration;
  86689. }
  86690. // Attaches observer.
  86691. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86692. _this._markAllSubMeshesAsImageProcessingDirty();
  86693. });
  86694. };
  86695. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86696. /**
  86697. * Gets the image processing configuration used either in this material.
  86698. */
  86699. get: function () {
  86700. return this._imageProcessingConfiguration;
  86701. },
  86702. /**
  86703. * Sets the Default image processing configuration used either in the this material.
  86704. *
  86705. * If sets to null, the scene one is in use.
  86706. */
  86707. set: function (value) {
  86708. this._attachImageProcessingConfiguration(value);
  86709. // Ensure the effect will be rebuilt.
  86710. this._markAllSubMeshesAsTexturesDirty();
  86711. },
  86712. enumerable: true,
  86713. configurable: true
  86714. });
  86715. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  86716. /**
  86717. * Gets wether the color curves effect is enabled.
  86718. */
  86719. get: function () {
  86720. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86721. },
  86722. /**
  86723. * Sets wether the color curves effect is enabled.
  86724. */
  86725. set: function (value) {
  86726. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86727. },
  86728. enumerable: true,
  86729. configurable: true
  86730. });
  86731. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  86732. /**
  86733. * Gets wether the color grading effect is enabled.
  86734. */
  86735. get: function () {
  86736. return this.imageProcessingConfiguration.colorGradingEnabled;
  86737. },
  86738. /**
  86739. * Gets wether the color grading effect is enabled.
  86740. */
  86741. set: function (value) {
  86742. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86743. },
  86744. enumerable: true,
  86745. configurable: true
  86746. });
  86747. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  86748. /**
  86749. * Gets wether tonemapping is enabled or not.
  86750. */
  86751. get: function () {
  86752. return this._imageProcessingConfiguration.toneMappingEnabled;
  86753. },
  86754. /**
  86755. * Sets wether tonemapping is enabled or not
  86756. */
  86757. set: function (value) {
  86758. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86759. },
  86760. enumerable: true,
  86761. configurable: true
  86762. });
  86763. ;
  86764. ;
  86765. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  86766. /**
  86767. * The camera exposure used on this material.
  86768. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86769. * This corresponds to a photographic exposure.
  86770. */
  86771. get: function () {
  86772. return this._imageProcessingConfiguration.exposure;
  86773. },
  86774. /**
  86775. * The camera exposure used on this material.
  86776. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86777. * This corresponds to a photographic exposure.
  86778. */
  86779. set: function (value) {
  86780. this._imageProcessingConfiguration.exposure = value;
  86781. },
  86782. enumerable: true,
  86783. configurable: true
  86784. });
  86785. ;
  86786. ;
  86787. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  86788. /**
  86789. * Gets The camera contrast used on this material.
  86790. */
  86791. get: function () {
  86792. return this._imageProcessingConfiguration.contrast;
  86793. },
  86794. /**
  86795. * Sets The camera contrast used on this material.
  86796. */
  86797. set: function (value) {
  86798. this._imageProcessingConfiguration.contrast = value;
  86799. },
  86800. enumerable: true,
  86801. configurable: true
  86802. });
  86803. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  86804. /**
  86805. * Gets the Color Grading 2D Lookup Texture.
  86806. */
  86807. get: function () {
  86808. return this._imageProcessingConfiguration.colorGradingTexture;
  86809. },
  86810. /**
  86811. * Sets the Color Grading 2D Lookup Texture.
  86812. */
  86813. set: function (value) {
  86814. this.imageProcessingConfiguration.colorGradingTexture = value;
  86815. },
  86816. enumerable: true,
  86817. configurable: true
  86818. });
  86819. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  86820. /**
  86821. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86822. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86823. * 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;
  86824. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86825. */
  86826. get: function () {
  86827. return this.imageProcessingConfiguration.colorCurves;
  86828. },
  86829. /**
  86830. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86831. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86832. * 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;
  86833. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86834. */
  86835. set: function (value) {
  86836. this.imageProcessingConfiguration.colorCurves = value;
  86837. },
  86838. enumerable: true,
  86839. configurable: true
  86840. });
  86841. /**
  86842. * The entire material has been created in order to prevent overdraw.
  86843. * @returns false
  86844. */
  86845. BackgroundMaterial.prototype.needAlphaTesting = function () {
  86846. return true;
  86847. };
  86848. /**
  86849. * The entire material has been created in order to prevent overdraw.
  86850. * @returns true if blending is enable
  86851. */
  86852. BackgroundMaterial.prototype.needAlphaBlending = function () {
  86853. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  86854. };
  86855. /**
  86856. * Checks wether the material is ready to be rendered for a given mesh.
  86857. * @param mesh The mesh to render
  86858. * @param subMesh The submesh to check against
  86859. * @param useInstances Specify wether or not the material is used with instances
  86860. * @returns true if all the dependencies are ready (Textures, Effects...)
  86861. */
  86862. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  86863. var _this = this;
  86864. if (useInstances === void 0) { useInstances = false; }
  86865. if (subMesh.effect && this.isFrozen) {
  86866. if (this._wasPreviouslyReady) {
  86867. return true;
  86868. }
  86869. }
  86870. if (!subMesh._materialDefines) {
  86871. subMesh._materialDefines = new BackgroundMaterialDefines();
  86872. }
  86873. var scene = this.getScene();
  86874. var defines = subMesh._materialDefines;
  86875. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  86876. if (defines._renderId === scene.getRenderId()) {
  86877. return true;
  86878. }
  86879. }
  86880. var engine = scene.getEngine();
  86881. // Lights
  86882. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  86883. defines._needNormals = true;
  86884. // Textures
  86885. if (defines._areTexturesDirty) {
  86886. defines._needUVs = false;
  86887. if (scene.texturesEnabled) {
  86888. if (scene.getEngine().getCaps().textureLOD) {
  86889. defines.TEXTURELODSUPPORT = true;
  86890. }
  86891. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86892. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  86893. return false;
  86894. }
  86895. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  86896. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  86897. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  86898. defines.OPACITYFRESNEL = this._opacityFresnel;
  86899. }
  86900. else {
  86901. defines.DIFFUSE = false;
  86902. defines.DIFFUSEHASALPHA = false;
  86903. defines.GAMMADIFFUSE = false;
  86904. defines.OPACITYFRESNEL = false;
  86905. }
  86906. var reflectionTexture = this._reflectionTexture;
  86907. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86908. if (!reflectionTexture.isReadyOrNotBlocking()) {
  86909. return false;
  86910. }
  86911. defines.REFLECTION = true;
  86912. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  86913. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  86914. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  86915. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  86916. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  86917. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  86918. defines.INVERTCUBICMAP = true;
  86919. }
  86920. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  86921. switch (reflectionTexture.coordinatesMode) {
  86922. case BABYLON.Texture.CUBIC_MODE:
  86923. case BABYLON.Texture.INVCUBIC_MODE:
  86924. defines.REFLECTIONMAP_CUBIC = true;
  86925. break;
  86926. case BABYLON.Texture.EXPLICIT_MODE:
  86927. defines.REFLECTIONMAP_EXPLICIT = true;
  86928. break;
  86929. case BABYLON.Texture.PLANAR_MODE:
  86930. defines.REFLECTIONMAP_PLANAR = true;
  86931. break;
  86932. case BABYLON.Texture.PROJECTION_MODE:
  86933. defines.REFLECTIONMAP_PROJECTION = true;
  86934. break;
  86935. case BABYLON.Texture.SKYBOX_MODE:
  86936. defines.REFLECTIONMAP_SKYBOX = true;
  86937. break;
  86938. case BABYLON.Texture.SPHERICAL_MODE:
  86939. defines.REFLECTIONMAP_SPHERICAL = true;
  86940. break;
  86941. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  86942. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  86943. break;
  86944. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  86945. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  86946. break;
  86947. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  86948. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  86949. break;
  86950. }
  86951. if (this.reflectionFresnel) {
  86952. defines.REFLECTIONFRESNEL = true;
  86953. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  86954. this._reflectionControls.x = this.reflectionAmount;
  86955. this._reflectionControls.y = this.reflectionReflectance0;
  86956. this._reflectionControls.z = this.reflectionReflectance90;
  86957. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  86958. }
  86959. else {
  86960. defines.REFLECTIONFRESNEL = false;
  86961. defines.REFLECTIONFALLOFF = false;
  86962. }
  86963. }
  86964. else {
  86965. defines.REFLECTION = false;
  86966. defines.REFLECTIONFALLOFF = false;
  86967. defines.REFLECTIONBLUR = false;
  86968. defines.REFLECTIONMAP_3D = false;
  86969. defines.REFLECTIONMAP_SPHERICAL = false;
  86970. defines.REFLECTIONMAP_PLANAR = false;
  86971. defines.REFLECTIONMAP_CUBIC = false;
  86972. defines.REFLECTIONMAP_PROJECTION = false;
  86973. defines.REFLECTIONMAP_SKYBOX = false;
  86974. defines.REFLECTIONMAP_EXPLICIT = false;
  86975. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86976. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86977. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86978. defines.INVERTCUBICMAP = false;
  86979. defines.REFLECTIONMAP_OPPOSITEZ = false;
  86980. defines.LODINREFLECTIONALPHA = false;
  86981. defines.GAMMAREFLECTION = false;
  86982. }
  86983. }
  86984. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  86985. defines.USERGBCOLOR = this._useRGBColor;
  86986. defines.NOISE = this._enableNoise;
  86987. }
  86988. if (defines._areImageProcessingDirty) {
  86989. if (!this._imageProcessingConfiguration.isReady()) {
  86990. return false;
  86991. }
  86992. this._imageProcessingConfiguration.prepareDefines(defines);
  86993. }
  86994. // Misc.
  86995. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  86996. // Values that need to be evaluated on every frame
  86997. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  86998. // Attribs
  86999. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  87000. if (mesh) {
  87001. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87002. mesh.createNormals(true);
  87003. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  87004. }
  87005. }
  87006. }
  87007. // Get correct effect
  87008. if (defines.isDirty) {
  87009. defines.markAsProcessed();
  87010. scene.resetCachedMaterial();
  87011. // Fallbacks
  87012. var fallbacks = new BABYLON.EffectFallbacks();
  87013. if (defines.FOG) {
  87014. fallbacks.addFallback(0, "FOG");
  87015. }
  87016. if (defines.POINTSIZE) {
  87017. fallbacks.addFallback(1, "POINTSIZE");
  87018. }
  87019. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  87020. if (defines.NUM_BONE_INFLUENCERS > 0) {
  87021. fallbacks.addCPUSkinningFallback(0, mesh);
  87022. }
  87023. //Attributes
  87024. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87025. if (defines.NORMAL) {
  87026. attribs.push(BABYLON.VertexBuffer.NormalKind);
  87027. }
  87028. if (defines.UV1) {
  87029. attribs.push(BABYLON.VertexBuffer.UVKind);
  87030. }
  87031. if (defines.UV2) {
  87032. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87033. }
  87034. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  87035. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  87036. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  87037. "vFogInfos", "vFogColor", "pointSize",
  87038. "vClipPlane", "mBones",
  87039. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  87040. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  87041. "shadowLevel", "alpha",
  87042. "vBackgroundCenter", "vReflectionControl",
  87043. "vDiffuseInfos", "diffuseMatrix",
  87044. ];
  87045. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  87046. var uniformBuffers = ["Material", "Scene"];
  87047. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  87048. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  87049. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  87050. uniformsNames: uniforms,
  87051. uniformBuffersNames: uniformBuffers,
  87052. samplers: samplers,
  87053. defines: defines,
  87054. maxSimultaneousLights: this._maxSimultaneousLights
  87055. });
  87056. var onCompiled = function (effect) {
  87057. if (_this.onCompiled) {
  87058. _this.onCompiled(effect);
  87059. }
  87060. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  87061. };
  87062. var join = defines.toString();
  87063. subMesh.setEffect(scene.getEngine().createEffect("background", {
  87064. attributes: attribs,
  87065. uniformsNames: uniforms,
  87066. uniformBuffersNames: uniformBuffers,
  87067. samplers: samplers,
  87068. defines: join,
  87069. fallbacks: fallbacks,
  87070. onCompiled: onCompiled,
  87071. onError: this.onError,
  87072. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  87073. }, engine), defines);
  87074. this.buildUniformLayout();
  87075. }
  87076. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87077. return false;
  87078. }
  87079. defines._renderId = scene.getRenderId();
  87080. this._wasPreviouslyReady = true;
  87081. return true;
  87082. };
  87083. /**
  87084. * Build the uniform buffer used in the material.
  87085. */
  87086. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87087. // Order is important !
  87088. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87089. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87090. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87091. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87092. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87093. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87094. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87095. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87096. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87097. this._uniformBuffer.addUniform("pointSize", 1);
  87098. this._uniformBuffer.addUniform("shadowLevel", 1);
  87099. this._uniformBuffer.addUniform("alpha", 1);
  87100. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87101. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87102. this._uniformBuffer.create();
  87103. };
  87104. /**
  87105. * Unbind the material.
  87106. */
  87107. BackgroundMaterial.prototype.unbind = function () {
  87108. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87109. this._uniformBuffer.setTexture("diffuseSampler", null);
  87110. }
  87111. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87112. this._uniformBuffer.setTexture("reflectionSampler", null);
  87113. }
  87114. _super.prototype.unbind.call(this);
  87115. };
  87116. /**
  87117. * Bind only the world matrix to the material.
  87118. * @param world The world matrix to bind.
  87119. */
  87120. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87121. this._activeEffect.setMatrix("world", world);
  87122. };
  87123. /**
  87124. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87125. * @param world The world matrix to bind.
  87126. * @param subMesh The submesh to bind for.
  87127. */
  87128. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87129. var scene = this.getScene();
  87130. var defines = subMesh._materialDefines;
  87131. if (!defines) {
  87132. return;
  87133. }
  87134. var effect = subMesh.effect;
  87135. if (!effect) {
  87136. return;
  87137. }
  87138. this._activeEffect = effect;
  87139. // Matrices
  87140. this.bindOnlyWorldMatrix(world);
  87141. // Bones
  87142. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87143. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87144. if (mustRebind) {
  87145. this._uniformBuffer.bindToEffect(effect, "Material");
  87146. this.bindViewProjection(effect);
  87147. var reflectionTexture = this._reflectionTexture;
  87148. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87149. // Texture uniforms
  87150. if (scene.texturesEnabled) {
  87151. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87152. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87153. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87154. }
  87155. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87156. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87157. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87158. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87159. }
  87160. }
  87161. if (this.shadowLevel > 0) {
  87162. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87163. }
  87164. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87165. // Point size
  87166. if (this.pointsCloud) {
  87167. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87168. }
  87169. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87170. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87171. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87172. }
  87173. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87174. // Textures
  87175. if (scene.texturesEnabled) {
  87176. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87177. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87178. }
  87179. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87180. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87181. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87182. }
  87183. else if (!defines.REFLECTIONBLUR) {
  87184. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87185. }
  87186. else {
  87187. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87188. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87189. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87190. }
  87191. if (defines.REFLECTIONFRESNEL) {
  87192. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87193. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87194. }
  87195. }
  87196. }
  87197. // Clip plane
  87198. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87199. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87200. }
  87201. if (mustRebind || !this.isFrozen) {
  87202. if (scene.lightsEnabled) {
  87203. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87204. }
  87205. // View
  87206. this.bindView(effect);
  87207. // Fog
  87208. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87209. // image processing
  87210. this._imageProcessingConfiguration.bind(this._activeEffect);
  87211. }
  87212. this._uniformBuffer.update();
  87213. this._afterBind(mesh);
  87214. };
  87215. /**
  87216. * Dispose the material.
  87217. * @param forceDisposeEffect Force disposal of the associated effect.
  87218. * @param forceDisposeTextures Force disposal of the associated textures.
  87219. */
  87220. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87221. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87222. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87223. if (forceDisposeTextures) {
  87224. if (this.diffuseTexture) {
  87225. this.diffuseTexture.dispose();
  87226. }
  87227. if (this.reflectionTexture) {
  87228. this.reflectionTexture.dispose();
  87229. }
  87230. }
  87231. this._renderTargets.dispose();
  87232. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87233. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87234. }
  87235. _super.prototype.dispose.call(this, forceDisposeEffect);
  87236. };
  87237. /**
  87238. * Clones the material.
  87239. * @param name The cloned name.
  87240. * @returns The cloned material.
  87241. */
  87242. BackgroundMaterial.prototype.clone = function (name) {
  87243. var _this = this;
  87244. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87245. };
  87246. /**
  87247. * Serializes the current material to its JSON representation.
  87248. * @returns The JSON representation.
  87249. */
  87250. BackgroundMaterial.prototype.serialize = function () {
  87251. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87252. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87253. return serializationObject;
  87254. };
  87255. /**
  87256. * Gets the class name of the material
  87257. * @returns "BackgroundMaterial"
  87258. */
  87259. BackgroundMaterial.prototype.getClassName = function () {
  87260. return "BackgroundMaterial";
  87261. };
  87262. /**
  87263. * Parse a JSON input to create back a background material.
  87264. * @param source The JSON data to parse
  87265. * @param scene The scene to create the parsed material in
  87266. * @param rootUrl The root url of the assets the material depends upon
  87267. * @returns the instantiated BackgroundMaterial.
  87268. */
  87269. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87270. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87271. };
  87272. /**
  87273. * Standard reflectance value at parallel view angle.
  87274. */
  87275. BackgroundMaterial.StandardReflectance0 = 0.05;
  87276. /**
  87277. * Standard reflectance value at grazing angle.
  87278. */
  87279. BackgroundMaterial.StandardReflectance90 = 0.5;
  87280. __decorate([
  87281. BABYLON.serializeAsColor3()
  87282. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87283. __decorate([
  87284. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87285. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87286. __decorate([
  87287. BABYLON.serialize()
  87288. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87289. __decorate([
  87290. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87291. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87292. __decorate([
  87293. BABYLON.serializeAsColor3()
  87294. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87295. __decorate([
  87296. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87297. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87298. __decorate([
  87299. BABYLON.serialize()
  87300. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87301. __decorate([
  87302. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87303. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87304. __decorate([
  87305. BABYLON.serializeAsColor3()
  87306. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87307. __decorate([
  87308. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87309. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87310. __decorate([
  87311. BABYLON.serialize()
  87312. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87313. __decorate([
  87314. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87315. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87316. __decorate([
  87317. BABYLON.serializeAsTexture()
  87318. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87319. __decorate([
  87320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87321. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87322. __decorate([
  87323. BABYLON.serialize()
  87324. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87325. __decorate([
  87326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87327. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87328. __decorate([
  87329. BABYLON.serializeAsTexture()
  87330. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87331. __decorate([
  87332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87333. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87334. __decorate([
  87335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87336. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87337. __decorate([
  87338. BABYLON.serialize()
  87339. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87340. __decorate([
  87341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87342. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87343. __decorate([
  87344. BABYLON.serialize()
  87345. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87346. __decorate([
  87347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87348. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87349. __decorate([
  87350. BABYLON.serializeAsVector3()
  87351. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87352. __decorate([
  87353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87354. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87355. __decorate([
  87356. BABYLON.serialize()
  87357. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87358. __decorate([
  87359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87360. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87361. __decorate([
  87362. BABYLON.serialize()
  87363. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87364. __decorate([
  87365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87366. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87367. __decorate([
  87368. BABYLON.serialize()
  87369. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87370. __decorate([
  87371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87372. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87373. __decorate([
  87374. BABYLON.serialize()
  87375. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87376. __decorate([
  87377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87378. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87379. __decorate([
  87380. BABYLON.serialize()
  87381. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87382. __decorate([
  87383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87384. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87385. __decorate([
  87386. BABYLON.serialize()
  87387. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87388. __decorate([
  87389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87390. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87391. __decorate([
  87392. BABYLON.serialize()
  87393. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87394. __decorate([
  87395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87396. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87397. __decorate([
  87398. BABYLON.serialize()
  87399. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87400. __decorate([
  87401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87402. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87403. __decorate([
  87404. BABYLON.serialize()
  87405. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87406. __decorate([
  87407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87408. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87409. __decorate([
  87410. BABYLON.serializeAsImageProcessingConfiguration()
  87411. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87412. return BackgroundMaterial;
  87413. }(BABYLON.PushMaterial));
  87414. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87415. })(BABYLON || (BABYLON = {}));
  87416. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87417. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87418. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87419. s = arguments[i];
  87420. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87421. t[p] = s[p];
  87422. }
  87423. return t;
  87424. };
  87425. var BABYLON;
  87426. (function (BABYLON) {
  87427. /**
  87428. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87429. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87430. * It also helps with the default setup of your imageProcessing configuration.
  87431. */
  87432. var EnvironmentHelper = /** @class */ (function () {
  87433. /**
  87434. * constructor
  87435. * @param options
  87436. * @param scene The scene to add the material to
  87437. */
  87438. function EnvironmentHelper(options, scene) {
  87439. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87440. this._scene = scene;
  87441. this._setupBackground();
  87442. this._setupImageProcessing();
  87443. }
  87444. /**
  87445. * Creates the default options for the helper.
  87446. */
  87447. EnvironmentHelper._getDefaultOptions = function () {
  87448. return {
  87449. createGround: true,
  87450. groundSize: 15,
  87451. groundTexture: this._groundTextureCDNUrl,
  87452. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87453. groundOpacity: 0.9,
  87454. enableGroundShadow: true,
  87455. groundShadowLevel: 0.5,
  87456. enableGroundMirror: false,
  87457. groundMirrorSizeRatio: 0.3,
  87458. groundMirrorBlurKernel: 64,
  87459. groundMirrorAmount: 1,
  87460. groundMirrorFresnelWeight: 1,
  87461. groundMirrorFallOffDistance: 0,
  87462. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87463. groundYBias: 0.00001,
  87464. createSkybox: true,
  87465. skyboxSize: 20,
  87466. skyboxTexture: this._skyboxTextureCDNUrl,
  87467. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87468. backgroundYRotation: 0,
  87469. sizeAuto: true,
  87470. rootPosition: BABYLON.Vector3.Zero(),
  87471. setupImageProcessing: true,
  87472. environmentTexture: this._environmentTextureCDNUrl,
  87473. cameraExposure: 0.8,
  87474. cameraContrast: 1.2,
  87475. toneMappingEnabled: true,
  87476. };
  87477. };
  87478. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87479. /**
  87480. * Gets the root mesh created by the helper.
  87481. */
  87482. get: function () {
  87483. return this._rootMesh;
  87484. },
  87485. enumerable: true,
  87486. configurable: true
  87487. });
  87488. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87489. /**
  87490. * Gets the skybox created by the helper.
  87491. */
  87492. get: function () {
  87493. return this._skybox;
  87494. },
  87495. enumerable: true,
  87496. configurable: true
  87497. });
  87498. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87499. /**
  87500. * Gets the skybox texture created by the helper.
  87501. */
  87502. get: function () {
  87503. return this._skyboxTexture;
  87504. },
  87505. enumerable: true,
  87506. configurable: true
  87507. });
  87508. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87509. /**
  87510. * Gets the skybox material created by the helper.
  87511. */
  87512. get: function () {
  87513. return this._skyboxMaterial;
  87514. },
  87515. enumerable: true,
  87516. configurable: true
  87517. });
  87518. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87519. /**
  87520. * Gets the ground mesh created by the helper.
  87521. */
  87522. get: function () {
  87523. return this._ground;
  87524. },
  87525. enumerable: true,
  87526. configurable: true
  87527. });
  87528. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87529. /**
  87530. * Gets the ground texture created by the helper.
  87531. */
  87532. get: function () {
  87533. return this._groundTexture;
  87534. },
  87535. enumerable: true,
  87536. configurable: true
  87537. });
  87538. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87539. /**
  87540. * Gets the ground mirror created by the helper.
  87541. */
  87542. get: function () {
  87543. return this._groundMirror;
  87544. },
  87545. enumerable: true,
  87546. configurable: true
  87547. });
  87548. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87549. /**
  87550. * Gets the ground mirror render list to helps pushing the meshes
  87551. * you wish in the ground reflection.
  87552. */
  87553. get: function () {
  87554. if (this._groundMirror) {
  87555. return this._groundMirror.renderList;
  87556. }
  87557. return null;
  87558. },
  87559. enumerable: true,
  87560. configurable: true
  87561. });
  87562. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87563. /**
  87564. * Gets the ground material created by the helper.
  87565. */
  87566. get: function () {
  87567. return this._groundMaterial;
  87568. },
  87569. enumerable: true,
  87570. configurable: true
  87571. });
  87572. /**
  87573. * Updates the background according to the new options
  87574. * @param options
  87575. */
  87576. EnvironmentHelper.prototype.updateOptions = function (options) {
  87577. var newOptions = __assign({}, this._options, options);
  87578. if (this._ground && !newOptions.createGround) {
  87579. this._ground.dispose();
  87580. this._ground = null;
  87581. }
  87582. if (this._groundMaterial && !newOptions.createGround) {
  87583. this._groundMaterial.dispose();
  87584. this._groundMaterial = null;
  87585. }
  87586. if (this._groundTexture) {
  87587. if (this._options.groundTexture != newOptions.groundTexture) {
  87588. this._groundTexture.dispose();
  87589. this._groundTexture = null;
  87590. }
  87591. }
  87592. if (this._skybox && !newOptions.createSkybox) {
  87593. this._skybox.dispose();
  87594. this._skybox = null;
  87595. }
  87596. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87597. this._skyboxMaterial.dispose();
  87598. this._skyboxMaterial = null;
  87599. }
  87600. if (this._skyboxTexture) {
  87601. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87602. this._skyboxTexture.dispose();
  87603. this._skyboxTexture = null;
  87604. }
  87605. }
  87606. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87607. this._groundMirror.dispose();
  87608. this._groundMirror = null;
  87609. }
  87610. if (this._scene.environmentTexture) {
  87611. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87612. this._scene.environmentTexture.dispose();
  87613. }
  87614. }
  87615. this._options = newOptions;
  87616. this._setupBackground();
  87617. this._setupImageProcessing();
  87618. };
  87619. /**
  87620. * Sets the primary color of all the available elements.
  87621. * @param color
  87622. */
  87623. EnvironmentHelper.prototype.setMainColor = function (color) {
  87624. if (this.groundMaterial) {
  87625. this.groundMaterial.primaryColor = color;
  87626. }
  87627. if (this.skyboxMaterial) {
  87628. this.skyboxMaterial.primaryColor = color;
  87629. }
  87630. if (this.groundMirror) {
  87631. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87632. }
  87633. };
  87634. /**
  87635. * Setup the image processing according to the specified options.
  87636. */
  87637. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87638. if (this._options.setupImageProcessing) {
  87639. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87640. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87641. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87642. this._setupEnvironmentTexture();
  87643. }
  87644. };
  87645. /**
  87646. * Setup the environment texture according to the specified options.
  87647. */
  87648. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87649. if (this._scene.environmentTexture) {
  87650. return;
  87651. }
  87652. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87653. this._scene.environmentTexture = this._options.environmentTexture;
  87654. return;
  87655. }
  87656. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87657. this._scene.environmentTexture = environmentTexture;
  87658. };
  87659. /**
  87660. * Setup the background according to the specified options.
  87661. */
  87662. EnvironmentHelper.prototype._setupBackground = function () {
  87663. if (!this._rootMesh) {
  87664. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87665. }
  87666. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87667. var sceneSize = this._getSceneSize();
  87668. if (this._options.createGround) {
  87669. this._setupGround(sceneSize);
  87670. this._setupGroundMaterial();
  87671. this._setupGroundDiffuseTexture();
  87672. if (this._options.enableGroundMirror) {
  87673. this._setupGroundMirrorTexture(sceneSize);
  87674. }
  87675. this._setupMirrorInGroundMaterial();
  87676. }
  87677. if (this._options.createSkybox) {
  87678. this._setupSkybox(sceneSize);
  87679. this._setupSkyboxMaterial();
  87680. this._setupSkyboxReflectionTexture();
  87681. }
  87682. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87683. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87684. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87685. };
  87686. /**
  87687. * Get the scene sizes according to the setup.
  87688. */
  87689. EnvironmentHelper.prototype._getSceneSize = function () {
  87690. var groundSize = this._options.groundSize;
  87691. var skyboxSize = this._options.skyboxSize;
  87692. var rootPosition = this._options.rootPosition;
  87693. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87694. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87695. }
  87696. var sceneExtends = this._scene.getWorldExtends();
  87697. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87698. if (this._options.sizeAuto) {
  87699. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87700. this._scene.activeCamera.upperRadiusLimit) {
  87701. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87702. skyboxSize = groundSize;
  87703. }
  87704. var sceneDiagonalLenght = sceneDiagonal.length();
  87705. if (sceneDiagonalLenght > groundSize) {
  87706. groundSize = sceneDiagonalLenght * 2;
  87707. skyboxSize = groundSize;
  87708. }
  87709. // 10 % bigger.
  87710. groundSize *= 1.1;
  87711. skyboxSize *= 1.5;
  87712. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  87713. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  87714. }
  87715. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87716. };
  87717. /**
  87718. * Setup the ground according to the specified options.
  87719. */
  87720. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  87721. var _this = this;
  87722. if (!this._ground) {
  87723. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  87724. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  87725. this._ground.parent = this._rootMesh;
  87726. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  87727. }
  87728. this._ground.receiveShadows = this._options.enableGroundShadow;
  87729. };
  87730. /**
  87731. * Setup the ground material according to the specified options.
  87732. */
  87733. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  87734. if (!this._groundMaterial) {
  87735. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  87736. }
  87737. this._groundMaterial.alpha = this._options.groundOpacity;
  87738. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  87739. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  87740. this._groundMaterial.primaryLevel = 1;
  87741. this._groundMaterial.primaryColor = this._options.groundColor;
  87742. this._groundMaterial.secondaryLevel = 0;
  87743. this._groundMaterial.tertiaryLevel = 0;
  87744. this._groundMaterial.useRGBColor = false;
  87745. this._groundMaterial.enableNoise = true;
  87746. if (this._ground) {
  87747. this._ground.material = this._groundMaterial;
  87748. }
  87749. };
  87750. /**
  87751. * Setup the ground diffuse texture according to the specified options.
  87752. */
  87753. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  87754. if (!this._groundMaterial) {
  87755. return;
  87756. }
  87757. if (this._groundTexture) {
  87758. return;
  87759. }
  87760. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  87761. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  87762. return;
  87763. }
  87764. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  87765. diffuseTexture.gammaSpace = false;
  87766. diffuseTexture.hasAlpha = true;
  87767. this._groundMaterial.diffuseTexture = diffuseTexture;
  87768. };
  87769. /**
  87770. * Setup the ground mirror texture according to the specified options.
  87771. */
  87772. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  87773. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87774. if (!this._groundMirror) {
  87775. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  87776. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  87777. this._groundMirror.anisotropicFilteringLevel = 1;
  87778. this._groundMirror.wrapU = wrapping;
  87779. this._groundMirror.wrapV = wrapping;
  87780. this._groundMirror.gammaSpace = false;
  87781. if (this._groundMirror.renderList) {
  87782. for (var i = 0; i < this._scene.meshes.length; i++) {
  87783. var mesh = this._scene.meshes[i];
  87784. if (mesh !== this._ground &&
  87785. mesh !== this._skybox &&
  87786. mesh !== this._rootMesh) {
  87787. this._groundMirror.renderList.push(mesh);
  87788. }
  87789. }
  87790. }
  87791. }
  87792. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  87793. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  87794. };
  87795. /**
  87796. * Setup the ground to receive the mirror texture.
  87797. */
  87798. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  87799. if (this._groundMaterial) {
  87800. this._groundMaterial.reflectionTexture = this._groundMirror;
  87801. this._groundMaterial.reflectionFresnel = true;
  87802. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  87803. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  87804. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  87805. }
  87806. };
  87807. /**
  87808. * Setup the skybox according to the specified options.
  87809. */
  87810. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  87811. var _this = this;
  87812. if (!this._skybox) {
  87813. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  87814. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  87815. }
  87816. this._skybox.parent = this._rootMesh;
  87817. };
  87818. /**
  87819. * Setup the skybox material according to the specified options.
  87820. */
  87821. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  87822. if (!this._skybox) {
  87823. return;
  87824. }
  87825. if (!this._skyboxMaterial) {
  87826. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  87827. }
  87828. this._skyboxMaterial.useRGBColor = false;
  87829. this._skyboxMaterial.primaryLevel = 1;
  87830. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  87831. this._skyboxMaterial.secondaryLevel = 0;
  87832. this._skyboxMaterial.tertiaryLevel = 0;
  87833. this._skyboxMaterial.enableNoise = true;
  87834. this._skybox.material = this._skyboxMaterial;
  87835. };
  87836. /**
  87837. * Setup the skybox reflection texture according to the specified options.
  87838. */
  87839. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  87840. if (!this._skyboxMaterial) {
  87841. return;
  87842. }
  87843. if (this._skyboxTexture) {
  87844. return;
  87845. }
  87846. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  87847. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87848. return;
  87849. }
  87850. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  87851. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  87852. this._skyboxTexture.gammaSpace = false;
  87853. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87854. };
  87855. /**
  87856. * Dispose all the elements created by the Helper.
  87857. */
  87858. EnvironmentHelper.prototype.dispose = function () {
  87859. if (this._groundMaterial) {
  87860. this._groundMaterial.dispose(true, true);
  87861. }
  87862. if (this._skyboxMaterial) {
  87863. this._skyboxMaterial.dispose(true, true);
  87864. }
  87865. this._rootMesh.dispose(false);
  87866. };
  87867. /**
  87868. * Default ground texture URL.
  87869. */
  87870. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  87871. /**
  87872. * Default skybox texture URL.
  87873. */
  87874. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  87875. /**
  87876. * Default environment texture URL.
  87877. */
  87878. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  87879. return EnvironmentHelper;
  87880. }());
  87881. BABYLON.EnvironmentHelper = EnvironmentHelper;
  87882. })(BABYLON || (BABYLON = {}));
  87883. //# sourceMappingURL=babylon.environmentHelper.js.map
  87884. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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>\nvoid main(void) {\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\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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#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\ngl_FragColor=color;\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=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}","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"};
  87885. 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\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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};"};
  87886. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87887. var BABYLON;
  87888. (function (BABYLON) {
  87889. var GridMaterialDefines = /** @class */ (function (_super) {
  87890. __extends(GridMaterialDefines, _super);
  87891. function GridMaterialDefines() {
  87892. var _this = _super.call(this) || this;
  87893. _this.TRANSPARENT = false;
  87894. _this.FOG = false;
  87895. _this.PREMULTIPLYALPHA = false;
  87896. _this.rebuild();
  87897. return _this;
  87898. }
  87899. return GridMaterialDefines;
  87900. }(BABYLON.MaterialDefines));
  87901. /**
  87902. * The grid materials allows you to wrap any shape with a grid.
  87903. * Colors are customizable.
  87904. */
  87905. var GridMaterial = /** @class */ (function (_super) {
  87906. __extends(GridMaterial, _super);
  87907. /**
  87908. * constructor
  87909. * @param name The name given to the material in order to identify it afterwards.
  87910. * @param scene The scene the material is used in.
  87911. */
  87912. function GridMaterial(name, scene) {
  87913. var _this = _super.call(this, name, scene) || this;
  87914. /**
  87915. * Main color of the grid (e.g. between lines)
  87916. */
  87917. _this.mainColor = BABYLON.Color3.Black();
  87918. /**
  87919. * Color of the grid lines.
  87920. */
  87921. _this.lineColor = BABYLON.Color3.Teal();
  87922. /**
  87923. * The scale of the grid compared to unit.
  87924. */
  87925. _this.gridRatio = 1.0;
  87926. /**
  87927. * Allows setting an offset for the grid lines.
  87928. */
  87929. _this.gridOffset = BABYLON.Vector3.Zero();
  87930. /**
  87931. * The frequency of thicker lines.
  87932. */
  87933. _this.majorUnitFrequency = 10;
  87934. /**
  87935. * The visibility of minor units in the grid.
  87936. */
  87937. _this.minorUnitVisibility = 0.33;
  87938. /**
  87939. * The grid opacity outside of the lines.
  87940. */
  87941. _this.opacity = 1.0;
  87942. /**
  87943. * Determine RBG output is premultiplied by alpha value.
  87944. */
  87945. _this.preMultiplyAlpha = false;
  87946. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  87947. return _this;
  87948. }
  87949. /**
  87950. * Returns wehter or not the grid requires alpha blending.
  87951. */
  87952. GridMaterial.prototype.needAlphaBlending = function () {
  87953. return this.opacity < 1.0;
  87954. };
  87955. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  87956. return this.needAlphaBlending();
  87957. };
  87958. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87959. if (this.isFrozen) {
  87960. if (this._wasPreviouslyReady && subMesh.effect) {
  87961. return true;
  87962. }
  87963. }
  87964. if (!subMesh._materialDefines) {
  87965. subMesh._materialDefines = new GridMaterialDefines();
  87966. }
  87967. var defines = subMesh._materialDefines;
  87968. var scene = this.getScene();
  87969. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87970. if (this._renderId === scene.getRenderId()) {
  87971. return true;
  87972. }
  87973. }
  87974. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  87975. defines.TRANSPARENT = !defines.TRANSPARENT;
  87976. defines.markAsUnprocessed();
  87977. }
  87978. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  87979. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  87980. defines.markAsUnprocessed();
  87981. }
  87982. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  87983. // Get correct effect
  87984. if (defines.isDirty) {
  87985. defines.markAsProcessed();
  87986. scene.resetCachedMaterial();
  87987. // Attributes
  87988. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  87989. // Defines
  87990. var join = defines.toString();
  87991. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  87992. }
  87993. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87994. return false;
  87995. }
  87996. this._renderId = scene.getRenderId();
  87997. this._wasPreviouslyReady = true;
  87998. return true;
  87999. };
  88000. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88001. var scene = this.getScene();
  88002. var defines = subMesh._materialDefines;
  88003. if (!defines) {
  88004. return;
  88005. }
  88006. var effect = subMesh.effect;
  88007. if (!effect) {
  88008. return;
  88009. }
  88010. this._activeEffect = effect;
  88011. // Matrices
  88012. this.bindOnlyWorldMatrix(world);
  88013. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  88014. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  88015. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  88016. // Uniforms
  88017. if (this._mustRebind(scene, effect)) {
  88018. this._activeEffect.setColor3("mainColor", this.mainColor);
  88019. this._activeEffect.setColor3("lineColor", this.lineColor);
  88020. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  88021. this._gridControl.x = this.gridRatio;
  88022. this._gridControl.y = Math.round(this.majorUnitFrequency);
  88023. this._gridControl.z = this.minorUnitVisibility;
  88024. this._gridControl.w = this.opacity;
  88025. this._activeEffect.setVector4("gridControl", this._gridControl);
  88026. }
  88027. // Fog
  88028. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88029. this._afterBind(mesh, this._activeEffect);
  88030. };
  88031. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  88032. _super.prototype.dispose.call(this, forceDisposeEffect);
  88033. };
  88034. GridMaterial.prototype.clone = function (name) {
  88035. var _this = this;
  88036. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  88037. };
  88038. GridMaterial.prototype.serialize = function () {
  88039. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88040. serializationObject.customType = "BABYLON.GridMaterial";
  88041. return serializationObject;
  88042. };
  88043. GridMaterial.prototype.getClassName = function () {
  88044. return "GridMaterial";
  88045. };
  88046. GridMaterial.Parse = function (source, scene, rootUrl) {
  88047. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  88048. };
  88049. __decorate([
  88050. BABYLON.serializeAsColor3()
  88051. ], GridMaterial.prototype, "mainColor", void 0);
  88052. __decorate([
  88053. BABYLON.serializeAsColor3()
  88054. ], GridMaterial.prototype, "lineColor", void 0);
  88055. __decorate([
  88056. BABYLON.serialize()
  88057. ], GridMaterial.prototype, "gridRatio", void 0);
  88058. __decorate([
  88059. BABYLON.serializeAsColor3()
  88060. ], GridMaterial.prototype, "gridOffset", void 0);
  88061. __decorate([
  88062. BABYLON.serialize()
  88063. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  88064. __decorate([
  88065. BABYLON.serialize()
  88066. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  88067. __decorate([
  88068. BABYLON.serialize()
  88069. ], GridMaterial.prototype, "opacity", void 0);
  88070. __decorate([
  88071. BABYLON.serialize()
  88072. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  88073. return GridMaterial;
  88074. }(BABYLON.PushMaterial));
  88075. BABYLON.GridMaterial = GridMaterial;
  88076. })(BABYLON || (BABYLON = {}));
  88077. //# sourceMappingURL=babylon.gridmaterial.js.map
  88078. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  88079. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  88080. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88081. var BABYLON;
  88082. (function (BABYLON) {
  88083. var GLTFLoaderCoordinateSystemMode;
  88084. (function (GLTFLoaderCoordinateSystemMode) {
  88085. /**
  88086. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  88087. */
  88088. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  88089. /**
  88090. * Sets the useRightHandedSystem flag on the scene.
  88091. */
  88092. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  88093. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  88094. var GLTFLoaderAnimationStartMode;
  88095. (function (GLTFLoaderAnimationStartMode) {
  88096. /**
  88097. * No animation will start.
  88098. */
  88099. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  88100. /**
  88101. * The first animation will start.
  88102. */
  88103. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  88104. /**
  88105. * All animations will start.
  88106. */
  88107. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  88108. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  88109. var GLTFLoaderState;
  88110. (function (GLTFLoaderState) {
  88111. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  88112. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  88113. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  88114. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  88115. var GLTFFileLoader = /** @class */ (function () {
  88116. function GLTFFileLoader() {
  88117. // #region Common options
  88118. /**
  88119. * Raised when the asset has been parsed.
  88120. * The data.json property stores the glTF JSON.
  88121. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  88122. */
  88123. this.onParsedObservable = new BABYLON.Observable();
  88124. // #endregion
  88125. // #region V2 options
  88126. /**
  88127. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  88128. */
  88129. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  88130. /**
  88131. * The animation start mode (NONE, FIRST, ALL).
  88132. */
  88133. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  88134. /**
  88135. * Set to true to compile materials before raising the success callback.
  88136. */
  88137. this.compileMaterials = false;
  88138. /**
  88139. * Set to true to also compile materials with clip planes.
  88140. */
  88141. this.useClipPlane = false;
  88142. /**
  88143. * Set to true to compile shadow generators before raising the success callback.
  88144. */
  88145. this.compileShadowGenerators = false;
  88146. /**
  88147. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  88148. */
  88149. this.onMeshLoadedObservable = new BABYLON.Observable();
  88150. /**
  88151. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  88152. */
  88153. this.onTextureLoadedObservable = new BABYLON.Observable();
  88154. /**
  88155. * Raised when the loader creates a material after parsing the glTF properties of the material.
  88156. */
  88157. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88158. /**
  88159. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  88160. * For assets with LODs, raised when all of the LODs are complete.
  88161. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  88162. */
  88163. this.onCompleteObservable = new BABYLON.Observable();
  88164. /**
  88165. * Raised when the loader is disposed.
  88166. */
  88167. this.onDisposeObservable = new BABYLON.Observable();
  88168. /**
  88169. * Raised after a loader extension is created.
  88170. * Set additional options for a loader extension in this event.
  88171. */
  88172. this.onExtensionLoadedObservable = new BABYLON.Observable();
  88173. // #endregion
  88174. this._loader = null;
  88175. this.name = "gltf";
  88176. this.extensions = {
  88177. ".gltf": { isBinary: false },
  88178. ".glb": { isBinary: true }
  88179. };
  88180. }
  88181. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  88182. set: function (callback) {
  88183. if (this._onParsedObserver) {
  88184. this.onParsedObservable.remove(this._onParsedObserver);
  88185. }
  88186. this._onParsedObserver = this.onParsedObservable.add(callback);
  88187. },
  88188. enumerable: true,
  88189. configurable: true
  88190. });
  88191. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  88192. set: function (callback) {
  88193. if (this._onMeshLoadedObserver) {
  88194. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88195. }
  88196. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88197. },
  88198. enumerable: true,
  88199. configurable: true
  88200. });
  88201. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88202. set: function (callback) {
  88203. if (this._onTextureLoadedObserver) {
  88204. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88205. }
  88206. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88207. },
  88208. enumerable: true,
  88209. configurable: true
  88210. });
  88211. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88212. set: function (callback) {
  88213. if (this._onMaterialLoadedObserver) {
  88214. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88215. }
  88216. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88217. },
  88218. enumerable: true,
  88219. configurable: true
  88220. });
  88221. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88222. set: function (callback) {
  88223. if (this._onCompleteObserver) {
  88224. this.onCompleteObservable.remove(this._onCompleteObserver);
  88225. }
  88226. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88227. },
  88228. enumerable: true,
  88229. configurable: true
  88230. });
  88231. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88232. set: function (callback) {
  88233. if (this._onDisposeObserver) {
  88234. this.onDisposeObservable.remove(this._onDisposeObserver);
  88235. }
  88236. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88237. },
  88238. enumerable: true,
  88239. configurable: true
  88240. });
  88241. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88242. set: function (callback) {
  88243. if (this._onExtensionLoadedObserver) {
  88244. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88245. }
  88246. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88247. },
  88248. enumerable: true,
  88249. configurable: true
  88250. });
  88251. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88252. /**
  88253. * The loader state or null if not active.
  88254. */
  88255. get: function () {
  88256. return this._loader ? this._loader.state : null;
  88257. },
  88258. enumerable: true,
  88259. configurable: true
  88260. });
  88261. /**
  88262. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88263. */
  88264. GLTFFileLoader.prototype.dispose = function () {
  88265. if (this._loader) {
  88266. this._loader.dispose();
  88267. this._loader = null;
  88268. }
  88269. this.onMeshLoadedObservable.clear();
  88270. this.onTextureLoadedObservable.clear();
  88271. this.onMaterialLoadedObservable.clear();
  88272. this.onDisposeObservable.notifyObservers(this);
  88273. this.onDisposeObservable.clear();
  88274. };
  88275. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88276. var _this = this;
  88277. return Promise.resolve().then(function () {
  88278. var loaderData = _this._parse(data);
  88279. _this._loader = _this._getLoader(loaderData);
  88280. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88281. });
  88282. };
  88283. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88284. var _this = this;
  88285. return Promise.resolve().then(function () {
  88286. var loaderData = _this._parse(data);
  88287. _this._loader = _this._getLoader(loaderData);
  88288. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88289. });
  88290. };
  88291. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88292. var _this = this;
  88293. return Promise.resolve().then(function () {
  88294. var loaderData = _this._parse(data);
  88295. _this._loader = _this._getLoader(loaderData);
  88296. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88297. var container = new BABYLON.AssetContainer(scene);
  88298. Array.prototype.push.apply(container.meshes, result.meshes);
  88299. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88300. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88301. container.removeAllFromScene();
  88302. return container;
  88303. });
  88304. });
  88305. };
  88306. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88307. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88308. };
  88309. GLTFFileLoader.prototype.createPlugin = function () {
  88310. return new GLTFFileLoader();
  88311. };
  88312. GLTFFileLoader.prototype._parse = function (data) {
  88313. var parsedData;
  88314. if (data instanceof ArrayBuffer) {
  88315. parsedData = GLTFFileLoader._parseBinary(data);
  88316. }
  88317. else {
  88318. parsedData = {
  88319. json: JSON.parse(data),
  88320. bin: null
  88321. };
  88322. }
  88323. this.onParsedObservable.notifyObservers(parsedData);
  88324. this.onParsedObservable.clear();
  88325. return parsedData;
  88326. };
  88327. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88328. var _this = this;
  88329. var loaderVersion = { major: 2, minor: 0 };
  88330. var asset = loaderData.json.asset || {};
  88331. var version = GLTFFileLoader._parseVersion(asset.version);
  88332. if (!version) {
  88333. throw new Error("Invalid version: " + asset.version);
  88334. }
  88335. if (asset.minVersion !== undefined) {
  88336. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88337. if (!minVersion) {
  88338. throw new Error("Invalid minimum version: " + asset.minVersion);
  88339. }
  88340. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88341. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88342. }
  88343. }
  88344. var createLoaders = {
  88345. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88346. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88347. };
  88348. var createLoader = createLoaders[version.major];
  88349. if (!createLoader) {
  88350. throw new Error("Unsupported version: " + asset.version);
  88351. }
  88352. var loader = createLoader();
  88353. loader.coordinateSystemMode = this.coordinateSystemMode;
  88354. loader.animationStartMode = this.animationStartMode;
  88355. loader.compileMaterials = this.compileMaterials;
  88356. loader.useClipPlane = this.useClipPlane;
  88357. loader.compileShadowGenerators = this.compileShadowGenerators;
  88358. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88359. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88360. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88361. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88362. loader.onCompleteObservable.add(function () {
  88363. _this.onMeshLoadedObservable.clear();
  88364. _this.onTextureLoadedObservable.clear();
  88365. _this.onMaterialLoadedObservable.clear();
  88366. _this.onCompleteObservable.notifyObservers(_this);
  88367. _this.onCompleteObservable.clear();
  88368. });
  88369. return loader;
  88370. };
  88371. GLTFFileLoader._parseBinary = function (data) {
  88372. var Binary = {
  88373. Magic: 0x46546C67
  88374. };
  88375. var binaryReader = new BinaryReader(data);
  88376. var magic = binaryReader.readUint32();
  88377. if (magic !== Binary.Magic) {
  88378. throw new Error("Unexpected magic: " + magic);
  88379. }
  88380. var version = binaryReader.readUint32();
  88381. switch (version) {
  88382. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88383. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88384. }
  88385. throw new Error("Unsupported version: " + version);
  88386. };
  88387. GLTFFileLoader._parseV1 = function (binaryReader) {
  88388. var ContentFormat = {
  88389. JSON: 0
  88390. };
  88391. var length = binaryReader.readUint32();
  88392. if (length != binaryReader.getLength()) {
  88393. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88394. }
  88395. var contentLength = binaryReader.readUint32();
  88396. var contentFormat = binaryReader.readUint32();
  88397. var content;
  88398. switch (contentFormat) {
  88399. case ContentFormat.JSON: {
  88400. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88401. break;
  88402. }
  88403. default: {
  88404. throw new Error("Unexpected content format: " + contentFormat);
  88405. }
  88406. }
  88407. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88408. var body = binaryReader.readUint8Array(bytesRemaining);
  88409. return {
  88410. json: content,
  88411. bin: body
  88412. };
  88413. };
  88414. GLTFFileLoader._parseV2 = function (binaryReader) {
  88415. var ChunkFormat = {
  88416. JSON: 0x4E4F534A,
  88417. BIN: 0x004E4942
  88418. };
  88419. var length = binaryReader.readUint32();
  88420. if (length !== binaryReader.getLength()) {
  88421. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88422. }
  88423. // JSON chunk
  88424. var chunkLength = binaryReader.readUint32();
  88425. var chunkFormat = binaryReader.readUint32();
  88426. if (chunkFormat !== ChunkFormat.JSON) {
  88427. throw new Error("First chunk format is not JSON");
  88428. }
  88429. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88430. // Look for BIN chunk
  88431. var bin = null;
  88432. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88433. var chunkLength_1 = binaryReader.readUint32();
  88434. var chunkFormat_1 = binaryReader.readUint32();
  88435. switch (chunkFormat_1) {
  88436. case ChunkFormat.JSON: {
  88437. throw new Error("Unexpected JSON chunk");
  88438. }
  88439. case ChunkFormat.BIN: {
  88440. bin = binaryReader.readUint8Array(chunkLength_1);
  88441. break;
  88442. }
  88443. default: {
  88444. // ignore unrecognized chunkFormat
  88445. binaryReader.skipBytes(chunkLength_1);
  88446. break;
  88447. }
  88448. }
  88449. }
  88450. return {
  88451. json: json,
  88452. bin: bin
  88453. };
  88454. };
  88455. GLTFFileLoader._parseVersion = function (version) {
  88456. if (version === "1.0" || version === "1.0.1") {
  88457. return {
  88458. major: 1,
  88459. minor: 0
  88460. };
  88461. }
  88462. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88463. if (!match) {
  88464. return null;
  88465. }
  88466. return {
  88467. major: parseInt(match[1]),
  88468. minor: parseInt(match[2])
  88469. };
  88470. };
  88471. GLTFFileLoader._compareVersion = function (a, b) {
  88472. if (a.major > b.major)
  88473. return 1;
  88474. if (a.major < b.major)
  88475. return -1;
  88476. if (a.minor > b.minor)
  88477. return 1;
  88478. if (a.minor < b.minor)
  88479. return -1;
  88480. return 0;
  88481. };
  88482. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88483. var result = "";
  88484. var length = buffer.byteLength;
  88485. for (var i = 0; i < length; i++) {
  88486. result += String.fromCharCode(buffer[i]);
  88487. }
  88488. return result;
  88489. };
  88490. // #endregion
  88491. // #region V1 options
  88492. GLTFFileLoader.IncrementalLoading = true;
  88493. GLTFFileLoader.HomogeneousCoordinates = false;
  88494. return GLTFFileLoader;
  88495. }());
  88496. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88497. var BinaryReader = /** @class */ (function () {
  88498. function BinaryReader(arrayBuffer) {
  88499. this._arrayBuffer = arrayBuffer;
  88500. this._dataView = new DataView(arrayBuffer);
  88501. this._byteOffset = 0;
  88502. }
  88503. BinaryReader.prototype.getPosition = function () {
  88504. return this._byteOffset;
  88505. };
  88506. BinaryReader.prototype.getLength = function () {
  88507. return this._arrayBuffer.byteLength;
  88508. };
  88509. BinaryReader.prototype.readUint32 = function () {
  88510. var value = this._dataView.getUint32(this._byteOffset, true);
  88511. this._byteOffset += 4;
  88512. return value;
  88513. };
  88514. BinaryReader.prototype.readUint8Array = function (length) {
  88515. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88516. this._byteOffset += length;
  88517. return value;
  88518. };
  88519. BinaryReader.prototype.skipBytes = function (length) {
  88520. this._byteOffset += length;
  88521. };
  88522. return BinaryReader;
  88523. }());
  88524. if (BABYLON.SceneLoader) {
  88525. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88526. }
  88527. })(BABYLON || (BABYLON = {}));
  88528. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88529. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88530. var BABYLON;
  88531. (function (BABYLON) {
  88532. var GLTF1;
  88533. (function (GLTF1) {
  88534. /**
  88535. * Enums
  88536. */
  88537. var EComponentType;
  88538. (function (EComponentType) {
  88539. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88540. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88541. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88542. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88543. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88544. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88545. var EShaderType;
  88546. (function (EShaderType) {
  88547. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88548. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88549. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88550. var EParameterType;
  88551. (function (EParameterType) {
  88552. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88553. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88554. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88555. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88556. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88557. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88558. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88559. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88560. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88561. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88562. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88563. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88564. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88565. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88566. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88567. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88568. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88569. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88570. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88571. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88572. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88573. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88574. var ETextureWrapMode;
  88575. (function (ETextureWrapMode) {
  88576. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88577. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88578. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88579. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88580. var ETextureFilterType;
  88581. (function (ETextureFilterType) {
  88582. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88583. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88584. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88585. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88586. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88587. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88588. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88589. var ETextureFormat;
  88590. (function (ETextureFormat) {
  88591. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88592. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88593. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88594. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88595. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88596. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88597. var ECullingType;
  88598. (function (ECullingType) {
  88599. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88600. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88601. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88602. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88603. var EBlendingFunction;
  88604. (function (EBlendingFunction) {
  88605. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88606. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88607. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88608. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88609. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88610. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88611. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88612. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88613. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88614. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88615. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88616. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88617. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88618. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88619. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88620. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88621. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88622. })(BABYLON || (BABYLON = {}));
  88623. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88624. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88625. var BABYLON;
  88626. (function (BABYLON) {
  88627. var GLTF1;
  88628. (function (GLTF1) {
  88629. /**
  88630. * Tokenizer. Used for shaders compatibility
  88631. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88632. */
  88633. var ETokenType;
  88634. (function (ETokenType) {
  88635. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88636. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88637. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88638. })(ETokenType || (ETokenType = {}));
  88639. var Tokenizer = /** @class */ (function () {
  88640. function Tokenizer(toParse) {
  88641. this._pos = 0;
  88642. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88643. this._toParse = toParse;
  88644. this._maxPos = toParse.length;
  88645. }
  88646. Tokenizer.prototype.getNextToken = function () {
  88647. if (this.isEnd())
  88648. return ETokenType.END_OF_INPUT;
  88649. this.currentString = this.read();
  88650. this.currentToken = ETokenType.UNKNOWN;
  88651. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88652. this.currentToken = ETokenType.IDENTIFIER;
  88653. this.currentIdentifier = this.currentString;
  88654. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88655. this.currentIdentifier += this.currentString;
  88656. this.forward();
  88657. }
  88658. }
  88659. return this.currentToken;
  88660. };
  88661. Tokenizer.prototype.peek = function () {
  88662. return this._toParse[this._pos];
  88663. };
  88664. Tokenizer.prototype.read = function () {
  88665. return this._toParse[this._pos++];
  88666. };
  88667. Tokenizer.prototype.forward = function () {
  88668. this._pos++;
  88669. };
  88670. Tokenizer.prototype.isEnd = function () {
  88671. return this._pos >= this._maxPos;
  88672. };
  88673. return Tokenizer;
  88674. }());
  88675. /**
  88676. * Values
  88677. */
  88678. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88679. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88680. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88681. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88682. /**
  88683. * Parse
  88684. */
  88685. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88686. for (var buf in parsedBuffers) {
  88687. var parsedBuffer = parsedBuffers[buf];
  88688. gltfRuntime.buffers[buf] = parsedBuffer;
  88689. gltfRuntime.buffersCount++;
  88690. }
  88691. };
  88692. var parseShaders = function (parsedShaders, gltfRuntime) {
  88693. for (var sha in parsedShaders) {
  88694. var parsedShader = parsedShaders[sha];
  88695. gltfRuntime.shaders[sha] = parsedShader;
  88696. gltfRuntime.shaderscount++;
  88697. }
  88698. };
  88699. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88700. for (var object in parsedObjects) {
  88701. var parsedObject = parsedObjects[object];
  88702. gltfRuntime[runtimeProperty][object] = parsedObject;
  88703. }
  88704. };
  88705. /**
  88706. * Utils
  88707. */
  88708. var normalizeUVs = function (buffer) {
  88709. if (!buffer) {
  88710. return;
  88711. }
  88712. for (var i = 0; i < buffer.length / 2; i++) {
  88713. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  88714. }
  88715. };
  88716. var getAttribute = function (attributeParameter) {
  88717. if (attributeParameter.semantic === "NORMAL") {
  88718. return "normal";
  88719. }
  88720. else if (attributeParameter.semantic === "POSITION") {
  88721. return "position";
  88722. }
  88723. else if (attributeParameter.semantic === "JOINT") {
  88724. return "matricesIndices";
  88725. }
  88726. else if (attributeParameter.semantic === "WEIGHT") {
  88727. return "matricesWeights";
  88728. }
  88729. else if (attributeParameter.semantic === "COLOR") {
  88730. return "color";
  88731. }
  88732. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  88733. var channel = Number(attributeParameter.semantic.split("_")[1]);
  88734. return "uv" + (channel === 0 ? "" : channel + 1);
  88735. }
  88736. return null;
  88737. };
  88738. /**
  88739. * Loads and creates animations
  88740. */
  88741. var loadAnimations = function (gltfRuntime) {
  88742. for (var anim in gltfRuntime.animations) {
  88743. var animation = gltfRuntime.animations[anim];
  88744. if (!animation.channels || !animation.samplers) {
  88745. continue;
  88746. }
  88747. var lastAnimation = null;
  88748. for (var i = 0; i < animation.channels.length; i++) {
  88749. // Get parameters and load buffers
  88750. var channel = animation.channels[i];
  88751. var sampler = animation.samplers[channel.sampler];
  88752. if (!sampler) {
  88753. continue;
  88754. }
  88755. var inputData = null;
  88756. var outputData = null;
  88757. if (animation.parameters) {
  88758. inputData = animation.parameters[sampler.input];
  88759. outputData = animation.parameters[sampler.output];
  88760. }
  88761. else {
  88762. inputData = sampler.input;
  88763. outputData = sampler.output;
  88764. }
  88765. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  88766. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  88767. var targetID = channel.target.id;
  88768. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  88769. if (targetNode === null) {
  88770. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  88771. }
  88772. if (targetNode === null) {
  88773. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  88774. continue;
  88775. }
  88776. var isBone = targetNode instanceof BABYLON.Bone;
  88777. // Get target path (position, rotation or scaling)
  88778. var targetPath = channel.target.path;
  88779. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  88780. if (targetPathIndex !== -1) {
  88781. targetPath = babylonAnimationPaths[targetPathIndex];
  88782. }
  88783. // Determine animation type
  88784. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  88785. if (!isBone) {
  88786. if (targetPath === "rotationQuaternion") {
  88787. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88788. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  88789. }
  88790. else {
  88791. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88792. }
  88793. }
  88794. // Create animation and key frames
  88795. var babylonAnimation = null;
  88796. var keys = [];
  88797. var arrayOffset = 0;
  88798. var modifyKey = false;
  88799. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  88800. babylonAnimation = lastAnimation;
  88801. modifyKey = true;
  88802. }
  88803. if (!modifyKey) {
  88804. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88805. }
  88806. // For each frame
  88807. for (var j = 0; j < bufferInput.length; j++) {
  88808. var value = null;
  88809. if (targetPath === "rotationQuaternion") {
  88810. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  88811. arrayOffset += 4;
  88812. }
  88813. else {
  88814. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  88815. arrayOffset += 3;
  88816. }
  88817. if (isBone) {
  88818. var bone = targetNode;
  88819. var translation = BABYLON.Vector3.Zero();
  88820. var rotationQuaternion = new BABYLON.Quaternion();
  88821. var scaling = BABYLON.Vector3.Zero();
  88822. // Warning on decompose
  88823. var mat = bone.getBaseMatrix();
  88824. if (modifyKey && lastAnimation) {
  88825. mat = lastAnimation.getKeys()[j].value;
  88826. }
  88827. mat.decompose(scaling, rotationQuaternion, translation);
  88828. if (targetPath === "position") {
  88829. translation = value;
  88830. }
  88831. else if (targetPath === "rotationQuaternion") {
  88832. rotationQuaternion = value;
  88833. }
  88834. else {
  88835. scaling = value;
  88836. }
  88837. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  88838. }
  88839. if (!modifyKey) {
  88840. keys.push({
  88841. frame: bufferInput[j],
  88842. value: value
  88843. });
  88844. }
  88845. else if (lastAnimation) {
  88846. lastAnimation.getKeys()[j].value = value;
  88847. }
  88848. }
  88849. // Finish
  88850. if (!modifyKey && babylonAnimation) {
  88851. babylonAnimation.setKeys(keys);
  88852. targetNode.animations.push(babylonAnimation);
  88853. }
  88854. lastAnimation = babylonAnimation;
  88855. gltfRuntime.scene.stopAnimation(targetNode);
  88856. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  88857. }
  88858. }
  88859. };
  88860. /**
  88861. * Returns the bones transformation matrix
  88862. */
  88863. var configureBoneTransformation = function (node) {
  88864. var mat = null;
  88865. if (node.translation || node.rotation || node.scale) {
  88866. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  88867. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  88868. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  88869. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  88870. }
  88871. else {
  88872. mat = BABYLON.Matrix.FromArray(node.matrix);
  88873. }
  88874. return mat;
  88875. };
  88876. /**
  88877. * Returns the parent bone
  88878. */
  88879. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  88880. // Try to find
  88881. for (var i = 0; i < newSkeleton.bones.length; i++) {
  88882. if (newSkeleton.bones[i].name === jointName) {
  88883. return newSkeleton.bones[i];
  88884. }
  88885. }
  88886. // Not found, search in gltf nodes
  88887. var nodes = gltfRuntime.nodes;
  88888. for (var nde in nodes) {
  88889. var node = nodes[nde];
  88890. if (!node.jointName) {
  88891. continue;
  88892. }
  88893. var children = node.children;
  88894. for (var i = 0; i < children.length; i++) {
  88895. var child = gltfRuntime.nodes[children[i]];
  88896. if (!child.jointName) {
  88897. continue;
  88898. }
  88899. if (child.jointName === jointName) {
  88900. var mat = configureBoneTransformation(node);
  88901. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  88902. bone.id = nde;
  88903. return bone;
  88904. }
  88905. }
  88906. }
  88907. return null;
  88908. };
  88909. /**
  88910. * Returns the appropriate root node
  88911. */
  88912. var getNodeToRoot = function (nodesToRoot, id) {
  88913. for (var i = 0; i < nodesToRoot.length; i++) {
  88914. var nodeToRoot = nodesToRoot[i];
  88915. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  88916. var child = nodeToRoot.node.children[j];
  88917. if (child === id) {
  88918. return nodeToRoot.bone;
  88919. }
  88920. }
  88921. }
  88922. return null;
  88923. };
  88924. /**
  88925. * Returns the node with the joint name
  88926. */
  88927. var getJointNode = function (gltfRuntime, jointName) {
  88928. var nodes = gltfRuntime.nodes;
  88929. var node = nodes[jointName];
  88930. if (node) {
  88931. return {
  88932. node: node,
  88933. id: jointName
  88934. };
  88935. }
  88936. for (var nde in nodes) {
  88937. node = nodes[nde];
  88938. if (node.jointName === jointName) {
  88939. return {
  88940. node: node,
  88941. id: nde
  88942. };
  88943. }
  88944. }
  88945. return null;
  88946. };
  88947. /**
  88948. * Checks if a nodes is in joints
  88949. */
  88950. var nodeIsInJoints = function (skins, id) {
  88951. for (var i = 0; i < skins.jointNames.length; i++) {
  88952. if (skins.jointNames[i] === id) {
  88953. return true;
  88954. }
  88955. }
  88956. return false;
  88957. };
  88958. /**
  88959. * Fills the nodes to root for bones and builds hierarchy
  88960. */
  88961. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  88962. // Creates nodes for root
  88963. for (var nde in gltfRuntime.nodes) {
  88964. var node = gltfRuntime.nodes[nde];
  88965. var id = nde;
  88966. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  88967. continue;
  88968. }
  88969. // Create node to root bone
  88970. var mat = configureBoneTransformation(node);
  88971. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  88972. bone.id = id;
  88973. nodesToRoot.push({ bone: bone, node: node, id: id });
  88974. }
  88975. // Parenting
  88976. for (var i = 0; i < nodesToRoot.length; i++) {
  88977. var nodeToRoot = nodesToRoot[i];
  88978. var children = nodeToRoot.node.children;
  88979. for (var j = 0; j < children.length; j++) {
  88980. var child = null;
  88981. for (var k = 0; k < nodesToRoot.length; k++) {
  88982. if (nodesToRoot[k].id === children[j]) {
  88983. child = nodesToRoot[k];
  88984. break;
  88985. }
  88986. }
  88987. if (child) {
  88988. child.bone._parent = nodeToRoot.bone;
  88989. nodeToRoot.bone.children.push(child.bone);
  88990. }
  88991. }
  88992. }
  88993. };
  88994. /**
  88995. * Imports a skeleton
  88996. */
  88997. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  88998. if (!newSkeleton) {
  88999. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  89000. }
  89001. if (!skins.babylonSkeleton) {
  89002. return newSkeleton;
  89003. }
  89004. // Find the root bones
  89005. var nodesToRoot = [];
  89006. var nodesToRootToAdd = [];
  89007. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  89008. newSkeleton.bones = [];
  89009. // Joints
  89010. for (var i = 0; i < skins.jointNames.length; i++) {
  89011. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89012. if (!jointNode) {
  89013. continue;
  89014. }
  89015. var node = jointNode.node;
  89016. if (!node) {
  89017. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  89018. continue;
  89019. }
  89020. var id = jointNode.id;
  89021. // Optimize, if the bone already exists...
  89022. var existingBone = gltfRuntime.scene.getBoneByID(id);
  89023. if (existingBone) {
  89024. newSkeleton.bones.push(existingBone);
  89025. continue;
  89026. }
  89027. // Search for parent bone
  89028. var foundBone = false;
  89029. var parentBone = null;
  89030. for (var j = 0; j < i; j++) {
  89031. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  89032. if (!jointNode_1) {
  89033. continue;
  89034. }
  89035. var joint = jointNode_1.node;
  89036. if (!joint) {
  89037. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  89038. continue;
  89039. }
  89040. var children = joint.children;
  89041. if (!children) {
  89042. continue;
  89043. }
  89044. foundBone = false;
  89045. for (var k = 0; k < children.length; k++) {
  89046. if (children[k] === id) {
  89047. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  89048. foundBone = true;
  89049. break;
  89050. }
  89051. }
  89052. if (foundBone) {
  89053. break;
  89054. }
  89055. }
  89056. // Create bone
  89057. var mat = configureBoneTransformation(node);
  89058. if (!parentBone && nodesToRoot.length > 0) {
  89059. parentBone = getNodeToRoot(nodesToRoot, id);
  89060. if (parentBone) {
  89061. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  89062. nodesToRootToAdd.push(parentBone);
  89063. }
  89064. }
  89065. }
  89066. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  89067. bone.id = id;
  89068. }
  89069. // Polish
  89070. var bones = newSkeleton.bones;
  89071. newSkeleton.bones = [];
  89072. for (var i = 0; i < skins.jointNames.length; i++) {
  89073. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89074. if (!jointNode) {
  89075. continue;
  89076. }
  89077. for (var j = 0; j < bones.length; j++) {
  89078. if (bones[j].id === jointNode.id) {
  89079. newSkeleton.bones.push(bones[j]);
  89080. break;
  89081. }
  89082. }
  89083. }
  89084. newSkeleton.prepare();
  89085. // Finish
  89086. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  89087. newSkeleton.bones.push(nodesToRootToAdd[i]);
  89088. }
  89089. return newSkeleton;
  89090. };
  89091. /**
  89092. * Imports a mesh and its geometries
  89093. */
  89094. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  89095. if (!newMesh) {
  89096. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89097. newMesh.id = id;
  89098. }
  89099. if (!node.babylonNode) {
  89100. return newMesh;
  89101. }
  89102. var subMaterials = [];
  89103. var vertexData = null;
  89104. var verticesStarts = new Array();
  89105. var verticesCounts = new Array();
  89106. var indexStarts = new Array();
  89107. var indexCounts = new Array();
  89108. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89109. var meshID = meshes[meshIndex];
  89110. var mesh = gltfRuntime.meshes[meshID];
  89111. if (!mesh) {
  89112. continue;
  89113. }
  89114. // Positions, normals and UVs
  89115. for (var i = 0; i < mesh.primitives.length; i++) {
  89116. // Temporary vertex data
  89117. var tempVertexData = new BABYLON.VertexData();
  89118. var primitive = mesh.primitives[i];
  89119. if (primitive.mode !== 4) {
  89120. // continue;
  89121. }
  89122. var attributes = primitive.attributes;
  89123. var accessor = null;
  89124. var buffer = null;
  89125. // Set positions, normal and uvs
  89126. for (var semantic in attributes) {
  89127. // Link accessor and buffer view
  89128. accessor = gltfRuntime.accessors[attributes[semantic]];
  89129. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89130. if (semantic === "NORMAL") {
  89131. tempVertexData.normals = new Float32Array(buffer.length);
  89132. tempVertexData.normals.set(buffer);
  89133. }
  89134. else if (semantic === "POSITION") {
  89135. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  89136. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  89137. for (var j = 0; j < buffer.length; j += 4) {
  89138. tempVertexData.positions[j] = buffer[j];
  89139. tempVertexData.positions[j + 1] = buffer[j + 1];
  89140. tempVertexData.positions[j + 2] = buffer[j + 2];
  89141. }
  89142. }
  89143. else {
  89144. tempVertexData.positions = new Float32Array(buffer.length);
  89145. tempVertexData.positions.set(buffer);
  89146. }
  89147. verticesCounts.push(tempVertexData.positions.length);
  89148. }
  89149. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  89150. var channel = Number(semantic.split("_")[1]);
  89151. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  89152. var uvs = new Float32Array(buffer.length);
  89153. uvs.set(buffer);
  89154. normalizeUVs(uvs);
  89155. tempVertexData.set(uvs, uvKind);
  89156. }
  89157. else if (semantic === "JOINT") {
  89158. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  89159. tempVertexData.matricesIndices.set(buffer);
  89160. }
  89161. else if (semantic === "WEIGHT") {
  89162. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  89163. tempVertexData.matricesWeights.set(buffer);
  89164. }
  89165. else if (semantic === "COLOR") {
  89166. tempVertexData.colors = new Float32Array(buffer.length);
  89167. tempVertexData.colors.set(buffer);
  89168. }
  89169. }
  89170. // Indices
  89171. accessor = gltfRuntime.accessors[primitive.indices];
  89172. if (accessor) {
  89173. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89174. tempVertexData.indices = new Int32Array(buffer.length);
  89175. tempVertexData.indices.set(buffer);
  89176. indexCounts.push(tempVertexData.indices.length);
  89177. }
  89178. else {
  89179. // Set indices on the fly
  89180. var indices = [];
  89181. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  89182. indices.push(j);
  89183. }
  89184. tempVertexData.indices = new Int32Array(indices);
  89185. indexCounts.push(tempVertexData.indices.length);
  89186. }
  89187. if (!vertexData) {
  89188. vertexData = tempVertexData;
  89189. }
  89190. else {
  89191. vertexData.merge(tempVertexData);
  89192. }
  89193. // Sub material
  89194. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89195. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89196. // Update vertices start and index start
  89197. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89198. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89199. }
  89200. }
  89201. var material;
  89202. if (subMaterials.length > 1) {
  89203. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89204. material.subMaterials = subMaterials;
  89205. }
  89206. else {
  89207. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89208. }
  89209. if (subMaterials.length === 1) {
  89210. material = subMaterials[0];
  89211. }
  89212. if (!newMesh.material) {
  89213. newMesh.material = material;
  89214. }
  89215. // Apply geometry
  89216. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89217. newMesh.computeWorldMatrix(true);
  89218. // Apply submeshes
  89219. newMesh.subMeshes = [];
  89220. var index = 0;
  89221. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89222. var meshID = meshes[meshIndex];
  89223. var mesh = gltfRuntime.meshes[meshID];
  89224. if (!mesh) {
  89225. continue;
  89226. }
  89227. for (var i = 0; i < mesh.primitives.length; i++) {
  89228. if (mesh.primitives[i].mode !== 4) {
  89229. //continue;
  89230. }
  89231. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89232. index++;
  89233. }
  89234. }
  89235. // Finish
  89236. return newMesh;
  89237. };
  89238. /**
  89239. * Configure node transformation from position, rotation and scaling
  89240. */
  89241. var configureNode = function (newNode, position, rotation, scaling) {
  89242. if (newNode.position) {
  89243. newNode.position = position;
  89244. }
  89245. if (newNode.rotationQuaternion || newNode.rotation) {
  89246. newNode.rotationQuaternion = rotation;
  89247. }
  89248. if (newNode.scaling) {
  89249. newNode.scaling = scaling;
  89250. }
  89251. };
  89252. /**
  89253. * Configures node from transformation matrix
  89254. */
  89255. var configureNodeFromMatrix = function (newNode, node, parent) {
  89256. if (node.matrix) {
  89257. var position = new BABYLON.Vector3(0, 0, 0);
  89258. var rotation = new BABYLON.Quaternion();
  89259. var scaling = new BABYLON.Vector3(0, 0, 0);
  89260. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89261. mat.decompose(scaling, rotation, position);
  89262. configureNode(newNode, position, rotation, scaling);
  89263. }
  89264. else if (node.translation && node.rotation && node.scale) {
  89265. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89266. }
  89267. newNode.computeWorldMatrix(true);
  89268. };
  89269. /**
  89270. * Imports a node
  89271. */
  89272. var importNode = function (gltfRuntime, node, id, parent) {
  89273. var lastNode = null;
  89274. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89275. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89276. return null;
  89277. }
  89278. }
  89279. // Meshes
  89280. if (node.skin) {
  89281. if (node.meshes) {
  89282. var skin = gltfRuntime.skins[node.skin];
  89283. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89284. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89285. if (newMesh.skeleton === null) {
  89286. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89287. if (!skin.babylonSkeleton) {
  89288. skin.babylonSkeleton = newMesh.skeleton;
  89289. }
  89290. }
  89291. lastNode = newMesh;
  89292. }
  89293. }
  89294. else if (node.meshes) {
  89295. /**
  89296. * Improve meshes property
  89297. */
  89298. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89299. lastNode = newMesh;
  89300. }
  89301. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89302. var light = gltfRuntime.lights[node.light];
  89303. if (light) {
  89304. if (light.type === "ambient") {
  89305. var ambienLight = light[light.type];
  89306. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89307. hemiLight.name = node.name || "";
  89308. if (ambienLight.color) {
  89309. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89310. }
  89311. lastNode = hemiLight;
  89312. }
  89313. else if (light.type === "directional") {
  89314. var directionalLight = light[light.type];
  89315. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89316. dirLight.name = node.name || "";
  89317. if (directionalLight.color) {
  89318. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89319. }
  89320. lastNode = dirLight;
  89321. }
  89322. else if (light.type === "point") {
  89323. var pointLight = light[light.type];
  89324. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89325. ptLight.name = node.name || "";
  89326. if (pointLight.color) {
  89327. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89328. }
  89329. lastNode = ptLight;
  89330. }
  89331. else if (light.type === "spot") {
  89332. var spotLight = light[light.type];
  89333. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89334. spLight.name = node.name || "";
  89335. if (spotLight.color) {
  89336. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89337. }
  89338. if (spotLight.fallOfAngle) {
  89339. spLight.angle = spotLight.fallOfAngle;
  89340. }
  89341. if (spotLight.fallOffExponent) {
  89342. spLight.exponent = spotLight.fallOffExponent;
  89343. }
  89344. lastNode = spLight;
  89345. }
  89346. }
  89347. }
  89348. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89349. var camera = gltfRuntime.cameras[node.camera];
  89350. if (camera) {
  89351. if (camera.type === "orthographic") {
  89352. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89353. orthoCamera.name = node.name || "";
  89354. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89355. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89356. lastNode = orthoCamera;
  89357. }
  89358. else if (camera.type === "perspective") {
  89359. var perspectiveCamera = camera[camera.type];
  89360. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89361. persCamera.name = node.name || "";
  89362. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89363. if (!perspectiveCamera.aspectRatio) {
  89364. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89365. }
  89366. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89367. persCamera.maxZ = perspectiveCamera.zfar;
  89368. persCamera.minZ = perspectiveCamera.znear;
  89369. }
  89370. lastNode = persCamera;
  89371. }
  89372. }
  89373. }
  89374. // Empty node
  89375. if (!node.jointName) {
  89376. if (node.babylonNode) {
  89377. return node.babylonNode;
  89378. }
  89379. else if (lastNode === null) {
  89380. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89381. node.babylonNode = dummy;
  89382. lastNode = dummy;
  89383. }
  89384. }
  89385. if (lastNode !== null) {
  89386. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89387. configureNodeFromMatrix(lastNode, node, parent);
  89388. }
  89389. else {
  89390. var translation = node.translation || [0, 0, 0];
  89391. var rotation = node.rotation || [0, 0, 0, 1];
  89392. var scale = node.scale || [1, 1, 1];
  89393. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89394. }
  89395. lastNode.updateCache(true);
  89396. node.babylonNode = lastNode;
  89397. }
  89398. return lastNode;
  89399. };
  89400. /**
  89401. * Traverses nodes and creates them
  89402. */
  89403. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89404. if (meshIncluded === void 0) { meshIncluded = false; }
  89405. var node = gltfRuntime.nodes[id];
  89406. var newNode = null;
  89407. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89408. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89409. meshIncluded = true;
  89410. }
  89411. else {
  89412. meshIncluded = false;
  89413. }
  89414. }
  89415. else {
  89416. meshIncluded = true;
  89417. }
  89418. if (!node.jointName && meshIncluded) {
  89419. newNode = importNode(gltfRuntime, node, id, parent);
  89420. if (newNode !== null) {
  89421. newNode.id = id;
  89422. newNode.parent = parent;
  89423. }
  89424. }
  89425. if (node.children) {
  89426. for (var i = 0; i < node.children.length; i++) {
  89427. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89428. }
  89429. }
  89430. };
  89431. /**
  89432. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89433. */
  89434. var postLoad = function (gltfRuntime) {
  89435. // Nodes
  89436. var currentScene = gltfRuntime.currentScene;
  89437. if (currentScene) {
  89438. for (var i = 0; i < currentScene.nodes.length; i++) {
  89439. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89440. }
  89441. }
  89442. else {
  89443. for (var thing in gltfRuntime.scenes) {
  89444. currentScene = gltfRuntime.scenes[thing];
  89445. for (var i = 0; i < currentScene.nodes.length; i++) {
  89446. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89447. }
  89448. }
  89449. }
  89450. // Set animations
  89451. loadAnimations(gltfRuntime);
  89452. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89453. var skeleton = gltfRuntime.scene.skeletons[i];
  89454. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89455. }
  89456. };
  89457. /**
  89458. * onBind shaderrs callback to set uniforms and matrices
  89459. */
  89460. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89461. var materialValues = material.values || technique.parameters;
  89462. for (var unif in unTreatedUniforms) {
  89463. var uniform = unTreatedUniforms[unif];
  89464. var type = uniform.type;
  89465. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89466. if (uniform.semantic && !uniform.source && !uniform.node) {
  89467. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89468. }
  89469. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89470. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89471. if (source === null) {
  89472. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89473. }
  89474. if (source === null) {
  89475. continue;
  89476. }
  89477. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89478. }
  89479. }
  89480. else {
  89481. var value = materialValues[technique.uniforms[unif]];
  89482. if (!value) {
  89483. continue;
  89484. }
  89485. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89486. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89487. if (texture === null || texture === undefined) {
  89488. continue;
  89489. }
  89490. shaderMaterial.getEffect().setTexture(unif, texture);
  89491. }
  89492. else {
  89493. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89494. }
  89495. }
  89496. }
  89497. onSuccess(shaderMaterial);
  89498. };
  89499. /**
  89500. * Prepare uniforms to send the only one time
  89501. * Loads the appropriate textures
  89502. */
  89503. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89504. var materialValues = material.values || technique.parameters;
  89505. var techniqueUniforms = technique.uniforms;
  89506. /**
  89507. * Prepare values here (not matrices)
  89508. */
  89509. for (var unif in unTreatedUniforms) {
  89510. var uniform = unTreatedUniforms[unif];
  89511. var type = uniform.type;
  89512. var value = materialValues[techniqueUniforms[unif]];
  89513. if (value === undefined) {
  89514. // In case the value is the same for all materials
  89515. value = uniform.value;
  89516. }
  89517. if (!value) {
  89518. continue;
  89519. }
  89520. var onLoadTexture = function (uniformName) {
  89521. return function (texture) {
  89522. if (uniform.value && uniformName) {
  89523. // Static uniform
  89524. shaderMaterial.setTexture(uniformName, texture);
  89525. delete unTreatedUniforms[uniformName];
  89526. }
  89527. };
  89528. };
  89529. // Texture (sampler2D)
  89530. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89531. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89532. }
  89533. else {
  89534. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89535. // Static uniform
  89536. delete unTreatedUniforms[unif];
  89537. }
  89538. }
  89539. }
  89540. };
  89541. /**
  89542. * Shader compilation failed
  89543. */
  89544. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89545. return function (effect, error) {
  89546. shaderMaterial.dispose(true);
  89547. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89548. };
  89549. };
  89550. /**
  89551. * Shader compilation success
  89552. */
  89553. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89554. return function (_) {
  89555. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89556. shaderMaterial.onBind = function (mesh) {
  89557. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89558. };
  89559. };
  89560. };
  89561. /**
  89562. * Returns the appropriate uniform if already handled by babylon
  89563. */
  89564. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89565. for (var unif in technique.uniforms) {
  89566. var uniform = technique.uniforms[unif];
  89567. var uniformParameter = technique.parameters[uniform];
  89568. if (tokenizer.currentIdentifier === unif) {
  89569. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89570. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89571. if (transformIndex !== -1) {
  89572. delete unTreatedUniforms[unif];
  89573. return babylonTransforms[transformIndex];
  89574. }
  89575. }
  89576. }
  89577. }
  89578. return tokenizer.currentIdentifier;
  89579. };
  89580. /**
  89581. * All shaders loaded. Create materials one by one
  89582. */
  89583. var importMaterials = function (gltfRuntime) {
  89584. // Create materials
  89585. for (var mat in gltfRuntime.materials) {
  89586. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89587. }
  89588. };
  89589. /**
  89590. * Implementation of the base glTF spec
  89591. */
  89592. var GLTFLoaderBase = /** @class */ (function () {
  89593. function GLTFLoaderBase() {
  89594. }
  89595. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89596. var gltfRuntime = {
  89597. extensions: {},
  89598. accessors: {},
  89599. buffers: {},
  89600. bufferViews: {},
  89601. meshes: {},
  89602. lights: {},
  89603. cameras: {},
  89604. nodes: {},
  89605. images: {},
  89606. textures: {},
  89607. shaders: {},
  89608. programs: {},
  89609. samplers: {},
  89610. techniques: {},
  89611. materials: {},
  89612. animations: {},
  89613. skins: {},
  89614. extensionsUsed: [],
  89615. scenes: {},
  89616. buffersCount: 0,
  89617. shaderscount: 0,
  89618. scene: scene,
  89619. rootUrl: rootUrl,
  89620. loadedBufferCount: 0,
  89621. loadedBufferViews: {},
  89622. loadedShaderCount: 0,
  89623. importOnlyMeshes: false,
  89624. dummyNodes: []
  89625. };
  89626. // Parse
  89627. if (parsedData.extensions) {
  89628. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89629. }
  89630. if (parsedData.extensionsUsed) {
  89631. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89632. }
  89633. if (parsedData.buffers) {
  89634. parseBuffers(parsedData.buffers, gltfRuntime);
  89635. }
  89636. if (parsedData.bufferViews) {
  89637. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89638. }
  89639. if (parsedData.accessors) {
  89640. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89641. }
  89642. if (parsedData.meshes) {
  89643. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89644. }
  89645. if (parsedData.lights) {
  89646. parseObject(parsedData.lights, "lights", gltfRuntime);
  89647. }
  89648. if (parsedData.cameras) {
  89649. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89650. }
  89651. if (parsedData.nodes) {
  89652. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89653. }
  89654. if (parsedData.images) {
  89655. parseObject(parsedData.images, "images", gltfRuntime);
  89656. }
  89657. if (parsedData.textures) {
  89658. parseObject(parsedData.textures, "textures", gltfRuntime);
  89659. }
  89660. if (parsedData.shaders) {
  89661. parseShaders(parsedData.shaders, gltfRuntime);
  89662. }
  89663. if (parsedData.programs) {
  89664. parseObject(parsedData.programs, "programs", gltfRuntime);
  89665. }
  89666. if (parsedData.samplers) {
  89667. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89668. }
  89669. if (parsedData.techniques) {
  89670. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89671. }
  89672. if (parsedData.materials) {
  89673. parseObject(parsedData.materials, "materials", gltfRuntime);
  89674. }
  89675. if (parsedData.animations) {
  89676. parseObject(parsedData.animations, "animations", gltfRuntime);
  89677. }
  89678. if (parsedData.skins) {
  89679. parseObject(parsedData.skins, "skins", gltfRuntime);
  89680. }
  89681. if (parsedData.scenes) {
  89682. gltfRuntime.scenes = parsedData.scenes;
  89683. }
  89684. if (parsedData.scene && parsedData.scenes) {
  89685. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89686. }
  89687. return gltfRuntime;
  89688. };
  89689. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89690. var buffer = gltfRuntime.buffers[id];
  89691. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89692. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89693. }
  89694. else {
  89695. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89696. if (request) {
  89697. onError(request.status + " " + request.statusText);
  89698. }
  89699. });
  89700. }
  89701. };
  89702. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89703. var texture = gltfRuntime.textures[id];
  89704. if (!texture || !texture.source) {
  89705. onError("");
  89706. return;
  89707. }
  89708. if (texture.babylonTexture) {
  89709. onSuccess(null);
  89710. return;
  89711. }
  89712. var source = gltfRuntime.images[texture.source];
  89713. if (BABYLON.Tools.IsBase64(source.uri)) {
  89714. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  89715. }
  89716. else {
  89717. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  89718. if (request) {
  89719. onError(request.status + " " + request.statusText);
  89720. }
  89721. });
  89722. }
  89723. };
  89724. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89725. var texture = gltfRuntime.textures[id];
  89726. if (texture.babylonTexture) {
  89727. onSuccess(texture.babylonTexture);
  89728. return;
  89729. }
  89730. var sampler = gltfRuntime.samplers[texture.sampler];
  89731. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  89732. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  89733. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  89734. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  89735. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  89736. var blob = new Blob([buffer]);
  89737. var blobURL = URL.createObjectURL(blob);
  89738. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  89739. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  89740. if (sampler.wrapS !== undefined) {
  89741. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  89742. }
  89743. if (sampler.wrapT !== undefined) {
  89744. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  89745. }
  89746. newTexture.name = id;
  89747. texture.babylonTexture = newTexture;
  89748. onSuccess(newTexture);
  89749. };
  89750. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89751. var shader = gltfRuntime.shaders[id];
  89752. if (BABYLON.Tools.IsBase64(shader.uri)) {
  89753. var shaderString = atob(shader.uri.split(",")[1]);
  89754. onSuccess(shaderString);
  89755. }
  89756. else {
  89757. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  89758. if (request) {
  89759. onError(request.status + " " + request.statusText);
  89760. }
  89761. });
  89762. }
  89763. };
  89764. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89765. var material = gltfRuntime.materials[id];
  89766. if (!material.technique) {
  89767. if (onError) {
  89768. onError("No technique found.");
  89769. }
  89770. return;
  89771. }
  89772. var technique = gltfRuntime.techniques[material.technique];
  89773. if (!technique) {
  89774. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  89775. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  89776. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89777. onSuccess(defaultMaterial);
  89778. return;
  89779. }
  89780. var program = gltfRuntime.programs[technique.program];
  89781. var states = technique.states;
  89782. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  89783. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  89784. var newVertexShader = "";
  89785. var newPixelShader = "";
  89786. var vertexTokenizer = new Tokenizer(vertexShader);
  89787. var pixelTokenizer = new Tokenizer(pixelShader);
  89788. var unTreatedUniforms = {};
  89789. var uniforms = [];
  89790. var attributes = [];
  89791. var samplers = [];
  89792. // Fill uniform, sampler2D and attributes
  89793. for (var unif in technique.uniforms) {
  89794. var uniform = technique.uniforms[unif];
  89795. var uniformParameter = technique.parameters[uniform];
  89796. unTreatedUniforms[unif] = uniformParameter;
  89797. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  89798. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89799. if (transformIndex !== -1) {
  89800. uniforms.push(babylonTransforms[transformIndex]);
  89801. delete unTreatedUniforms[unif];
  89802. }
  89803. else {
  89804. uniforms.push(unif);
  89805. }
  89806. }
  89807. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  89808. samplers.push(unif);
  89809. }
  89810. else {
  89811. uniforms.push(unif);
  89812. }
  89813. }
  89814. for (var attr in technique.attributes) {
  89815. var attribute = technique.attributes[attr];
  89816. var attributeParameter = technique.parameters[attribute];
  89817. if (attributeParameter.semantic) {
  89818. attributes.push(getAttribute(attributeParameter));
  89819. }
  89820. }
  89821. // Configure vertex shader
  89822. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  89823. var tokenType = vertexTokenizer.currentToken;
  89824. if (tokenType !== ETokenType.IDENTIFIER) {
  89825. newVertexShader += vertexTokenizer.currentString;
  89826. continue;
  89827. }
  89828. var foundAttribute = false;
  89829. for (var attr in technique.attributes) {
  89830. var attribute = technique.attributes[attr];
  89831. var attributeParameter = technique.parameters[attribute];
  89832. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  89833. newVertexShader += getAttribute(attributeParameter);
  89834. foundAttribute = true;
  89835. break;
  89836. }
  89837. }
  89838. if (foundAttribute) {
  89839. continue;
  89840. }
  89841. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  89842. }
  89843. // Configure pixel shader
  89844. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  89845. var tokenType = pixelTokenizer.currentToken;
  89846. if (tokenType !== ETokenType.IDENTIFIER) {
  89847. newPixelShader += pixelTokenizer.currentString;
  89848. continue;
  89849. }
  89850. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  89851. }
  89852. // Create shader material
  89853. var shaderPath = {
  89854. vertex: program.vertexShader + id,
  89855. fragment: program.fragmentShader + id
  89856. };
  89857. var options = {
  89858. attributes: attributes,
  89859. uniforms: uniforms,
  89860. samplers: samplers,
  89861. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  89862. };
  89863. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  89864. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  89865. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  89866. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  89867. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  89868. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89869. if (states && states.functions) {
  89870. var functions = states.functions;
  89871. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  89872. shaderMaterial.backFaceCulling = false;
  89873. }
  89874. var blendFunc = functions.blendFuncSeparate;
  89875. if (blendFunc) {
  89876. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89877. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  89878. }
  89879. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89880. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89881. }
  89882. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89883. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  89884. }
  89885. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89886. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  89887. }
  89888. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89889. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  89890. }
  89891. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89892. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  89893. }
  89894. }
  89895. }
  89896. };
  89897. return GLTFLoaderBase;
  89898. }());
  89899. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  89900. /**
  89901. * glTF V1 Loader
  89902. */
  89903. var GLTFLoader = /** @class */ (function () {
  89904. function GLTFLoader() {
  89905. // #region Stubs for IGLTFLoader interface
  89906. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  89907. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  89908. this.compileMaterials = false;
  89909. this.useClipPlane = false;
  89910. this.compileShadowGenerators = false;
  89911. this.onDisposeObservable = new BABYLON.Observable();
  89912. this.onMeshLoadedObservable = new BABYLON.Observable();
  89913. this.onTextureLoadedObservable = new BABYLON.Observable();
  89914. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89915. this.onCompleteObservable = new BABYLON.Observable();
  89916. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89917. this.state = null;
  89918. }
  89919. GLTFLoader.RegisterExtension = function (extension) {
  89920. if (GLTFLoader.Extensions[extension.name]) {
  89921. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  89922. return;
  89923. }
  89924. GLTFLoader.Extensions[extension.name] = extension;
  89925. };
  89926. GLTFLoader.prototype.dispose = function () { };
  89927. // #endregion
  89928. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89929. var _this = this;
  89930. scene.useRightHandedSystem = true;
  89931. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89932. gltfRuntime.importOnlyMeshes = true;
  89933. if (meshesNames === "") {
  89934. gltfRuntime.importMeshesNames = [];
  89935. }
  89936. else if (typeof meshesNames === "string") {
  89937. gltfRuntime.importMeshesNames = [meshesNames];
  89938. }
  89939. else if (meshesNames && !(meshesNames instanceof Array)) {
  89940. gltfRuntime.importMeshesNames = [meshesNames];
  89941. }
  89942. else {
  89943. gltfRuntime.importMeshesNames = [];
  89944. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  89945. }
  89946. // Create nodes
  89947. _this._createNodes(gltfRuntime);
  89948. var meshes = new Array();
  89949. var skeletons = new Array();
  89950. // Fill arrays of meshes and skeletons
  89951. for (var nde in gltfRuntime.nodes) {
  89952. var node = gltfRuntime.nodes[nde];
  89953. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  89954. meshes.push(node.babylonNode);
  89955. }
  89956. }
  89957. for (var skl in gltfRuntime.skins) {
  89958. var skin = gltfRuntime.skins[skl];
  89959. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  89960. skeletons.push(skin.babylonSkeleton);
  89961. }
  89962. }
  89963. // Load buffers, shaders, materials, etc.
  89964. _this._loadBuffersAsync(gltfRuntime, function () {
  89965. _this._loadShadersAsync(gltfRuntime, function () {
  89966. importMaterials(gltfRuntime);
  89967. postLoad(gltfRuntime);
  89968. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89969. onSuccess(meshes, [], skeletons);
  89970. }
  89971. });
  89972. }, onProgress);
  89973. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89974. onSuccess(meshes, [], skeletons);
  89975. }
  89976. }, onError);
  89977. return true;
  89978. };
  89979. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89980. var _this = this;
  89981. return new Promise(function (resolve, reject) {
  89982. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  89983. resolve({
  89984. meshes: meshes,
  89985. particleSystems: particleSystems,
  89986. skeletons: skeletons
  89987. });
  89988. }, onProgress, function (message) {
  89989. reject(new Error(message));
  89990. });
  89991. });
  89992. };
  89993. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  89994. var _this = this;
  89995. scene.useRightHandedSystem = true;
  89996. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89997. // Load runtime extensios
  89998. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  89999. // Create nodes
  90000. _this._createNodes(gltfRuntime);
  90001. // Load buffers, shaders, materials, etc.
  90002. _this._loadBuffersAsync(gltfRuntime, function () {
  90003. _this._loadShadersAsync(gltfRuntime, function () {
  90004. importMaterials(gltfRuntime);
  90005. postLoad(gltfRuntime);
  90006. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  90007. onSuccess();
  90008. }
  90009. });
  90010. });
  90011. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  90012. onSuccess();
  90013. }
  90014. }, onError);
  90015. }, onError);
  90016. };
  90017. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90018. var _this = this;
  90019. return new Promise(function (resolve, reject) {
  90020. _this._loadAsync(scene, data, rootUrl, function () {
  90021. resolve();
  90022. }, onProgress, function (message) {
  90023. reject(new Error(message));
  90024. });
  90025. });
  90026. };
  90027. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  90028. var hasShaders = false;
  90029. var processShader = function (sha, shader) {
  90030. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  90031. gltfRuntime.loadedShaderCount++;
  90032. if (shaderString) {
  90033. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  90034. }
  90035. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  90036. onload();
  90037. }
  90038. }, function () {
  90039. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  90040. });
  90041. };
  90042. for (var sha in gltfRuntime.shaders) {
  90043. hasShaders = true;
  90044. var shader = gltfRuntime.shaders[sha];
  90045. if (shader) {
  90046. processShader.bind(this, sha, shader)();
  90047. }
  90048. else {
  90049. BABYLON.Tools.Error("No shader named: " + sha);
  90050. }
  90051. }
  90052. if (!hasShaders) {
  90053. onload();
  90054. }
  90055. };
  90056. ;
  90057. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  90058. var hasBuffers = false;
  90059. var processBuffer = function (buf, buffer) {
  90060. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  90061. gltfRuntime.loadedBufferCount++;
  90062. if (bufferView) {
  90063. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  90064. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  90065. }
  90066. gltfRuntime.loadedBufferViews[buf] = bufferView;
  90067. }
  90068. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  90069. onLoad();
  90070. }
  90071. }, function () {
  90072. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  90073. });
  90074. };
  90075. for (var buf in gltfRuntime.buffers) {
  90076. hasBuffers = true;
  90077. var buffer = gltfRuntime.buffers[buf];
  90078. if (buffer) {
  90079. processBuffer.bind(this, buf, buffer)();
  90080. }
  90081. else {
  90082. BABYLON.Tools.Error("No buffer named: " + buf);
  90083. }
  90084. }
  90085. if (!hasBuffers) {
  90086. onLoad();
  90087. }
  90088. };
  90089. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  90090. var currentScene = gltfRuntime.currentScene;
  90091. if (currentScene) {
  90092. // Only one scene even if multiple scenes are defined
  90093. for (var i = 0; i < currentScene.nodes.length; i++) {
  90094. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90095. }
  90096. }
  90097. else {
  90098. // Load all scenes
  90099. for (var thing in gltfRuntime.scenes) {
  90100. currentScene = gltfRuntime.scenes[thing];
  90101. for (var i = 0; i < currentScene.nodes.length; i++) {
  90102. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90103. }
  90104. }
  90105. }
  90106. };
  90107. GLTFLoader.Extensions = {};
  90108. return GLTFLoader;
  90109. }());
  90110. GLTF1.GLTFLoader = GLTFLoader;
  90111. ;
  90112. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  90113. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90114. })(BABYLON || (BABYLON = {}));
  90115. //# sourceMappingURL=babylon.glTFLoader.js.map
  90116. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90117. var BABYLON;
  90118. (function (BABYLON) {
  90119. var GLTF1;
  90120. (function (GLTF1) {
  90121. /**
  90122. * Utils functions for GLTF
  90123. */
  90124. var GLTFUtils = /** @class */ (function () {
  90125. function GLTFUtils() {
  90126. }
  90127. /**
  90128. * Sets the given "parameter" matrix
  90129. * @param scene: the {BABYLON.Scene} object
  90130. * @param source: the source node where to pick the matrix
  90131. * @param parameter: the GLTF technique parameter
  90132. * @param uniformName: the name of the shader's uniform
  90133. * @param shaderMaterial: the shader material
  90134. */
  90135. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  90136. var mat = null;
  90137. if (parameter.semantic === "MODEL") {
  90138. mat = source.getWorldMatrix();
  90139. }
  90140. else if (parameter.semantic === "PROJECTION") {
  90141. mat = scene.getProjectionMatrix();
  90142. }
  90143. else if (parameter.semantic === "VIEW") {
  90144. mat = scene.getViewMatrix();
  90145. }
  90146. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  90147. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  90148. }
  90149. else if (parameter.semantic === "MODELVIEW") {
  90150. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  90151. }
  90152. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  90153. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  90154. }
  90155. else if (parameter.semantic === "MODELINVERSE") {
  90156. mat = source.getWorldMatrix().invert();
  90157. }
  90158. else if (parameter.semantic === "VIEWINVERSE") {
  90159. mat = scene.getViewMatrix().invert();
  90160. }
  90161. else if (parameter.semantic === "PROJECTIONINVERSE") {
  90162. mat = scene.getProjectionMatrix().invert();
  90163. }
  90164. else if (parameter.semantic === "MODELVIEWINVERSE") {
  90165. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  90166. }
  90167. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  90168. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  90169. }
  90170. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  90171. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  90172. }
  90173. else {
  90174. debugger;
  90175. }
  90176. if (mat) {
  90177. switch (parameter.type) {
  90178. case GLTF1.EParameterType.FLOAT_MAT2:
  90179. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  90180. break;
  90181. case GLTF1.EParameterType.FLOAT_MAT3:
  90182. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  90183. break;
  90184. case GLTF1.EParameterType.FLOAT_MAT4:
  90185. shaderMaterial.setMatrix(uniformName, mat);
  90186. break;
  90187. default: break;
  90188. }
  90189. }
  90190. };
  90191. /**
  90192. * Sets the given "parameter" matrix
  90193. * @param shaderMaterial: the shader material
  90194. * @param uniform: the name of the shader's uniform
  90195. * @param value: the value of the uniform
  90196. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90197. */
  90198. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90199. switch (type) {
  90200. case GLTF1.EParameterType.FLOAT:
  90201. shaderMaterial.setFloat(uniform, value);
  90202. return true;
  90203. case GLTF1.EParameterType.FLOAT_VEC2:
  90204. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90205. return true;
  90206. case GLTF1.EParameterType.FLOAT_VEC3:
  90207. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90208. return true;
  90209. case GLTF1.EParameterType.FLOAT_VEC4:
  90210. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90211. return true;
  90212. default: return false;
  90213. }
  90214. };
  90215. /**
  90216. * Returns the wrap mode of the texture
  90217. * @param mode: the mode value
  90218. */
  90219. GLTFUtils.GetWrapMode = function (mode) {
  90220. switch (mode) {
  90221. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90222. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90223. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90224. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90225. }
  90226. };
  90227. /**
  90228. * Returns the byte stride giving an accessor
  90229. * @param accessor: the GLTF accessor objet
  90230. */
  90231. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90232. // Needs this function since "byteStride" isn't requiered in glTF format
  90233. var type = accessor.type;
  90234. switch (type) {
  90235. case "VEC2": return 2;
  90236. case "VEC3": return 3;
  90237. case "VEC4": return 4;
  90238. case "MAT2": return 4;
  90239. case "MAT3": return 9;
  90240. case "MAT4": return 16;
  90241. default: return 1;
  90242. }
  90243. };
  90244. /**
  90245. * Returns the texture filter mode giving a mode value
  90246. * @param mode: the filter mode value
  90247. */
  90248. GLTFUtils.GetTextureFilterMode = function (mode) {
  90249. switch (mode) {
  90250. case GLTF1.ETextureFilterType.LINEAR:
  90251. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90252. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90253. case GLTF1.ETextureFilterType.NEAREST:
  90254. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90255. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90256. }
  90257. };
  90258. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90259. var byteOffset = bufferView.byteOffset + byteOffset;
  90260. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90261. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90262. throw new Error("Buffer access is out of range");
  90263. }
  90264. var buffer = loadedBufferView.buffer;
  90265. byteOffset += loadedBufferView.byteOffset;
  90266. switch (componentType) {
  90267. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90268. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90269. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90270. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90271. default: return new Float32Array(buffer, byteOffset, byteLength);
  90272. }
  90273. };
  90274. /**
  90275. * Returns a buffer from its accessor
  90276. * @param gltfRuntime: the GLTF runtime
  90277. * @param accessor: the GLTF accessor
  90278. */
  90279. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90280. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90281. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90282. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90283. };
  90284. /**
  90285. * Decodes a buffer view into a string
  90286. * @param view: the buffer view
  90287. */
  90288. GLTFUtils.DecodeBufferToText = function (view) {
  90289. var result = "";
  90290. var length = view.byteLength;
  90291. for (var i = 0; i < length; ++i) {
  90292. result += String.fromCharCode(view[i]);
  90293. }
  90294. return result;
  90295. };
  90296. /**
  90297. * Returns the default material of gltf. Related to
  90298. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90299. * @param scene: the Babylon.js scene
  90300. */
  90301. GLTFUtils.GetDefaultMaterial = function (scene) {
  90302. if (!GLTFUtils._DefaultMaterial) {
  90303. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90304. "precision highp float;",
  90305. "",
  90306. "uniform mat4 worldView;",
  90307. "uniform mat4 projection;",
  90308. "",
  90309. "attribute vec3 position;",
  90310. "",
  90311. "void main(void)",
  90312. "{",
  90313. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90314. "}"
  90315. ].join("\n");
  90316. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90317. "precision highp float;",
  90318. "",
  90319. "uniform vec4 u_emission;",
  90320. "",
  90321. "void main(void)",
  90322. "{",
  90323. " gl_FragColor = u_emission;",
  90324. "}"
  90325. ].join("\n");
  90326. var shaderPath = {
  90327. vertex: "GLTFDefaultMaterial",
  90328. fragment: "GLTFDefaultMaterial"
  90329. };
  90330. var options = {
  90331. attributes: ["position"],
  90332. uniforms: ["worldView", "projection", "u_emission"],
  90333. samplers: new Array(),
  90334. needAlphaBlending: false
  90335. };
  90336. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90337. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90338. }
  90339. return GLTFUtils._DefaultMaterial;
  90340. };
  90341. // The GLTF default material
  90342. GLTFUtils._DefaultMaterial = null;
  90343. return GLTFUtils;
  90344. }());
  90345. GLTF1.GLTFUtils = GLTFUtils;
  90346. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90347. })(BABYLON || (BABYLON = {}));
  90348. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90349. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90350. var BABYLON;
  90351. (function (BABYLON) {
  90352. var GLTF1;
  90353. (function (GLTF1) {
  90354. var GLTFLoaderExtension = /** @class */ (function () {
  90355. function GLTFLoaderExtension(name) {
  90356. this._name = name;
  90357. }
  90358. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90359. get: function () {
  90360. return this._name;
  90361. },
  90362. enumerable: true,
  90363. configurable: true
  90364. });
  90365. /**
  90366. * Defines an override for loading the runtime
  90367. * Return true to stop further extensions from loading the runtime
  90368. */
  90369. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90370. return false;
  90371. };
  90372. /**
  90373. * Defines an onverride for creating gltf runtime
  90374. * Return true to stop further extensions from creating the runtime
  90375. */
  90376. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90377. return false;
  90378. };
  90379. /**
  90380. * Defines an override for loading buffers
  90381. * Return true to stop further extensions from loading this buffer
  90382. */
  90383. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90384. return false;
  90385. };
  90386. /**
  90387. * Defines an override for loading texture buffers
  90388. * Return true to stop further extensions from loading this texture data
  90389. */
  90390. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90391. return false;
  90392. };
  90393. /**
  90394. * Defines an override for creating textures
  90395. * Return true to stop further extensions from loading this texture
  90396. */
  90397. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90398. return false;
  90399. };
  90400. /**
  90401. * Defines an override for loading shader strings
  90402. * Return true to stop further extensions from loading this shader data
  90403. */
  90404. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90405. return false;
  90406. };
  90407. /**
  90408. * Defines an override for loading materials
  90409. * Return true to stop further extensions from loading this material
  90410. */
  90411. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90412. return false;
  90413. };
  90414. // ---------
  90415. // Utilities
  90416. // ---------
  90417. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90418. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90419. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90420. }, function () {
  90421. setTimeout(function () {
  90422. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90423. });
  90424. });
  90425. };
  90426. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90427. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90428. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90429. }, function () {
  90430. setTimeout(function () {
  90431. onSuccess();
  90432. });
  90433. });
  90434. };
  90435. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90436. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90437. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90438. }, function () {
  90439. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90440. });
  90441. };
  90442. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90443. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90444. };
  90445. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90446. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90447. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90448. }, function () {
  90449. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90450. });
  90451. };
  90452. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90453. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90454. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90455. }, function () {
  90456. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90457. });
  90458. };
  90459. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90460. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90461. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90462. }, function () {
  90463. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90464. });
  90465. };
  90466. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90467. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90468. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90469. }, function () {
  90470. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90471. });
  90472. };
  90473. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90474. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90475. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90476. if (func(loaderExtension)) {
  90477. return;
  90478. }
  90479. }
  90480. defaultFunc();
  90481. };
  90482. return GLTFLoaderExtension;
  90483. }());
  90484. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90485. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90486. })(BABYLON || (BABYLON = {}));
  90487. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90488. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90489. var BABYLON;
  90490. (function (BABYLON) {
  90491. var GLTF1;
  90492. (function (GLTF1) {
  90493. var BinaryExtensionBufferName = "binary_glTF";
  90494. ;
  90495. ;
  90496. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90497. __extends(GLTFBinaryExtension, _super);
  90498. function GLTFBinaryExtension() {
  90499. return _super.call(this, "KHR_binary_glTF") || this;
  90500. }
  90501. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90502. var extensionsUsed = data.json.extensionsUsed;
  90503. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90504. return false;
  90505. }
  90506. this._bin = data.bin;
  90507. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90508. return true;
  90509. };
  90510. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90511. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90512. return false;
  90513. }
  90514. if (id !== BinaryExtensionBufferName) {
  90515. return false;
  90516. }
  90517. onSuccess(this._bin);
  90518. return true;
  90519. };
  90520. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90521. var texture = gltfRuntime.textures[id];
  90522. var source = gltfRuntime.images[texture.source];
  90523. if (!source.extensions || !(this.name in source.extensions)) {
  90524. return false;
  90525. }
  90526. var sourceExt = source.extensions[this.name];
  90527. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90528. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90529. onSuccess(buffer);
  90530. return true;
  90531. };
  90532. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90533. var shader = gltfRuntime.shaders[id];
  90534. if (!shader.extensions || !(this.name in shader.extensions)) {
  90535. return false;
  90536. }
  90537. var binaryExtensionShader = shader.extensions[this.name];
  90538. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90539. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90540. setTimeout(function () {
  90541. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90542. onSuccess(shaderString);
  90543. });
  90544. return true;
  90545. };
  90546. return GLTFBinaryExtension;
  90547. }(GLTF1.GLTFLoaderExtension));
  90548. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90549. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90550. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90551. })(BABYLON || (BABYLON = {}));
  90552. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90553. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90554. var BABYLON;
  90555. (function (BABYLON) {
  90556. var GLTF1;
  90557. (function (GLTF1) {
  90558. ;
  90559. ;
  90560. ;
  90561. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90562. __extends(GLTFMaterialsCommonExtension, _super);
  90563. function GLTFMaterialsCommonExtension() {
  90564. return _super.call(this, "KHR_materials_common") || this;
  90565. }
  90566. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90567. if (!gltfRuntime.extensions)
  90568. return false;
  90569. var extension = gltfRuntime.extensions[this.name];
  90570. if (!extension)
  90571. return false;
  90572. // Create lights
  90573. var lights = extension.lights;
  90574. if (lights) {
  90575. for (var thing in lights) {
  90576. var light = lights[thing];
  90577. switch (light.type) {
  90578. case "ambient":
  90579. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90580. var ambient = light.ambient;
  90581. if (ambient) {
  90582. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90583. }
  90584. break;
  90585. case "point":
  90586. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90587. var point = light.point;
  90588. if (point) {
  90589. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90590. }
  90591. break;
  90592. case "directional":
  90593. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90594. var directional = light.directional;
  90595. if (directional) {
  90596. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90597. }
  90598. break;
  90599. case "spot":
  90600. var spot = light.spot;
  90601. if (spot) {
  90602. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  90603. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90604. }
  90605. break;
  90606. default:
  90607. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90608. break;
  90609. }
  90610. }
  90611. }
  90612. return false;
  90613. };
  90614. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90615. var material = gltfRuntime.materials[id];
  90616. if (!material || !material.extensions)
  90617. return false;
  90618. var extension = material.extensions[this.name];
  90619. if (!extension)
  90620. return false;
  90621. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90622. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90623. if (extension.technique === "CONSTANT") {
  90624. standardMaterial.disableLighting = true;
  90625. }
  90626. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90627. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90628. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90629. // Ambient
  90630. if (typeof extension.values.ambient === "string") {
  90631. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90632. }
  90633. else {
  90634. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90635. }
  90636. // Diffuse
  90637. if (typeof extension.values.diffuse === "string") {
  90638. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90639. }
  90640. else {
  90641. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90642. }
  90643. // Emission
  90644. if (typeof extension.values.emission === "string") {
  90645. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90646. }
  90647. else {
  90648. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90649. }
  90650. // Specular
  90651. if (typeof extension.values.specular === "string") {
  90652. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90653. }
  90654. else {
  90655. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90656. }
  90657. return true;
  90658. };
  90659. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90660. // Create buffer from texture url
  90661. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90662. // Create texture from buffer
  90663. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90664. }, onError);
  90665. };
  90666. return GLTFMaterialsCommonExtension;
  90667. }(GLTF1.GLTFLoaderExtension));
  90668. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90669. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90670. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90671. })(BABYLON || (BABYLON = {}));
  90672. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90673. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90674. var BABYLON;
  90675. (function (BABYLON) {
  90676. var GLTF2;
  90677. (function (GLTF2) {
  90678. var ArrayItem = /** @class */ (function () {
  90679. function ArrayItem() {
  90680. }
  90681. ArrayItem.Assign = function (values) {
  90682. if (values) {
  90683. for (var index = 0; index < values.length; index++) {
  90684. values[index]._index = index;
  90685. }
  90686. }
  90687. };
  90688. return ArrayItem;
  90689. }());
  90690. GLTF2.ArrayItem = ArrayItem;
  90691. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90692. })(BABYLON || (BABYLON = {}));
  90693. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90694. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90695. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90696. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90697. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90698. var BABYLON;
  90699. (function (BABYLON) {
  90700. var GLTF2;
  90701. (function (GLTF2) {
  90702. var GLTFLoader = /** @class */ (function () {
  90703. function GLTFLoader() {
  90704. this._completePromises = new Array();
  90705. this._disposed = false;
  90706. this._state = null;
  90707. this._extensions = {};
  90708. this._defaultSampler = {};
  90709. this._requests = new Array();
  90710. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90711. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90712. this.compileMaterials = false;
  90713. this.useClipPlane = false;
  90714. this.compileShadowGenerators = false;
  90715. this.onDisposeObservable = new BABYLON.Observable();
  90716. this.onMeshLoadedObservable = new BABYLON.Observable();
  90717. this.onTextureLoadedObservable = new BABYLON.Observable();
  90718. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90719. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90720. this.onCompleteObservable = new BABYLON.Observable();
  90721. }
  90722. GLTFLoader._Register = function (name, factory) {
  90723. if (GLTFLoader._Factories[name]) {
  90724. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  90725. return;
  90726. }
  90727. GLTFLoader._Factories[name] = factory;
  90728. // Keep the order of registration so that extensions registered first are called first.
  90729. GLTFLoader._Names.push(name);
  90730. };
  90731. Object.defineProperty(GLTFLoader.prototype, "state", {
  90732. get: function () {
  90733. return this._state;
  90734. },
  90735. enumerable: true,
  90736. configurable: true
  90737. });
  90738. GLTFLoader.prototype.dispose = function () {
  90739. if (this._disposed) {
  90740. return;
  90741. }
  90742. this._disposed = true;
  90743. this.onDisposeObservable.notifyObservers(this);
  90744. this.onDisposeObservable.clear();
  90745. this._clear();
  90746. };
  90747. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90748. var _this = this;
  90749. return Promise.resolve().then(function () {
  90750. var nodes = null;
  90751. if (meshesNames) {
  90752. var nodeMap_1 = {};
  90753. if (_this._gltf.nodes) {
  90754. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  90755. var node = _a[_i];
  90756. if (node.name) {
  90757. nodeMap_1[node.name] = node;
  90758. }
  90759. }
  90760. }
  90761. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  90762. nodes = names.map(function (name) {
  90763. var node = nodeMap_1[name];
  90764. if (!node) {
  90765. throw new Error("Failed to find node " + name);
  90766. }
  90767. return node;
  90768. });
  90769. }
  90770. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  90771. return {
  90772. meshes: _this._getMeshes(),
  90773. particleSystems: [],
  90774. skeletons: _this._getSkeletons(),
  90775. };
  90776. });
  90777. });
  90778. };
  90779. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90780. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  90781. };
  90782. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  90783. var _this = this;
  90784. return Promise.resolve().then(function () {
  90785. _this._loadExtensions();
  90786. _this._babylonScene = scene;
  90787. _this._rootUrl = rootUrl;
  90788. _this._progressCallback = onProgress;
  90789. _this._state = BABYLON.GLTFLoaderState.Loading;
  90790. _this._loadData(data);
  90791. var promises = new Array();
  90792. if (nodes) {
  90793. promises.push(_this._loadNodesAsync(nodes));
  90794. }
  90795. else {
  90796. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  90797. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  90798. }
  90799. if (_this.compileMaterials) {
  90800. promises.push(_this._compileMaterialsAsync());
  90801. }
  90802. if (_this.compileShadowGenerators) {
  90803. promises.push(_this._compileShadowGeneratorsAsync());
  90804. }
  90805. return Promise.all(promises).then(function () {
  90806. _this._state = BABYLON.GLTFLoaderState.Ready;
  90807. _this._startAnimations();
  90808. BABYLON.Tools.SetImmediate(function () {
  90809. if (!_this._disposed) {
  90810. Promise.all(_this._completePromises).then(function () {
  90811. _this._state = BABYLON.GLTFLoaderState.Complete;
  90812. _this.onCompleteObservable.notifyObservers(_this);
  90813. _this.onCompleteObservable.clear();
  90814. _this._clear();
  90815. }).catch(function (error) {
  90816. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90817. _this._clear();
  90818. });
  90819. }
  90820. });
  90821. });
  90822. }).catch(function (error) {
  90823. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90824. _this._clear();
  90825. throw error;
  90826. });
  90827. };
  90828. GLTFLoader.prototype._loadExtensions = function () {
  90829. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  90830. var name_1 = _a[_i];
  90831. var extension = GLTFLoader._Factories[name_1](this);
  90832. this._extensions[name_1] = extension;
  90833. this.onExtensionLoadedObservable.notifyObservers(extension);
  90834. }
  90835. this.onExtensionLoadedObservable.clear();
  90836. };
  90837. GLTFLoader.prototype._loadData = function (data) {
  90838. this._gltf = data.json;
  90839. this._setupData();
  90840. if (data.bin) {
  90841. var buffers = this._gltf.buffers;
  90842. if (buffers && buffers[0] && !buffers[0].uri) {
  90843. var binaryBuffer = buffers[0];
  90844. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  90845. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  90846. }
  90847. binaryBuffer._data = Promise.resolve(data.bin);
  90848. }
  90849. else {
  90850. BABYLON.Tools.Warn("Unexpected BIN chunk");
  90851. }
  90852. }
  90853. };
  90854. GLTFLoader.prototype._setupData = function () {
  90855. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  90856. GLTF2.ArrayItem.Assign(this._gltf.animations);
  90857. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  90858. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  90859. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  90860. GLTF2.ArrayItem.Assign(this._gltf.images);
  90861. GLTF2.ArrayItem.Assign(this._gltf.materials);
  90862. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  90863. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  90864. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  90865. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  90866. GLTF2.ArrayItem.Assign(this._gltf.skins);
  90867. GLTF2.ArrayItem.Assign(this._gltf.textures);
  90868. if (this._gltf.nodes) {
  90869. var nodeParents = {};
  90870. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  90871. var node = _a[_i];
  90872. if (node.children) {
  90873. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  90874. var index = _c[_b];
  90875. nodeParents[index] = node._index;
  90876. }
  90877. }
  90878. }
  90879. var rootNode = this._createRootNode();
  90880. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  90881. var node = _e[_d];
  90882. var parentIndex = nodeParents[node._index];
  90883. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  90884. }
  90885. }
  90886. };
  90887. GLTFLoader.prototype._createRootNode = function () {
  90888. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  90889. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  90890. switch (this.coordinateSystemMode) {
  90891. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  90892. if (!this._babylonScene.useRightHandedSystem) {
  90893. rootNode.rotation = [0, 1, 0, 0];
  90894. rootNode.scale = [1, 1, -1];
  90895. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  90896. }
  90897. break;
  90898. }
  90899. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  90900. this._babylonScene.useRightHandedSystem = true;
  90901. break;
  90902. }
  90903. default: {
  90904. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  90905. }
  90906. }
  90907. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  90908. return rootNode;
  90909. };
  90910. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  90911. var promises = new Array();
  90912. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  90913. var node = nodes_1[_i];
  90914. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90915. }
  90916. promises.push(this._loadAnimationsAsync());
  90917. return Promise.all(promises).then(function () { });
  90918. };
  90919. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  90920. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  90921. if (promise) {
  90922. return promise;
  90923. }
  90924. var promises = new Array();
  90925. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  90926. var index = _a[_i];
  90927. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  90928. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90929. }
  90930. promises.push(this._loadAnimationsAsync());
  90931. return Promise.all(promises).then(function () { });
  90932. };
  90933. GLTFLoader.prototype._getMeshes = function () {
  90934. var meshes = new Array();
  90935. // Root mesh is always first.
  90936. meshes.push(this._rootBabylonMesh);
  90937. var nodes = this._gltf.nodes;
  90938. if (nodes) {
  90939. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  90940. var node = nodes_2[_i];
  90941. if (node._babylonMesh) {
  90942. meshes.push(node._babylonMesh);
  90943. }
  90944. }
  90945. }
  90946. return meshes;
  90947. };
  90948. GLTFLoader.prototype._getSkeletons = function () {
  90949. var skeletons = new Array();
  90950. var skins = this._gltf.skins;
  90951. if (skins) {
  90952. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  90953. var skin = skins_1[_i];
  90954. if (skin._babylonSkeleton) {
  90955. skeletons.push(skin._babylonSkeleton);
  90956. }
  90957. }
  90958. }
  90959. return skeletons;
  90960. };
  90961. GLTFLoader.prototype._startAnimations = function () {
  90962. var animations = this._gltf.animations;
  90963. if (!animations) {
  90964. return;
  90965. }
  90966. switch (this.animationStartMode) {
  90967. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  90968. // do nothing
  90969. break;
  90970. }
  90971. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  90972. var animation = animations[0];
  90973. animation._babylonAnimationGroup.start(true);
  90974. break;
  90975. }
  90976. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  90977. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  90978. var animation = animations_1[_i];
  90979. animation._babylonAnimationGroup.start(true);
  90980. }
  90981. break;
  90982. }
  90983. default: {
  90984. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  90985. return;
  90986. }
  90987. }
  90988. };
  90989. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  90990. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  90991. if (promise) {
  90992. return promise;
  90993. }
  90994. if (node._babylonMesh) {
  90995. throw new Error(context + ": Invalid recursive node hierarchy");
  90996. }
  90997. var promises = new Array();
  90998. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  90999. node._babylonMesh = babylonMesh;
  91000. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91001. node._babylonAnimationTargets.push(babylonMesh);
  91002. GLTFLoader._LoadTransform(node, babylonMesh);
  91003. if (node.mesh != undefined) {
  91004. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  91005. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  91006. }
  91007. if (node.children) {
  91008. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  91009. var index = _a[_i];
  91010. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  91011. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  91012. }
  91013. }
  91014. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91015. return Promise.all(promises).then(function () { });
  91016. };
  91017. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  91018. // TODO: instancing
  91019. var promises = new Array();
  91020. var primitives = mesh.primitives;
  91021. if (!primitives || primitives.length === 0) {
  91022. throw new Error(context + ": Primitives are missing");
  91023. }
  91024. GLTF2.ArrayItem.Assign(primitives);
  91025. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  91026. var primitive = primitives_1[_i];
  91027. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  91028. }
  91029. if (node.skin != undefined) {
  91030. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  91031. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  91032. }
  91033. return Promise.all(promises).then(function () {
  91034. if (node._primitiveBabylonMeshes) {
  91035. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91036. var primitiveBabylonMesh = _a[_i];
  91037. primitiveBabylonMesh._refreshBoundingInfo(true);
  91038. }
  91039. }
  91040. });
  91041. };
  91042. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  91043. var _this = this;
  91044. var promises = new Array();
  91045. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  91046. babylonMesh.setEnabled(false);
  91047. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  91048. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  91049. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  91050. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  91051. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  91052. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  91053. }));
  91054. if (primitive.material == undefined) {
  91055. babylonMesh.material = this._getDefaultMaterial();
  91056. }
  91057. else {
  91058. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  91059. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  91060. }
  91061. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91062. return Promise.all(promises).then(function () {
  91063. babylonMesh.setEnabled(true);
  91064. });
  91065. };
  91066. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  91067. var _this = this;
  91068. var attributes = primitive.attributes;
  91069. if (!attributes) {
  91070. throw new Error(context + ": Attributes are missing");
  91071. }
  91072. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  91073. // TODO: handle other primitive modes
  91074. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  91075. }
  91076. var promises = new Array();
  91077. var babylonVertexData = new BABYLON.VertexData();
  91078. if (primitive.indices == undefined) {
  91079. var positionAccessorIndex = attributes["POSITION"];
  91080. if (positionAccessorIndex != undefined) {
  91081. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  91082. babylonVertexData.indices = new Uint32Array(accessor.count);
  91083. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  91084. babylonVertexData.indices[i] = i;
  91085. }
  91086. }
  91087. }
  91088. else {
  91089. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  91090. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  91091. babylonVertexData.indices = data;
  91092. }));
  91093. }
  91094. var loadAttribute = function (attribute, kind) {
  91095. if (attributes[attribute] == undefined) {
  91096. return;
  91097. }
  91098. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  91099. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  91100. babylonMesh._delayInfo.push(kind);
  91101. }
  91102. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91103. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91104. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  91105. if (attribute === "COLOR_0") {
  91106. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  91107. babylonMesh.hasVertexAlpha = true;
  91108. if (accessor.type === "VEC3") {
  91109. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  91110. }
  91111. }
  91112. babylonVertexData.set(attributeData, kind);
  91113. }));
  91114. };
  91115. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  91116. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  91117. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  91118. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  91119. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  91120. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  91121. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  91122. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  91123. return Promise.all(promises).then(function () {
  91124. return babylonVertexData;
  91125. });
  91126. };
  91127. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  91128. if (!primitive.targets) {
  91129. return;
  91130. }
  91131. if (node._numMorphTargets == undefined) {
  91132. node._numMorphTargets = primitive.targets.length;
  91133. }
  91134. else if (primitive.targets.length !== node._numMorphTargets) {
  91135. throw new Error(context + ": Primitives do not have the same number of targets");
  91136. }
  91137. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  91138. for (var index = 0; index < primitive.targets.length; index++) {
  91139. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  91140. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  91141. // TODO: tell the target whether it has positions, normals, tangents
  91142. }
  91143. };
  91144. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  91145. if (!primitive.targets) {
  91146. return Promise.resolve();
  91147. }
  91148. var promises = new Array();
  91149. var morphTargetManager = babylonMesh.morphTargetManager;
  91150. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  91151. var babylonMorphTarget = morphTargetManager.getTarget(index);
  91152. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  91153. }
  91154. return Promise.all(promises).then(function () { });
  91155. };
  91156. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  91157. var _this = this;
  91158. var promises = new Array();
  91159. var loadAttribute = function (attribute, setData) {
  91160. if (attributes[attribute] == undefined) {
  91161. return;
  91162. }
  91163. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91164. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91165. setData(data);
  91166. }));
  91167. };
  91168. loadAttribute("POSITION", function (data) {
  91169. if (babylonVertexData.positions) {
  91170. for (var i = 0; i < data.length; i++) {
  91171. data[i] += babylonVertexData.positions[i];
  91172. }
  91173. babylonMorphTarget.setPositions(data);
  91174. }
  91175. });
  91176. loadAttribute("NORMAL", function (data) {
  91177. if (babylonVertexData.normals) {
  91178. for (var i = 0; i < data.length; i++) {
  91179. data[i] += babylonVertexData.normals[i];
  91180. }
  91181. babylonMorphTarget.setNormals(data);
  91182. }
  91183. });
  91184. loadAttribute("TANGENT", function (data) {
  91185. if (babylonVertexData.tangents) {
  91186. // Tangent data for morph targets is stored as xyz delta.
  91187. // The vertexData.tangent is stored as xyzw.
  91188. // So we need to skip every fourth vertexData.tangent.
  91189. for (var i = 0, j = 0; i < data.length; i++) {
  91190. data[i] += babylonVertexData.tangents[j++];
  91191. if ((i + 1) % 3 == 0) {
  91192. j++;
  91193. }
  91194. }
  91195. babylonMorphTarget.setTangents(data);
  91196. }
  91197. });
  91198. return Promise.all(promises).then(function () { });
  91199. };
  91200. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91201. if (accessor.componentType == 5126 /* FLOAT */) {
  91202. return data;
  91203. }
  91204. var factor = 1;
  91205. if (accessor.normalized) {
  91206. switch (accessor.componentType) {
  91207. case 5121 /* UNSIGNED_BYTE */: {
  91208. factor = 1 / 255;
  91209. break;
  91210. }
  91211. case 5123 /* UNSIGNED_SHORT */: {
  91212. factor = 1 / 65535;
  91213. break;
  91214. }
  91215. default: {
  91216. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91217. }
  91218. }
  91219. }
  91220. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91221. for (var i = 0; i < result.length; i++) {
  91222. result[i] = data[i] * factor;
  91223. }
  91224. return result;
  91225. };
  91226. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91227. var result = new Float32Array(data.length / 3 * 4);
  91228. var offset = 0;
  91229. for (var i = 0; i < result.length; i++) {
  91230. if ((i + 1) % 4 === 0) {
  91231. result[i] = 1;
  91232. }
  91233. else {
  91234. result[i] = data[offset++];
  91235. }
  91236. }
  91237. return result;
  91238. };
  91239. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91240. var position = BABYLON.Vector3.Zero();
  91241. var rotation = BABYLON.Quaternion.Identity();
  91242. var scaling = BABYLON.Vector3.One();
  91243. if (node.matrix) {
  91244. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91245. matrix.decompose(scaling, rotation, position);
  91246. }
  91247. else {
  91248. if (node.translation)
  91249. position = BABYLON.Vector3.FromArray(node.translation);
  91250. if (node.rotation)
  91251. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91252. if (node.scale)
  91253. scaling = BABYLON.Vector3.FromArray(node.scale);
  91254. }
  91255. babylonNode.position = position;
  91256. babylonNode.rotationQuaternion = rotation;
  91257. babylonNode.scaling = scaling;
  91258. };
  91259. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91260. var _this = this;
  91261. var assignSkeleton = function () {
  91262. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91263. var babylonMesh = _a[_i];
  91264. babylonMesh.skeleton = skin._babylonSkeleton;
  91265. }
  91266. node._babylonMesh.parent = _this._rootBabylonMesh;
  91267. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91268. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91269. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91270. };
  91271. if (skin._loaded) {
  91272. assignSkeleton();
  91273. return skin._loaded;
  91274. }
  91275. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91276. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91277. var skeletonId = "skeleton" + skin._index;
  91278. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91279. skin._babylonSkeleton = babylonSkeleton;
  91280. _this._loadBones(context, skin, inverseBindMatricesData);
  91281. assignSkeleton();
  91282. }));
  91283. };
  91284. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91285. if (skin.inverseBindMatrices == undefined) {
  91286. return Promise.resolve(null);
  91287. }
  91288. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91289. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91290. return data;
  91291. });
  91292. };
  91293. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91294. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91295. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91296. node._babylonAnimationTargets.push(babylonBone);
  91297. return babylonBone;
  91298. };
  91299. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91300. var babylonBones = {};
  91301. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91302. var index = _a[_i];
  91303. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91304. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91305. }
  91306. };
  91307. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91308. var babylonBone = babylonBones[node._index];
  91309. if (babylonBone) {
  91310. return babylonBone;
  91311. }
  91312. var boneIndex = skin.joints.indexOf(node._index);
  91313. var baseMatrix = BABYLON.Matrix.Identity();
  91314. if (inverseBindMatricesData && boneIndex !== -1) {
  91315. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91316. baseMatrix.invertToRef(baseMatrix);
  91317. }
  91318. var babylonParentBone = null;
  91319. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91320. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91321. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91322. }
  91323. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91324. babylonBones[node._index] = babylonBone;
  91325. return babylonBone;
  91326. };
  91327. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91328. return node.matrix ?
  91329. BABYLON.Matrix.FromArray(node.matrix) :
  91330. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  91331. };
  91332. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91333. var animations = this._gltf.animations;
  91334. if (!animations) {
  91335. return Promise.resolve();
  91336. }
  91337. var promises = new Array();
  91338. for (var index = 0; index < animations.length; index++) {
  91339. var animation = animations[index];
  91340. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91341. }
  91342. return Promise.all(promises).then(function () { });
  91343. };
  91344. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91345. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91346. animation._babylonAnimationGroup = babylonAnimationGroup;
  91347. var promises = new Array();
  91348. GLTF2.ArrayItem.Assign(animation.channels);
  91349. GLTF2.ArrayItem.Assign(animation.samplers);
  91350. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91351. var channel = _a[_i];
  91352. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91353. }
  91354. return Promise.all(promises).then(function () {
  91355. babylonAnimationGroup.normalize();
  91356. });
  91357. };
  91358. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91359. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91360. if (!targetNode._babylonMesh) {
  91361. return Promise.resolve();
  91362. }
  91363. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91364. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91365. var targetPath;
  91366. var animationType;
  91367. switch (channel.target.path) {
  91368. case "translation" /* TRANSLATION */: {
  91369. targetPath = "position";
  91370. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91371. break;
  91372. }
  91373. case "rotation" /* ROTATION */: {
  91374. targetPath = "rotationQuaternion";
  91375. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91376. break;
  91377. }
  91378. case "scale" /* SCALE */: {
  91379. targetPath = "scaling";
  91380. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91381. break;
  91382. }
  91383. case "weights" /* WEIGHTS */: {
  91384. targetPath = "influence";
  91385. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91386. break;
  91387. }
  91388. default: {
  91389. throw new Error(context + ": Invalid target path " + channel.target.path);
  91390. }
  91391. }
  91392. var outputBufferOffset = 0;
  91393. var getNextOutputValue;
  91394. switch (targetPath) {
  91395. case "position": {
  91396. getNextOutputValue = function () {
  91397. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91398. outputBufferOffset += 3;
  91399. return value;
  91400. };
  91401. break;
  91402. }
  91403. case "rotationQuaternion": {
  91404. getNextOutputValue = function () {
  91405. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91406. outputBufferOffset += 4;
  91407. return value;
  91408. };
  91409. break;
  91410. }
  91411. case "scaling": {
  91412. getNextOutputValue = function () {
  91413. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91414. outputBufferOffset += 3;
  91415. return value;
  91416. };
  91417. break;
  91418. }
  91419. case "influence": {
  91420. getNextOutputValue = function () {
  91421. var value = new Array(targetNode._numMorphTargets);
  91422. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91423. value[i] = data.output[outputBufferOffset++];
  91424. }
  91425. return value;
  91426. };
  91427. break;
  91428. }
  91429. }
  91430. var getNextKey;
  91431. switch (data.interpolation) {
  91432. case "STEP" /* STEP */: {
  91433. getNextKey = function (frameIndex) { return ({
  91434. frame: data.input[frameIndex],
  91435. value: getNextOutputValue(),
  91436. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91437. }); };
  91438. break;
  91439. }
  91440. case "LINEAR" /* LINEAR */: {
  91441. getNextKey = function (frameIndex) { return ({
  91442. frame: data.input[frameIndex],
  91443. value: getNextOutputValue()
  91444. }); };
  91445. break;
  91446. }
  91447. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91448. getNextKey = function (frameIndex) { return ({
  91449. frame: data.input[frameIndex],
  91450. inTangent: getNextOutputValue(),
  91451. value: getNextOutputValue(),
  91452. outTangent: getNextOutputValue()
  91453. }); };
  91454. break;
  91455. }
  91456. }
  91457. var keys;
  91458. if (data.input.length === 1) {
  91459. var key = getNextKey(0);
  91460. keys = [
  91461. { frame: key.frame, value: key.value },
  91462. { frame: key.frame + 1, value: key.value }
  91463. ];
  91464. }
  91465. else {
  91466. keys = new Array(data.input.length);
  91467. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91468. keys[frameIndex] = getNextKey(frameIndex);
  91469. }
  91470. }
  91471. if (targetPath === "influence") {
  91472. var _loop_1 = function (targetIndex) {
  91473. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91474. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91475. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91476. frame: key.frame,
  91477. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91478. value: key.value[targetIndex],
  91479. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91480. }); }));
  91481. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91482. var babylonMesh = _a[_i];
  91483. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91484. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91485. }
  91486. };
  91487. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91488. _loop_1(targetIndex);
  91489. }
  91490. }
  91491. else {
  91492. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91493. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91494. babylonAnimation.setKeys(keys);
  91495. if (targetNode._babylonAnimationTargets) {
  91496. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91497. var target = _a[_i];
  91498. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91499. }
  91500. }
  91501. }
  91502. });
  91503. };
  91504. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91505. if (sampler._data) {
  91506. return sampler._data;
  91507. }
  91508. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91509. switch (interpolation) {
  91510. case "STEP" /* STEP */:
  91511. case "LINEAR" /* LINEAR */:
  91512. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91513. break;
  91514. }
  91515. default: {
  91516. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91517. }
  91518. }
  91519. var inputData;
  91520. var outputData;
  91521. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91522. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91523. sampler._data = Promise.all([
  91524. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91525. inputData = data;
  91526. }),
  91527. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91528. outputData = data;
  91529. })
  91530. ]).then(function () {
  91531. return {
  91532. input: inputData,
  91533. interpolation: interpolation,
  91534. output: outputData,
  91535. };
  91536. });
  91537. return sampler._data;
  91538. };
  91539. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91540. if (buffer._data) {
  91541. return buffer._data;
  91542. }
  91543. if (!buffer.uri) {
  91544. throw new Error(context + ": Uri is missing");
  91545. }
  91546. buffer._data = this._loadUriAsync(context, buffer.uri);
  91547. return buffer._data;
  91548. };
  91549. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91550. if (bufferView._data) {
  91551. return bufferView._data;
  91552. }
  91553. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91554. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91555. try {
  91556. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91557. }
  91558. catch (e) {
  91559. throw new Error(context + ": " + e.message);
  91560. }
  91561. });
  91562. return bufferView._data;
  91563. };
  91564. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91565. var _this = this;
  91566. if (accessor.sparse) {
  91567. throw new Error(context + ": Sparse accessors are not currently supported");
  91568. }
  91569. if (accessor._data) {
  91570. return accessor._data;
  91571. }
  91572. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91573. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91574. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91575. var byteOffset = accessor.byteOffset || 0;
  91576. var byteStride = bufferView.byteStride;
  91577. if (byteStride === 0) {
  91578. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91579. }
  91580. try {
  91581. switch (accessor.componentType) {
  91582. case 5120 /* BYTE */: {
  91583. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91584. }
  91585. case 5121 /* UNSIGNED_BYTE */: {
  91586. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91587. }
  91588. case 5122 /* SHORT */: {
  91589. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91590. }
  91591. case 5123 /* UNSIGNED_SHORT */: {
  91592. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91593. }
  91594. case 5125 /* UNSIGNED_INT */: {
  91595. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91596. }
  91597. case 5126 /* FLOAT */: {
  91598. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91599. }
  91600. default: {
  91601. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91602. }
  91603. }
  91604. }
  91605. catch (e) {
  91606. throw new Error(context + ": " + e);
  91607. }
  91608. });
  91609. return accessor._data;
  91610. };
  91611. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91612. byteOffset += data.byteOffset;
  91613. var targetLength = count * numComponents;
  91614. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91615. return new typedArray(data.buffer, byteOffset, targetLength);
  91616. }
  91617. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91618. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91619. var targetBuffer = new typedArray(targetLength);
  91620. var sourceIndex = 0;
  91621. var targetIndex = 0;
  91622. while (targetIndex < targetLength) {
  91623. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91624. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91625. targetIndex++;
  91626. }
  91627. sourceIndex += elementStride;
  91628. }
  91629. return targetBuffer;
  91630. };
  91631. GLTFLoader.prototype._getDefaultMaterial = function () {
  91632. var id = "__gltf_default";
  91633. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91634. if (!babylonMaterial) {
  91635. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91636. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91637. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91638. babylonMaterial.metallic = 1;
  91639. babylonMaterial.roughness = 1;
  91640. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91641. }
  91642. return babylonMaterial;
  91643. };
  91644. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91645. var promises = new Array();
  91646. var babylonMaterial = material._babylonMaterial;
  91647. // Ensure metallic workflow
  91648. babylonMaterial.metallic = 1;
  91649. babylonMaterial.roughness = 1;
  91650. var properties = material.pbrMetallicRoughness;
  91651. if (properties) {
  91652. if (properties.baseColorFactor) {
  91653. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91654. babylonMaterial.alpha = properties.baseColorFactor[3];
  91655. }
  91656. else {
  91657. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91658. }
  91659. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91660. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91661. if (properties.baseColorTexture) {
  91662. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91663. babylonMaterial.albedoTexture = texture;
  91664. }));
  91665. }
  91666. if (properties.metallicRoughnessTexture) {
  91667. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91668. babylonMaterial.metallicTexture = texture;
  91669. }));
  91670. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91671. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91672. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91673. }
  91674. }
  91675. this._loadMaterialAlphaProperties(context, material);
  91676. return Promise.all(promises).then(function () { });
  91677. };
  91678. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91679. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91680. if (promise) {
  91681. return promise;
  91682. }
  91683. material._babylonMeshes = material._babylonMeshes || [];
  91684. material._babylonMeshes.push(babylonMesh);
  91685. if (material._loaded) {
  91686. babylonMesh.material = material._babylonMaterial;
  91687. return material._loaded;
  91688. }
  91689. var promises = new Array();
  91690. var babylonMaterial = this._createMaterial(material);
  91691. material._babylonMaterial = babylonMaterial;
  91692. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91693. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91694. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91695. babylonMesh.material = babylonMaterial;
  91696. return (material._loaded = Promise.all(promises).then(function () { }));
  91697. };
  91698. GLTFLoader.prototype._createMaterial = function (material) {
  91699. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91700. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91701. return babylonMaterial;
  91702. };
  91703. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91704. var promises = new Array();
  91705. var babylonMaterial = material._babylonMaterial;
  91706. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  91707. if (material.doubleSided) {
  91708. babylonMaterial.backFaceCulling = false;
  91709. babylonMaterial.twoSidedLighting = true;
  91710. }
  91711. if (material.normalTexture) {
  91712. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  91713. babylonMaterial.bumpTexture = texture;
  91714. }));
  91715. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  91716. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  91717. if (material.normalTexture.scale != undefined) {
  91718. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  91719. }
  91720. }
  91721. if (material.occlusionTexture) {
  91722. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  91723. babylonMaterial.ambientTexture = texture;
  91724. }));
  91725. babylonMaterial.useAmbientInGrayScale = true;
  91726. if (material.occlusionTexture.strength != undefined) {
  91727. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  91728. }
  91729. }
  91730. if (material.emissiveTexture) {
  91731. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  91732. babylonMaterial.emissiveTexture = texture;
  91733. }));
  91734. }
  91735. return Promise.all(promises).then(function () { });
  91736. };
  91737. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  91738. var babylonMaterial = material._babylonMaterial;
  91739. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  91740. switch (alphaMode) {
  91741. case "OPAQUE" /* OPAQUE */: {
  91742. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91743. break;
  91744. }
  91745. case "MASK" /* MASK */: {
  91746. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  91747. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  91748. if (babylonMaterial.alpha) {
  91749. if (babylonMaterial.alpha === 0) {
  91750. babylonMaterial.alphaCutOff = 1;
  91751. }
  91752. else {
  91753. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  91754. }
  91755. babylonMaterial.alpha = 1;
  91756. }
  91757. if (babylonMaterial.albedoTexture) {
  91758. babylonMaterial.albedoTexture.hasAlpha = true;
  91759. }
  91760. break;
  91761. }
  91762. case "BLEND" /* BLEND */: {
  91763. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  91764. if (babylonMaterial.albedoTexture) {
  91765. babylonMaterial.albedoTexture.hasAlpha = true;
  91766. babylonMaterial.useAlphaFromAlbedoTexture = true;
  91767. }
  91768. break;
  91769. }
  91770. default: {
  91771. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  91772. }
  91773. }
  91774. };
  91775. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  91776. var _this = this;
  91777. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  91778. context = "#/textures/" + textureInfo.index;
  91779. var promises = new Array();
  91780. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  91781. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  91782. var deferred = new BABYLON.Deferred();
  91783. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  91784. if (!_this._disposed) {
  91785. deferred.resolve();
  91786. }
  91787. }, function (message, exception) {
  91788. if (!_this._disposed) {
  91789. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  91790. }
  91791. });
  91792. promises.push(deferred.promise);
  91793. babylonTexture.name = texture.name || "texture" + texture._index;
  91794. babylonTexture.wrapU = samplerData.wrapU;
  91795. babylonTexture.wrapV = samplerData.wrapV;
  91796. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  91797. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  91798. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  91799. babylonTexture.updateURL(objectURL);
  91800. }));
  91801. assign(babylonTexture);
  91802. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  91803. return Promise.all(promises).then(function () { });
  91804. };
  91805. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  91806. if (!sampler._data) {
  91807. sampler._data = {
  91808. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  91809. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  91810. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  91811. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  91812. };
  91813. }
  91814. ;
  91815. return sampler._data;
  91816. };
  91817. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  91818. if (image._objectURL) {
  91819. return image._objectURL;
  91820. }
  91821. var promise;
  91822. if (image.uri) {
  91823. promise = this._loadUriAsync(context, image.uri);
  91824. }
  91825. else {
  91826. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  91827. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  91828. }
  91829. image._objectURL = promise.then(function (data) {
  91830. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  91831. });
  91832. return image._objectURL;
  91833. };
  91834. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  91835. var _this = this;
  91836. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  91837. if (promise) {
  91838. return promise;
  91839. }
  91840. if (!GLTFLoader._ValidateUri(uri)) {
  91841. throw new Error(context + ": Uri '" + uri + "' is invalid");
  91842. }
  91843. if (BABYLON.Tools.IsBase64(uri)) {
  91844. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  91845. }
  91846. return new Promise(function (resolve, reject) {
  91847. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  91848. if (!_this._disposed) {
  91849. resolve(new Uint8Array(data));
  91850. }
  91851. }, function (event) {
  91852. if (!_this._disposed) {
  91853. try {
  91854. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  91855. request._lengthComputable = event.lengthComputable;
  91856. request._loaded = event.loaded;
  91857. request._total = event.total;
  91858. _this._onProgress();
  91859. }
  91860. }
  91861. catch (e) {
  91862. reject(e);
  91863. }
  91864. }
  91865. }, _this._babylonScene.database, true, function (request, exception) {
  91866. if (!_this._disposed) {
  91867. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  91868. }
  91869. });
  91870. _this._requests.push(request);
  91871. });
  91872. };
  91873. GLTFLoader.prototype._onProgress = function () {
  91874. if (!this._progressCallback) {
  91875. return;
  91876. }
  91877. var lengthComputable = true;
  91878. var loaded = 0;
  91879. var total = 0;
  91880. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91881. var request = _a[_i];
  91882. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  91883. return;
  91884. }
  91885. lengthComputable = lengthComputable && request._lengthComputable;
  91886. loaded += request._loaded;
  91887. total += request._total;
  91888. }
  91889. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  91890. };
  91891. GLTFLoader._GetProperty = function (context, array, index) {
  91892. if (!array || index == undefined || !array[index]) {
  91893. throw new Error(context + ": Failed to find index " + index);
  91894. }
  91895. return array[index];
  91896. };
  91897. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  91898. // Set defaults if undefined
  91899. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  91900. switch (mode) {
  91901. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91902. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91903. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91904. default:
  91905. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  91906. return BABYLON.Texture.WRAP_ADDRESSMODE;
  91907. }
  91908. };
  91909. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  91910. // Set defaults if undefined
  91911. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  91912. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  91913. if (magFilter === 9729 /* LINEAR */) {
  91914. switch (minFilter) {
  91915. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  91916. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  91917. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  91918. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  91919. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  91920. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91921. default:
  91922. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91923. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91924. }
  91925. }
  91926. else {
  91927. if (magFilter !== 9728 /* NEAREST */) {
  91928. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  91929. }
  91930. switch (minFilter) {
  91931. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  91932. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  91933. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91934. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  91935. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  91936. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  91937. default:
  91938. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91939. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91940. }
  91941. }
  91942. };
  91943. GLTFLoader._GetNumComponents = function (context, type) {
  91944. switch (type) {
  91945. case "SCALAR": return 1;
  91946. case "VEC2": return 2;
  91947. case "VEC3": return 3;
  91948. case "VEC4": return 4;
  91949. case "MAT2": return 4;
  91950. case "MAT3": return 9;
  91951. case "MAT4": return 16;
  91952. }
  91953. throw new Error(context + ": Invalid type " + type);
  91954. };
  91955. GLTFLoader._ValidateUri = function (uri) {
  91956. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  91957. };
  91958. GLTFLoader.prototype._compileMaterialsAsync = function () {
  91959. var promises = new Array();
  91960. if (this._gltf.materials) {
  91961. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  91962. var material = _a[_i];
  91963. var babylonMaterial = material._babylonMaterial;
  91964. var babylonMeshes = material._babylonMeshes;
  91965. if (babylonMaterial && babylonMeshes) {
  91966. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  91967. var babylonMesh = babylonMeshes_1[_b];
  91968. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  91969. if (this.useClipPlane) {
  91970. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  91971. }
  91972. }
  91973. }
  91974. }
  91975. }
  91976. return Promise.all(promises).then(function () { });
  91977. };
  91978. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  91979. var promises = new Array();
  91980. var lights = this._babylonScene.lights;
  91981. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  91982. var light = lights_1[_i];
  91983. var generator = light.getShadowGenerator();
  91984. if (generator) {
  91985. promises.push(generator.forceCompilationAsync());
  91986. }
  91987. }
  91988. return Promise.all(promises).then(function () { });
  91989. };
  91990. GLTFLoader.prototype._clear = function () {
  91991. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91992. var request = _a[_i];
  91993. request.abort();
  91994. }
  91995. this._requests.length = 0;
  91996. if (this._gltf && this._gltf.images) {
  91997. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  91998. var image = _c[_b];
  91999. if (image._objectURL) {
  92000. image._objectURL.then(function (value) {
  92001. URL.revokeObjectURL(value);
  92002. });
  92003. image._objectURL = undefined;
  92004. }
  92005. }
  92006. }
  92007. delete this._gltf;
  92008. delete this._babylonScene;
  92009. this._completePromises.length = 0;
  92010. this._extensions = {};
  92011. delete this._rootBabylonMesh;
  92012. delete this._progressCallback;
  92013. this.onMeshLoadedObservable.clear();
  92014. this.onTextureLoadedObservable.clear();
  92015. this.onMaterialLoadedObservable.clear();
  92016. };
  92017. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  92018. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92019. var name_2 = _a[_i];
  92020. var extension = this._extensions[name_2];
  92021. if (extension.enabled) {
  92022. var promise = actionAsync(extension);
  92023. if (promise) {
  92024. return promise;
  92025. }
  92026. }
  92027. }
  92028. return null;
  92029. };
  92030. GLTFLoader._Names = new Array();
  92031. GLTFLoader._Factories = {};
  92032. return GLTFLoader;
  92033. }());
  92034. GLTF2.GLTFLoader = GLTFLoader;
  92035. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  92036. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92037. })(BABYLON || (BABYLON = {}));
  92038. //# sourceMappingURL=babylon.glTFLoader.js.map
  92039. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92040. var BABYLON;
  92041. (function (BABYLON) {
  92042. var GLTF2;
  92043. (function (GLTF2) {
  92044. var GLTFLoaderExtension = /** @class */ (function () {
  92045. function GLTFLoaderExtension(loader) {
  92046. this.enabled = true;
  92047. this._loader = loader;
  92048. }
  92049. // #region Overridable Methods
  92050. /** Override this method to modify the default behavior for loading scenes. */
  92051. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  92052. /** Override this method to modify the default behavior for loading nodes. */
  92053. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  92054. /** Override this method to modify the default behavior for loading materials. */
  92055. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  92056. /** Override this method to modify the default behavior for loading uris. */
  92057. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  92058. // #endregion
  92059. /** Helper method called by a loader extension to load an glTF extension. */
  92060. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  92061. var _this = this;
  92062. if (!property.extensions) {
  92063. return null;
  92064. }
  92065. var extensions = property.extensions;
  92066. var extension = extensions[this.name];
  92067. if (!extension) {
  92068. return null;
  92069. }
  92070. // Clear out the extension before executing the action to avoid recursing into the same property.
  92071. delete extensions[this.name];
  92072. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  92073. // Restore the extension after completing the action.
  92074. extensions[_this.name] = extension;
  92075. });
  92076. };
  92077. /** Helper method called by the loader to allow extensions to override loading scenes. */
  92078. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  92079. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  92080. };
  92081. /** Helper method called by the loader to allow extensions to override loading nodes. */
  92082. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  92083. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  92084. };
  92085. /** Helper method called by the loader to allow extensions to override loading materials. */
  92086. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  92087. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  92088. };
  92089. /** Helper method called by the loader to allow extensions to override loading uris. */
  92090. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  92091. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  92092. };
  92093. return GLTFLoaderExtension;
  92094. }());
  92095. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  92096. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92097. })(BABYLON || (BABYLON = {}));
  92098. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92099. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92100. var BABYLON;
  92101. (function (BABYLON) {
  92102. var GLTF2;
  92103. (function (GLTF2) {
  92104. var Extensions;
  92105. (function (Extensions) {
  92106. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  92107. var NAME = "MSFT_lod";
  92108. var MSFT_lod = /** @class */ (function (_super) {
  92109. __extends(MSFT_lod, _super);
  92110. function MSFT_lod() {
  92111. var _this = _super !== null && _super.apply(this, arguments) || this;
  92112. _this.name = NAME;
  92113. /**
  92114. * Maximum number of LODs to load, starting from the lowest LOD.
  92115. */
  92116. _this.maxLODsToLoad = Number.MAX_VALUE;
  92117. _this._loadingNodeLOD = null;
  92118. _this._loadNodeSignals = {};
  92119. _this._loadingMaterialLOD = null;
  92120. _this._loadMaterialSignals = {};
  92121. return _this;
  92122. }
  92123. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  92124. var _this = this;
  92125. return this._loadExtensionAsync(context, node, function (context, extension) {
  92126. var firstPromise;
  92127. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  92128. var _loop_1 = function (indexLOD) {
  92129. var nodeLOD = nodeLODs[indexLOD];
  92130. if (indexLOD !== 0) {
  92131. _this._loadingNodeLOD = nodeLOD;
  92132. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  92133. }
  92134. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  92135. if (indexLOD !== 0) {
  92136. var previousNodeLOD = nodeLODs[indexLOD - 1];
  92137. previousNodeLOD._babylonMesh.setEnabled(false);
  92138. }
  92139. if (indexLOD !== nodeLODs.length - 1) {
  92140. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  92141. _this._loadNodeSignals[nodeIndex].resolve();
  92142. delete _this._loadNodeSignals[nodeIndex];
  92143. }
  92144. });
  92145. if (indexLOD === 0) {
  92146. firstPromise = promise;
  92147. }
  92148. else {
  92149. _this._loader._completePromises.push(promise);
  92150. _this._loadingNodeLOD = null;
  92151. }
  92152. };
  92153. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  92154. _loop_1(indexLOD);
  92155. }
  92156. return firstPromise;
  92157. });
  92158. };
  92159. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92160. var _this = this;
  92161. // Don't load material LODs if already loading a node LOD.
  92162. if (this._loadingNodeLOD) {
  92163. return null;
  92164. }
  92165. return this._loadExtensionAsync(context, material, function (context, extension) {
  92166. var firstPromise;
  92167. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  92168. var _loop_2 = function (indexLOD) {
  92169. var materialLOD = materialLODs[indexLOD];
  92170. if (indexLOD !== 0) {
  92171. _this._loadingMaterialLOD = materialLOD;
  92172. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  92173. }
  92174. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  92175. if (indexLOD !== materialLODs.length - 1) {
  92176. var materialIndex = materialLODs[indexLOD + 1]._index;
  92177. _this._loadMaterialSignals[materialIndex].resolve();
  92178. delete _this._loadMaterialSignals[materialIndex];
  92179. }
  92180. });
  92181. if (indexLOD === 0) {
  92182. firstPromise = promise;
  92183. }
  92184. else {
  92185. _this._loader._completePromises.push(promise);
  92186. _this._loadingMaterialLOD = null;
  92187. }
  92188. };
  92189. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  92190. _loop_2(indexLOD);
  92191. }
  92192. return firstPromise;
  92193. });
  92194. };
  92195. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  92196. var _this = this;
  92197. // Defer the loading of uris if loading a material or node LOD.
  92198. if (this._loadingMaterialLOD) {
  92199. var index = this._loadingMaterialLOD._index;
  92200. return this._loadMaterialSignals[index].promise.then(function () {
  92201. return _this._loader._loadUriAsync(context, uri);
  92202. });
  92203. }
  92204. else if (this._loadingNodeLOD) {
  92205. var index = this._loadingNodeLOD._index;
  92206. return this._loadNodeSignals[index].promise.then(function () {
  92207. return _this._loader._loadUriAsync(context, uri);
  92208. });
  92209. }
  92210. return null;
  92211. };
  92212. /**
  92213. * Gets an array of LOD properties from lowest to highest.
  92214. */
  92215. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92216. if (this.maxLODsToLoad <= 0) {
  92217. throw new Error("maxLODsToLoad must be greater than zero");
  92218. }
  92219. var properties = new Array();
  92220. for (var i = ids.length - 1; i >= 0; i--) {
  92221. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92222. if (properties.length === this.maxLODsToLoad) {
  92223. return properties;
  92224. }
  92225. }
  92226. properties.push(property);
  92227. return properties;
  92228. };
  92229. return MSFT_lod;
  92230. }(GLTF2.GLTFLoaderExtension));
  92231. Extensions.MSFT_lod = MSFT_lod;
  92232. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92233. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92234. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92235. })(BABYLON || (BABYLON = {}));
  92236. //# sourceMappingURL=MSFT_lod.js.map
  92237. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92238. var BABYLON;
  92239. (function (BABYLON) {
  92240. var GLTF2;
  92241. (function (GLTF2) {
  92242. var Extensions;
  92243. (function (Extensions) {
  92244. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92245. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92246. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92247. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92248. function KHR_materials_pbrSpecularGlossiness() {
  92249. var _this = _super !== null && _super.apply(this, arguments) || this;
  92250. _this.name = NAME;
  92251. return _this;
  92252. }
  92253. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92254. var _this = this;
  92255. return this._loadExtensionAsync(context, material, function (context, extension) {
  92256. material._babylonMeshes = material._babylonMeshes || [];
  92257. material._babylonMeshes.push(babylonMesh);
  92258. if (material._loaded) {
  92259. babylonMesh.material = material._babylonMaterial;
  92260. return material._loaded;
  92261. }
  92262. var promises = new Array();
  92263. var babylonMaterial = _this._loader._createMaterial(material);
  92264. material._babylonMaterial = babylonMaterial;
  92265. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92266. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92267. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92268. babylonMesh.material = babylonMaterial;
  92269. return (material._loaded = Promise.all(promises).then(function () { }));
  92270. });
  92271. };
  92272. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92273. var promises = new Array();
  92274. var babylonMaterial = material._babylonMaterial;
  92275. if (properties.diffuseFactor) {
  92276. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92277. babylonMaterial.alpha = properties.diffuseFactor[3];
  92278. }
  92279. else {
  92280. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92281. }
  92282. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92283. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92284. if (properties.diffuseTexture) {
  92285. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92286. babylonMaterial.albedoTexture = texture;
  92287. }));
  92288. }
  92289. if (properties.specularGlossinessTexture) {
  92290. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92291. babylonMaterial.reflectivityTexture = texture;
  92292. }));
  92293. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92294. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92295. }
  92296. loader._loadMaterialAlphaProperties(context, material);
  92297. return Promise.all(promises).then(function () { });
  92298. };
  92299. return KHR_materials_pbrSpecularGlossiness;
  92300. }(GLTF2.GLTFLoaderExtension));
  92301. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92302. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92303. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92304. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92305. })(BABYLON || (BABYLON = {}));
  92306. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92307. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92308. var BABYLON;
  92309. (function (BABYLON) {
  92310. var GLTF2;
  92311. (function (GLTF2) {
  92312. var Extensions;
  92313. (function (Extensions) {
  92314. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92315. var NAME = "KHR_lights";
  92316. var LightType;
  92317. (function (LightType) {
  92318. LightType["AMBIENT"] = "ambient";
  92319. LightType["DIRECTIONAL"] = "directional";
  92320. LightType["POINT"] = "point";
  92321. LightType["SPOT"] = "spot";
  92322. })(LightType || (LightType = {}));
  92323. var KHR_lights = /** @class */ (function (_super) {
  92324. __extends(KHR_lights, _super);
  92325. function KHR_lights() {
  92326. var _this = _super !== null && _super.apply(this, arguments) || this;
  92327. _this.name = NAME;
  92328. return _this;
  92329. }
  92330. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92331. var _this = this;
  92332. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92333. var promise = _this._loader._loadSceneAsync(context, scene);
  92334. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92335. if (light.type !== LightType.AMBIENT) {
  92336. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92337. }
  92338. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92339. return promise;
  92340. });
  92341. };
  92342. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92343. var _this = this;
  92344. return this._loadExtensionAsync(context, node, function (context, extension) {
  92345. var promise = _this._loader._loadNodeAsync(context, node);
  92346. var babylonLight;
  92347. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92348. var name = node._babylonMesh.name;
  92349. switch (light.type) {
  92350. case LightType.AMBIENT: {
  92351. throw new Error(context + ": Ambient lights are not allowed on a node");
  92352. }
  92353. case LightType.DIRECTIONAL: {
  92354. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92355. break;
  92356. }
  92357. case LightType.POINT: {
  92358. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92359. break;
  92360. }
  92361. case LightType.SPOT: {
  92362. var spotLight = light;
  92363. // TODO: support inner and outer cone angles
  92364. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92365. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92366. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92367. break;
  92368. }
  92369. default: {
  92370. throw new Error(context + ": Invalid light type " + light.type);
  92371. }
  92372. }
  92373. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92374. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92375. babylonLight.parent = node._babylonMesh;
  92376. return promise;
  92377. });
  92378. };
  92379. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92380. get: function () {
  92381. var extensions = this._loader._gltf.extensions;
  92382. if (!extensions || !extensions[this.name]) {
  92383. throw new Error("#/extensions: " + this.name + " not found");
  92384. }
  92385. var extension = extensions[this.name];
  92386. return extension.lights;
  92387. },
  92388. enumerable: true,
  92389. configurable: true
  92390. });
  92391. return KHR_lights;
  92392. }(GLTF2.GLTFLoaderExtension));
  92393. Extensions.KHR_lights = KHR_lights;
  92394. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92395. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92396. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92397. })(BABYLON || (BABYLON = {}));
  92398. //# sourceMappingURL=KHR_lights.js.map
  92399. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92400. globalObject["BABYLON"] = BABYLON;
  92401. 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 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 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 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 EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  92402. 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,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,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,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,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };