es6.js 4.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242
  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 The current define statements for the shader.
  65. * @returns The resulting defines with defines of the current rank removed.
  66. */
  67. EffectFallbacks.prototype.reduce = function (currentDefines) {
  68. // First we try to switch to CPU skinning
  69. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  70. this._mesh.computeBonesUsingShaders = false;
  71. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  72. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  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 === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  77. otherMesh.computeBonesUsingShaders = false;
  78. }
  79. }
  80. }
  81. else {
  82. var currentFallbacks = this._defines[this._currentRank];
  83. if (currentFallbacks) {
  84. for (var index = 0; index < currentFallbacks.length; index++) {
  85. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  86. }
  87. }
  88. this._currentRank++;
  89. }
  90. return currentDefines;
  91. };
  92. return EffectFallbacks;
  93. }());
  94. BABYLON.EffectFallbacks = EffectFallbacks;
  95. /**
  96. * Options to be used when creating an effect.
  97. */
  98. var EffectCreationOptions = /** @class */ (function () {
  99. function EffectCreationOptions() {
  100. }
  101. return EffectCreationOptions;
  102. }());
  103. BABYLON.EffectCreationOptions = EffectCreationOptions;
  104. /**
  105. * Effect containing vertex and fragment shader that can be executed on an object.
  106. */
  107. var Effect = /** @class */ (function () {
  108. /**
  109. * Instantiates an effect.
  110. * An effect can be used to create/manage/execute vertex and fragment shaders.
  111. * @param baseName Name of the effect.
  112. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  113. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  114. * @param samplers List of sampler variables that will be passed to the shader.
  115. * @param engine Engine to be used to render the effect
  116. * @param defines Define statements to be added to the shader.
  117. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  118. * @param onCompiled Callback that will be called when the shader is compiled.
  119. * @param onError Callback that will be called if an error occurs during shader compilation.
  120. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  121. */
  122. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  123. if (samplers === void 0) { samplers = null; }
  124. if (defines === void 0) { defines = null; }
  125. if (fallbacks === void 0) { fallbacks = null; }
  126. if (onCompiled === void 0) { onCompiled = null; }
  127. if (onError === void 0) { onError = null; }
  128. var _this = this;
  129. /**
  130. * Unique ID of the effect.
  131. */
  132. this.uniqueId = 0;
  133. /**
  134. * Observable that will be called when the shader is compiled.
  135. */
  136. this.onCompileObservable = new BABYLON.Observable();
  137. /**
  138. * Observable that will be called if an error occurs during shader compilation.
  139. */
  140. this.onErrorObservable = new BABYLON.Observable();
  141. /**
  142. * Observable that will be called when effect is bound.
  143. */
  144. this.onBindObservable = new BABYLON.Observable();
  145. this._uniformBuffersNames = {};
  146. this._isReady = false;
  147. this._compilationError = "";
  148. this.name = baseName;
  149. if (attributesNamesOrOptions.attributes) {
  150. var options = attributesNamesOrOptions;
  151. this._engine = uniformsNamesOrEngine;
  152. this._attributesNames = options.attributes;
  153. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  154. this._samplers = options.samplers;
  155. this.defines = options.defines;
  156. this.onError = options.onError;
  157. this.onCompiled = options.onCompiled;
  158. this._fallbacks = options.fallbacks;
  159. this._indexParameters = options.indexParameters;
  160. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  161. if (options.uniformBuffersNames) {
  162. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  163. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  164. }
  165. }
  166. }
  167. else {
  168. this._engine = engine;
  169. this.defines = defines;
  170. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  171. this._samplers = samplers;
  172. this._attributesNames = attributesNamesOrOptions;
  173. this.onError = onError;
  174. this.onCompiled = onCompiled;
  175. this._indexParameters = indexParameters;
  176. this._fallbacks = fallbacks;
  177. }
  178. this.uniqueId = Effect._uniqueIdSeed++;
  179. var vertexSource;
  180. var fragmentSource;
  181. if (baseName.vertexElement) {
  182. vertexSource = document.getElementById(baseName.vertexElement);
  183. if (!vertexSource) {
  184. vertexSource = baseName.vertexElement;
  185. }
  186. }
  187. else {
  188. vertexSource = baseName.vertex || baseName;
  189. }
  190. if (baseName.fragmentElement) {
  191. fragmentSource = document.getElementById(baseName.fragmentElement);
  192. if (!fragmentSource) {
  193. fragmentSource = baseName.fragmentElement;
  194. }
  195. }
  196. else {
  197. fragmentSource = baseName.fragment || baseName;
  198. }
  199. var finalVertexCode;
  200. this._loadVertexShaderAsync(vertexSource)
  201. .then(function (vertexCode) {
  202. return _this._processIncludesAsync(vertexCode);
  203. })
  204. .then(function (vertexCodeWithIncludes) {
  205. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  206. return _this._loadFragmentShaderAsync(fragmentSource);
  207. })
  208. .then(function (fragmentCode) {
  209. return _this._processIncludesAsync(fragmentCode);
  210. })
  211. .then(function (fragmentCodeWithIncludes) {
  212. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  213. if (baseName) {
  214. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  215. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  216. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  217. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  218. }
  219. else {
  220. _this._vertexSourceCode = finalVertexCode;
  221. _this._fragmentSourceCode = migratedFragmentCode;
  222. }
  223. _this._prepareEffect();
  224. });
  225. }
  226. Object.defineProperty(Effect.prototype, "key", {
  227. /**
  228. * Unique key for this effect
  229. */
  230. get: function () {
  231. return this._key;
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. /**
  237. * If the effect has been compiled and prepared.
  238. * @returns if the effect is compiled and prepared.
  239. */
  240. Effect.prototype.isReady = function () {
  241. return this._isReady;
  242. };
  243. /**
  244. * The engine the effect was initialized with.
  245. * @returns the engine.
  246. */
  247. Effect.prototype.getEngine = function () {
  248. return this._engine;
  249. };
  250. /**
  251. * The compiled webGL program for the effect
  252. * @returns the webGL program.
  253. */
  254. Effect.prototype.getProgram = function () {
  255. return this._program;
  256. };
  257. /**
  258. * The set of names of attribute variables for the shader.
  259. * @returns An array of attribute names.
  260. */
  261. Effect.prototype.getAttributesNames = function () {
  262. return this._attributesNames;
  263. };
  264. /**
  265. * Returns the attribute at the given index.
  266. * @param index The index of the attribute.
  267. * @returns The location of the attribute.
  268. */
  269. Effect.prototype.getAttributeLocation = function (index) {
  270. return this._attributes[index];
  271. };
  272. /**
  273. * Returns the attribute based on the name of the variable.
  274. * @param name of the attribute to look up.
  275. * @returns the attribute location.
  276. */
  277. Effect.prototype.getAttributeLocationByName = function (name) {
  278. var index = this._attributesNames.indexOf(name);
  279. return this._attributes[index];
  280. };
  281. /**
  282. * The number of attributes.
  283. * @returns the numnber of attributes.
  284. */
  285. Effect.prototype.getAttributesCount = function () {
  286. return this._attributes.length;
  287. };
  288. /**
  289. * Gets the index of a uniform variable.
  290. * @param uniformName of the uniform to look up.
  291. * @returns the index.
  292. */
  293. Effect.prototype.getUniformIndex = function (uniformName) {
  294. return this._uniformsNames.indexOf(uniformName);
  295. };
  296. /**
  297. * Returns the attribute based on the name of the variable.
  298. * @param uniformName of the uniform to look up.
  299. * @returns the location of the uniform.
  300. */
  301. Effect.prototype.getUniform = function (uniformName) {
  302. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  303. };
  304. /**
  305. * Returns an array of sampler variable names
  306. * @returns The array of sampler variable neames.
  307. */
  308. Effect.prototype.getSamplers = function () {
  309. return this._samplers;
  310. };
  311. /**
  312. * The error from the last compilation.
  313. * @returns the error string.
  314. */
  315. Effect.prototype.getCompilationError = function () {
  316. return this._compilationError;
  317. };
  318. /**
  319. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  320. * @param func The callback to be used.
  321. */
  322. Effect.prototype.executeWhenCompiled = function (func) {
  323. if (this.isReady()) {
  324. func(this);
  325. return;
  326. }
  327. this.onCompileObservable.add(function (effect) {
  328. func(effect);
  329. });
  330. };
  331. /** @ignore */
  332. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  333. if (BABYLON.Tools.IsWindowObjectExist()) {
  334. // DOM element ?
  335. if (vertex instanceof HTMLElement) {
  336. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  337. return Promise.resolve(vertexCode);
  338. }
  339. }
  340. // Base64 encoded ?
  341. if (vertex.substr(0, 7) === "base64:") {
  342. var vertexBinary = window.atob(vertex.substr(7));
  343. return Promise.resolve(vertexBinary);
  344. }
  345. // Is in local store ?
  346. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  347. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  348. }
  349. var vertexShaderUrl;
  350. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  351. vertexShaderUrl = vertex;
  352. }
  353. else {
  354. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  355. }
  356. // Vertex shader
  357. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  358. };
  359. /** @ignore */
  360. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  361. if (BABYLON.Tools.IsWindowObjectExist()) {
  362. // DOM element ?
  363. if (fragment instanceof HTMLElement) {
  364. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  365. return Promise.resolve(fragmentCode);
  366. }
  367. }
  368. // Base64 encoded ?
  369. if (fragment.substr(0, 7) === "base64:") {
  370. var fragmentBinary = window.atob(fragment.substr(7));
  371. return Promise.resolve(fragmentBinary);
  372. }
  373. // Is in local store ?
  374. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  375. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  376. }
  377. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  378. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  379. }
  380. var fragmentShaderUrl;
  381. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  382. fragmentShaderUrl = fragment;
  383. }
  384. else {
  385. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  386. }
  387. // Fragment shader
  388. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  389. };
  390. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  391. // Rebuild shaders source code
  392. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  393. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  394. vertexCode = prefix + vertexCode;
  395. fragmentCode = prefix + fragmentCode;
  396. // Number lines of shaders source code
  397. var i = 2;
  398. var regex = /\n/gm;
  399. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  400. i = 2;
  401. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  402. // Dump shaders name and formatted source code
  403. if (this.name.vertexElement) {
  404. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  405. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  406. }
  407. else if (this.name.vertex) {
  408. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  409. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  410. }
  411. else {
  412. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  413. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  414. }
  415. };
  416. ;
  417. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  418. var preparedSourceCode = this._processPrecision(sourceCode);
  419. if (this._engine.webGLVersion == 1) {
  420. return preparedSourceCode;
  421. }
  422. // Already converted
  423. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  424. return preparedSourceCode.replace("#version 300 es", "");
  425. }
  426. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  427. // Remove extensions
  428. // #extension GL_OES_standard_derivatives : enable
  429. // #extension GL_EXT_shader_texture_lod : enable
  430. // #extension GL_EXT_frag_depth : enable
  431. // #extension GL_EXT_draw_buffers : require
  432. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  433. var result = preparedSourceCode.replace(regex, "");
  434. // Migrate to GLSL v300
  435. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  436. result = result.replace(/attribute[ \t]/g, "in ");
  437. result = result.replace(/[ \t]attribute/g, " in");
  438. if (isFragment) {
  439. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  440. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  441. result = result.replace(/texture2D\s*\(/g, "texture(");
  442. result = result.replace(/textureCube\s*\(/g, "texture(");
  443. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  444. result = result.replace(/gl_FragColor/g, "glFragColor");
  445. result = result.replace(/gl_FragData/g, "glFragData");
  446. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  447. }
  448. return result;
  449. };
  450. Effect.prototype._processIncludesAsync = function (sourceCode) {
  451. var _this = this;
  452. return new Promise(function (resolve, reject) {
  453. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  454. var match = regex.exec(sourceCode);
  455. var returnValue = sourceCode;
  456. while (match != null) {
  457. var includeFile = match[1];
  458. // Uniform declaration
  459. if (includeFile.indexOf("__decl__") !== -1) {
  460. includeFile = includeFile.replace(/__decl__/, "");
  461. if (_this._engine.supportsUniformBuffers) {
  462. includeFile = includeFile.replace(/Vertex/, "Ubo");
  463. includeFile = includeFile.replace(/Fragment/, "Ubo");
  464. }
  465. includeFile = includeFile + "Declaration";
  466. }
  467. if (Effect.IncludesShadersStore[includeFile]) {
  468. // Substitution
  469. var includeContent = Effect.IncludesShadersStore[includeFile];
  470. if (match[2]) {
  471. var splits = match[3].split(",");
  472. for (var index = 0; index < splits.length; index += 2) {
  473. var source = new RegExp(splits[index], "g");
  474. var dest = splits[index + 1];
  475. includeContent = includeContent.replace(source, dest);
  476. }
  477. }
  478. if (match[4]) {
  479. var indexString = match[5];
  480. if (indexString.indexOf("..") !== -1) {
  481. var indexSplits = indexString.split("..");
  482. var minIndex = parseInt(indexSplits[0]);
  483. var maxIndex = parseInt(indexSplits[1]);
  484. var sourceIncludeContent = includeContent.slice(0);
  485. includeContent = "";
  486. if (isNaN(maxIndex)) {
  487. maxIndex = _this._indexParameters[indexSplits[1]];
  488. }
  489. for (var i = minIndex; i < maxIndex; i++) {
  490. if (!_this._engine.supportsUniformBuffers) {
  491. // Ubo replacement
  492. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  493. return p1 + "{X}";
  494. });
  495. }
  496. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  497. }
  498. }
  499. else {
  500. if (!_this._engine.supportsUniformBuffers) {
  501. // Ubo replacement
  502. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  503. return p1 + "{X}";
  504. });
  505. }
  506. includeContent = includeContent.replace(/\{X\}/g, indexString);
  507. }
  508. }
  509. // Replace
  510. returnValue = returnValue.replace(match[0], includeContent);
  511. }
  512. else {
  513. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  514. _this._engine._loadFileAsync(includeShaderUrl)
  515. .then(function (fileContent) {
  516. Effect.IncludesShadersStore[includeFile] = fileContent;
  517. return _this._processIncludesAsync(returnValue);
  518. })
  519. .then(function (returnValue) {
  520. resolve(returnValue);
  521. });
  522. return;
  523. }
  524. match = regex.exec(sourceCode);
  525. }
  526. resolve(returnValue);
  527. });
  528. };
  529. Effect.prototype._processPrecision = function (source) {
  530. if (source.indexOf("precision highp float") === -1) {
  531. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  532. source = "precision mediump float;\n" + source;
  533. }
  534. else {
  535. source = "precision highp float;\n" + source;
  536. }
  537. }
  538. else {
  539. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  540. source = source.replace("precision highp float", "precision mediump float");
  541. }
  542. }
  543. return source;
  544. };
  545. /**
  546. * Recompiles the webGL program
  547. * @param vertexSourceCode The source code for the vertex shader.
  548. * @param fragmentSourceCode The source code for the fragment shader.
  549. * @param onCompiled Callback called when completed.
  550. * @param onError Callback called on error.
  551. */
  552. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  553. var _this = this;
  554. this._isReady = false;
  555. this._vertexSourceCodeOverride = vertexSourceCode;
  556. this._fragmentSourceCodeOverride = fragmentSourceCode;
  557. this.onError = function (effect, error) {
  558. if (onError) {
  559. onError(error);
  560. }
  561. };
  562. this.onCompiled = function () {
  563. var scenes = _this.getEngine().scenes;
  564. for (var i = 0; i < scenes.length; i++) {
  565. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  566. }
  567. if (onCompiled) {
  568. onCompiled(_this._program);
  569. }
  570. };
  571. this._fallbacks = null;
  572. this._prepareEffect();
  573. };
  574. /**
  575. * Gets the uniform locations of the the specified variable names
  576. * @param names THe names of the variables to lookup.
  577. * @returns Array of locations in the same order as variable names.
  578. */
  579. Effect.prototype.getSpecificUniformLocations = function (names) {
  580. var engine = this._engine;
  581. return engine.getUniforms(this._program, names);
  582. };
  583. /**
  584. * Prepares the effect
  585. */
  586. Effect.prototype._prepareEffect = function () {
  587. var attributesNames = this._attributesNames;
  588. var defines = this.defines;
  589. var fallbacks = this._fallbacks;
  590. this._valueCache = {};
  591. var previousProgram = this._program;
  592. try {
  593. var engine = this._engine;
  594. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  595. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  596. }
  597. else {
  598. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  599. }
  600. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  601. if (engine.supportsUniformBuffers) {
  602. for (var name in this._uniformBuffersNames) {
  603. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  604. }
  605. }
  606. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  607. this._attributes = engine.getAttributes(this._program, attributesNames);
  608. var index;
  609. for (index = 0; index < this._samplers.length; index++) {
  610. var sampler = this.getUniform(this._samplers[index]);
  611. if (sampler == null) {
  612. this._samplers.splice(index, 1);
  613. index--;
  614. }
  615. }
  616. engine.bindSamplers(this);
  617. this._compilationError = "";
  618. this._isReady = true;
  619. if (this.onCompiled) {
  620. this.onCompiled(this);
  621. }
  622. this.onCompileObservable.notifyObservers(this);
  623. this.onCompileObservable.clear();
  624. // Unbind mesh reference in fallbacks
  625. if (this._fallbacks) {
  626. this._fallbacks.unBindMesh();
  627. }
  628. if (previousProgram) {
  629. this.getEngine()._deleteProgram(previousProgram);
  630. }
  631. }
  632. catch (e) {
  633. this._compilationError = e.message;
  634. // Let's go through fallbacks then
  635. BABYLON.Tools.Error("Unable to compile effect:");
  636. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  637. return " " + uniform;
  638. }));
  639. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  640. return " " + attribute;
  641. }));
  642. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  643. BABYLON.Tools.Error("Error: " + this._compilationError);
  644. if (previousProgram) {
  645. this._program = previousProgram;
  646. this._isReady = true;
  647. if (this.onError) {
  648. this.onError(this, this._compilationError);
  649. }
  650. this.onErrorObservable.notifyObservers(this);
  651. }
  652. if (fallbacks && fallbacks.isMoreFallbacks) {
  653. BABYLON.Tools.Error("Trying next fallback.");
  654. this.defines = fallbacks.reduce(this.defines);
  655. this._prepareEffect();
  656. }
  657. else {
  658. if (this.onError) {
  659. this.onError(this, this._compilationError);
  660. }
  661. this.onErrorObservable.notifyObservers(this);
  662. this.onErrorObservable.clear();
  663. // Unbind mesh reference in fallbacks
  664. if (this._fallbacks) {
  665. this._fallbacks.unBindMesh();
  666. }
  667. }
  668. }
  669. };
  670. Object.defineProperty(Effect.prototype, "isSupported", {
  671. /**
  672. * Checks if the effect is supported. (Must be called after compilation)
  673. */
  674. get: function () {
  675. return this._compilationError === "";
  676. },
  677. enumerable: true,
  678. configurable: true
  679. });
  680. /**
  681. * Binds a texture to the engine to be used as output of the shader.
  682. * @param channel Name of the output variable.
  683. * @param texture Texture to bind.
  684. */
  685. Effect.prototype._bindTexture = function (channel, texture) {
  686. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  687. };
  688. /**
  689. * Sets a texture on the engine to be used in the shader.
  690. * @param channel Name of the sampler variable.
  691. * @param texture Texture to set.
  692. */
  693. Effect.prototype.setTexture = function (channel, texture) {
  694. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  695. };
  696. /**
  697. * Sets an array of textures on the engine to be used in the shader.
  698. * @param channel Name of the variable.
  699. * @param textures Textures to set.
  700. */
  701. Effect.prototype.setTextureArray = function (channel, textures) {
  702. if (this._samplers.indexOf(channel + "Ex") === -1) {
  703. var initialPos = this._samplers.indexOf(channel);
  704. for (var index = 1; index < textures.length; index++) {
  705. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  706. }
  707. }
  708. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  709. };
  710. /**
  711. * 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)
  712. * @param channel Name of the sampler variable.
  713. * @param postProcess Post process to get the input texture from.
  714. */
  715. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  716. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  717. };
  718. /** @ignore */
  719. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  720. var cache = this._valueCache[uniformName];
  721. var flag = matrix.updateFlag;
  722. if (cache !== undefined && cache === flag) {
  723. return false;
  724. }
  725. this._valueCache[uniformName] = flag;
  726. return true;
  727. };
  728. /** @ignore */
  729. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  730. var cache = this._valueCache[uniformName];
  731. if (!cache) {
  732. cache = [x, y];
  733. this._valueCache[uniformName] = cache;
  734. return true;
  735. }
  736. var changed = false;
  737. if (cache[0] !== x) {
  738. cache[0] = x;
  739. changed = true;
  740. }
  741. if (cache[1] !== y) {
  742. cache[1] = y;
  743. changed = true;
  744. }
  745. return changed;
  746. };
  747. /** @ignore */
  748. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  749. var cache = this._valueCache[uniformName];
  750. if (!cache) {
  751. cache = [x, y, z];
  752. this._valueCache[uniformName] = cache;
  753. return true;
  754. }
  755. var changed = false;
  756. if (cache[0] !== x) {
  757. cache[0] = x;
  758. changed = true;
  759. }
  760. if (cache[1] !== y) {
  761. cache[1] = y;
  762. changed = true;
  763. }
  764. if (cache[2] !== z) {
  765. cache[2] = z;
  766. changed = true;
  767. }
  768. return changed;
  769. };
  770. /** @ignore */
  771. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  772. var cache = this._valueCache[uniformName];
  773. if (!cache) {
  774. cache = [x, y, z, w];
  775. this._valueCache[uniformName] = cache;
  776. return true;
  777. }
  778. var changed = false;
  779. if (cache[0] !== x) {
  780. cache[0] = x;
  781. changed = true;
  782. }
  783. if (cache[1] !== y) {
  784. cache[1] = y;
  785. changed = true;
  786. }
  787. if (cache[2] !== z) {
  788. cache[2] = z;
  789. changed = true;
  790. }
  791. if (cache[3] !== w) {
  792. cache[3] = w;
  793. changed = true;
  794. }
  795. return changed;
  796. };
  797. /**
  798. * Binds a buffer to a uniform.
  799. * @param buffer Buffer to bind.
  800. * @param name Name of the uniform variable to bind to.
  801. */
  802. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  803. var bufferName = this._uniformBuffersNames[name];
  804. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  805. return;
  806. }
  807. Effect._baseCache[bufferName] = buffer;
  808. this._engine.bindUniformBufferBase(buffer, bufferName);
  809. };
  810. /**
  811. * Binds block to a uniform.
  812. * @param blockName Name of the block to bind.
  813. * @param index Index to bind.
  814. */
  815. Effect.prototype.bindUniformBlock = function (blockName, index) {
  816. this._engine.bindUniformBlock(this._program, blockName, index);
  817. };
  818. /**
  819. * Sets an interger value on a uniform variable.
  820. * @param uniformName Name of the variable.
  821. * @param value Value to be set.
  822. * @returns this effect.
  823. */
  824. Effect.prototype.setInt = function (uniformName, value) {
  825. var cache = this._valueCache[uniformName];
  826. if (cache !== undefined && cache === value)
  827. return this;
  828. this._valueCache[uniformName] = value;
  829. this._engine.setInt(this.getUniform(uniformName), value);
  830. return this;
  831. };
  832. /**
  833. * Sets an int array on a uniform variable.
  834. * @param uniformName Name of the variable.
  835. * @param array array to be set.
  836. * @returns this effect.
  837. */
  838. Effect.prototype.setIntArray = function (uniformName, array) {
  839. this._valueCache[uniformName] = null;
  840. this._engine.setIntArray(this.getUniform(uniformName), array);
  841. return this;
  842. };
  843. /**
  844. * 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)
  845. * @param uniformName Name of the variable.
  846. * @param array array to be set.
  847. * @returns this effect.
  848. */
  849. Effect.prototype.setIntArray2 = function (uniformName, array) {
  850. this._valueCache[uniformName] = null;
  851. this._engine.setIntArray2(this.getUniform(uniformName), array);
  852. return this;
  853. };
  854. /**
  855. * 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)
  856. * @param uniformName Name of the variable.
  857. * @param array array to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setIntArray3 = function (uniformName, array) {
  861. this._valueCache[uniformName] = null;
  862. this._engine.setIntArray3(this.getUniform(uniformName), array);
  863. return this;
  864. };
  865. /**
  866. * 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)
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray4 = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray4(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * Sets an float array on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setFloatArray = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setFloatArray(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * 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)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * 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)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * 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)
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * Sets an array on a uniform variable.
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setArray = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setArray(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * 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)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setArray2 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setArray2(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * 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)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setArray3 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setArray3(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * 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)
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray4 = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray4(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * Sets matrices on a uniform variable.
  966. * @param uniformName Name of the variable.
  967. * @param matrices matrices to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setMatrices = function (uniformName, matrices) {
  971. if (!matrices) {
  972. return this;
  973. }
  974. this._valueCache[uniformName] = null;
  975. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  976. return this;
  977. };
  978. /**
  979. * Sets matrix on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param matrix matrix to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setMatrix = function (uniformName, matrix) {
  985. if (this._cacheMatrix(uniformName, matrix)) {
  986. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  987. }
  988. return this;
  989. };
  990. /**
  991. * 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)
  992. * @param uniformName Name of the variable.
  993. * @param matrix matrix to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1003. * @param uniformName Name of the variable.
  1004. * @param matrix matrix to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets a float on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param value value to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setFloat = function (uniformName, value) {
  1019. var cache = this._valueCache[uniformName];
  1020. if (cache !== undefined && cache === value)
  1021. return this;
  1022. this._valueCache[uniformName] = value;
  1023. this._engine.setFloat(this.getUniform(uniformName), value);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a boolean on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param bool value to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setBool = function (uniformName, bool) {
  1033. var cache = this._valueCache[uniformName];
  1034. if (cache !== undefined && cache === bool)
  1035. return this;
  1036. this._valueCache[uniformName] = bool;
  1037. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets a Vector2 on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param vector2 vector2 to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1047. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1048. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1049. }
  1050. return this;
  1051. };
  1052. /**
  1053. * Sets a float2 on a uniform variable.
  1054. * @param uniformName Name of the variable.
  1055. * @param x First float in float2.
  1056. * @param y Second float in float2.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1060. if (this._cacheFloat2(uniformName, x, y)) {
  1061. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a Vector3 on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param vector3 Value to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1072. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1073. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1074. }
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets a float3 on a uniform variable.
  1079. * @param uniformName Name of the variable.
  1080. * @param x First float in float3.
  1081. * @param y Second float in float3.
  1082. * @param z Third float in float3.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1086. if (this._cacheFloat3(uniformName, x, y, z)) {
  1087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets a Vector4 on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param vector4 Value to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1098. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1099. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1100. }
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a float4 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param x First float in float4.
  1107. * @param y Second float in float4.
  1108. * @param z Third float in float4.
  1109. * @param w Fourth float in float4.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1113. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1114. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a Color3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param color3 Value to be set.
  1122. * @returns this effect.
  1123. */
  1124. Effect.prototype.setColor3 = function (uniformName, color3) {
  1125. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1126. this._engine.setColor3(this.getUniform(uniformName), color3);
  1127. }
  1128. return this;
  1129. };
  1130. /**
  1131. * Sets a Color4 on a uniform variable.
  1132. * @param uniformName Name of the variable.
  1133. * @param color3 Value to be set.
  1134. * @param alpha Alpha value to be set.
  1135. * @returns this effect.
  1136. */
  1137. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1138. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1139. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1140. }
  1141. return this;
  1142. };
  1143. /**
  1144. * Resets the cache of effects.
  1145. */
  1146. Effect.ResetCache = function () {
  1147. Effect._baseCache = {};
  1148. };
  1149. Effect._uniqueIdSeed = 0;
  1150. Effect._baseCache = {};
  1151. // Statics
  1152. /**
  1153. * Store of each shader (The can be looked up using effect.key)
  1154. */
  1155. Effect.ShadersStore = {};
  1156. /**
  1157. * Store of each included file for a shader (The can be looked up using effect.key)
  1158. */
  1159. Effect.IncludesShadersStore = {};
  1160. return Effect;
  1161. }());
  1162. BABYLON.Effect = Effect;
  1163. })(BABYLON || (BABYLON = {}));
  1164. //# sourceMappingURL=babylon.effect.js.map
  1165. //# sourceMappingURL=babylon.types.js.map
  1166. var BABYLON;
  1167. (function (BABYLON) {
  1168. var KeyboardEventTypes = /** @class */ (function () {
  1169. function KeyboardEventTypes() {
  1170. }
  1171. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1172. get: function () {
  1173. return KeyboardEventTypes._KEYDOWN;
  1174. },
  1175. enumerable: true,
  1176. configurable: true
  1177. });
  1178. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1179. get: function () {
  1180. return KeyboardEventTypes._KEYUP;
  1181. },
  1182. enumerable: true,
  1183. configurable: true
  1184. });
  1185. KeyboardEventTypes._KEYDOWN = 0x01;
  1186. KeyboardEventTypes._KEYUP = 0x02;
  1187. return KeyboardEventTypes;
  1188. }());
  1189. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1190. var KeyboardInfo = /** @class */ (function () {
  1191. function KeyboardInfo(type, event) {
  1192. this.type = type;
  1193. this.event = event;
  1194. }
  1195. return KeyboardInfo;
  1196. }());
  1197. BABYLON.KeyboardInfo = KeyboardInfo;
  1198. /**
  1199. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1200. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1201. */
  1202. var KeyboardInfoPre = /** @class */ (function (_super) {
  1203. __extends(KeyboardInfoPre, _super);
  1204. function KeyboardInfoPre(type, event) {
  1205. var _this = _super.call(this, type, event) || this;
  1206. _this.skipOnPointerObservable = false;
  1207. return _this;
  1208. }
  1209. return KeyboardInfoPre;
  1210. }(KeyboardInfo));
  1211. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1212. })(BABYLON || (BABYLON = {}));
  1213. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1214. var BABYLON;
  1215. (function (BABYLON) {
  1216. var PointerEventTypes = /** @class */ (function () {
  1217. function PointerEventTypes() {
  1218. }
  1219. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1220. get: function () {
  1221. return PointerEventTypes._POINTERDOWN;
  1222. },
  1223. enumerable: true,
  1224. configurable: true
  1225. });
  1226. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1227. get: function () {
  1228. return PointerEventTypes._POINTERUP;
  1229. },
  1230. enumerable: true,
  1231. configurable: true
  1232. });
  1233. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1234. get: function () {
  1235. return PointerEventTypes._POINTERMOVE;
  1236. },
  1237. enumerable: true,
  1238. configurable: true
  1239. });
  1240. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1241. get: function () {
  1242. return PointerEventTypes._POINTERWHEEL;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERPICK;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERTAP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOUBLETAP;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. PointerEventTypes._POINTERDOWN = 0x01;
  1269. PointerEventTypes._POINTERUP = 0x02;
  1270. PointerEventTypes._POINTERMOVE = 0x04;
  1271. PointerEventTypes._POINTERWHEEL = 0x08;
  1272. PointerEventTypes._POINTERPICK = 0x10;
  1273. PointerEventTypes._POINTERTAP = 0x20;
  1274. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1275. return PointerEventTypes;
  1276. }());
  1277. BABYLON.PointerEventTypes = PointerEventTypes;
  1278. var PointerInfoBase = /** @class */ (function () {
  1279. function PointerInfoBase(type, event) {
  1280. this.type = type;
  1281. this.event = event;
  1282. }
  1283. return PointerInfoBase;
  1284. }());
  1285. BABYLON.PointerInfoBase = PointerInfoBase;
  1286. /**
  1287. * This class is used to store pointer related info for the onPrePointerObservable event.
  1288. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1289. */
  1290. var PointerInfoPre = /** @class */ (function (_super) {
  1291. __extends(PointerInfoPre, _super);
  1292. function PointerInfoPre(type, event, localX, localY) {
  1293. var _this = _super.call(this, type, event) || this;
  1294. _this.skipOnPointerObservable = false;
  1295. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1296. return _this;
  1297. }
  1298. return PointerInfoPre;
  1299. }(PointerInfoBase));
  1300. BABYLON.PointerInfoPre = PointerInfoPre;
  1301. /**
  1302. * This type contains all the data related to a pointer event in Babylon.js.
  1303. * 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.
  1304. */
  1305. var PointerInfo = /** @class */ (function (_super) {
  1306. __extends(PointerInfo, _super);
  1307. function PointerInfo(type, event, pickInfo) {
  1308. var _this = _super.call(this, type, event) || this;
  1309. _this.pickInfo = pickInfo;
  1310. return _this;
  1311. }
  1312. return PointerInfo;
  1313. }(PointerInfoBase));
  1314. BABYLON.PointerInfo = PointerInfo;
  1315. })(BABYLON || (BABYLON = {}));
  1316. //# sourceMappingURL=babylon.pointerEvents.js.map
  1317. var BABYLON;
  1318. (function (BABYLON) {
  1319. BABYLON.ToGammaSpace = 1 / 2.2;
  1320. BABYLON.ToLinearSpace = 2.2;
  1321. BABYLON.Epsilon = 0.001;
  1322. /**
  1323. * Class used to hold a RBG color
  1324. */
  1325. var Color3 = /** @class */ (function () {
  1326. /**
  1327. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1328. * @param r defines the red component (between 0 and 1, default is 0)
  1329. * @param g defines the green component (between 0 and 1, default is 0)
  1330. * @param b defines the blue component (between 0 and 1, default is 0)
  1331. */
  1332. function Color3(
  1333. /**
  1334. * Defines the red component (between 0 and 1, default is 0)
  1335. */
  1336. r,
  1337. /**
  1338. * Defines the green component (between 0 and 1, default is 0)
  1339. */
  1340. g,
  1341. /**
  1342. * Defines the blue component (between 0 and 1, default is 0)
  1343. */
  1344. b) {
  1345. if (r === void 0) { r = 0; }
  1346. if (g === void 0) { g = 0; }
  1347. if (b === void 0) { b = 0; }
  1348. this.r = r;
  1349. this.g = g;
  1350. this.b = b;
  1351. }
  1352. /**
  1353. * Creates a string with the Color3 current values
  1354. * @returns the string representation of the Color3 object
  1355. */
  1356. Color3.prototype.toString = function () {
  1357. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1358. };
  1359. /**
  1360. * Returns the string "Color3"
  1361. * @returns "Color3"
  1362. */
  1363. Color3.prototype.getClassName = function () {
  1364. return "Color3";
  1365. };
  1366. /**
  1367. * Compute the Color3 hash code
  1368. * @returns an unique number that can be used to hash Color3 objects
  1369. */
  1370. Color3.prototype.getHashCode = function () {
  1371. var hash = this.r || 0;
  1372. hash = (hash * 397) ^ (this.g || 0);
  1373. hash = (hash * 397) ^ (this.b || 0);
  1374. return hash;
  1375. };
  1376. // Operators
  1377. /**
  1378. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1379. * @param array defines the array where to store the r,g,b components
  1380. * @param index defines an optional index in the target array to define where to start storing values
  1381. * @returns the current Color3 object
  1382. */
  1383. Color3.prototype.toArray = function (array, index) {
  1384. if (index === undefined) {
  1385. index = 0;
  1386. }
  1387. array[index] = this.r;
  1388. array[index + 1] = this.g;
  1389. array[index + 2] = this.b;
  1390. return this;
  1391. };
  1392. /**
  1393. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1394. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1395. * @returns a new {BABYLON.Color4} object
  1396. */
  1397. Color3.prototype.toColor4 = function (alpha) {
  1398. if (alpha === void 0) { alpha = 1; }
  1399. return new Color4(this.r, this.g, this.b, alpha);
  1400. };
  1401. /**
  1402. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1403. * @returns the new array
  1404. */
  1405. Color3.prototype.asArray = function () {
  1406. var result = new Array();
  1407. this.toArray(result, 0);
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns the luminance value
  1412. * @returns a float value
  1413. */
  1414. Color3.prototype.toLuminance = function () {
  1415. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1416. };
  1417. /**
  1418. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1419. * @param otherColor defines the second operand
  1420. * @returns the new Color3 object
  1421. */
  1422. Color3.prototype.multiply = function (otherColor) {
  1423. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1424. };
  1425. /**
  1426. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1427. * @param otherColor defines the second operand
  1428. * @param result defines the Color3 object where to store the result
  1429. * @returns the current Color3
  1430. */
  1431. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1432. result.r = this.r * otherColor.r;
  1433. result.g = this.g * otherColor.g;
  1434. result.b = this.b * otherColor.b;
  1435. return this;
  1436. };
  1437. /**
  1438. * Determines equality between Color3 objects
  1439. * @param otherColor defines the second operand
  1440. * @returns true if the rgb values are equal to the passed ones
  1441. */
  1442. Color3.prototype.equals = function (otherColor) {
  1443. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1444. };
  1445. /**
  1446. * Determines equality between the current Color3 object and a set of r,b,g values
  1447. * @param r defines the red component to check
  1448. * @param g defines the green component to check
  1449. * @param b defines the blue component to check
  1450. * @returns true if the rgb values are equal to the passed ones
  1451. */
  1452. Color3.prototype.equalsFloats = function (r, g, b) {
  1453. return this.r === r && this.g === g && this.b === b;
  1454. };
  1455. /**
  1456. * Multiplies in place each rgb value by scale
  1457. * @param scale defines the scaling factor
  1458. * @returns the updated Color3.
  1459. */
  1460. Color3.prototype.scale = function (scale) {
  1461. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1462. };
  1463. /**
  1464. * Multiplies the rgb values by scale and stores the result into "result"
  1465. * @param scale defines the scaling factor
  1466. * @param result defines the Color3 object where to store the result
  1467. * @returns the unmodified current Color3.
  1468. */
  1469. Color3.prototype.scaleToRef = function (scale, result) {
  1470. result.r = this.r * scale;
  1471. result.g = this.g * scale;
  1472. result.b = this.b * scale;
  1473. return this;
  1474. };
  1475. /**
  1476. * Clamps the rgb values by the min and max values and stores the result into "result"
  1477. * @param min defines minimum clamping value (default is 0)
  1478. * @param max defines maximum clamping value (default is 1)
  1479. * @param result defines color to store the result into
  1480. * @returns the original Color3
  1481. */
  1482. Color3.prototype.clampToRef = function (min, max, result) {
  1483. if (min === void 0) { min = 0; }
  1484. if (max === void 0) { max = 1; }
  1485. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1486. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1487. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1488. return this;
  1489. };
  1490. /**
  1491. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1492. * @param otherColor defines the second operand
  1493. * @returns the new Color3
  1494. */
  1495. Color3.prototype.add = function (otherColor) {
  1496. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1497. };
  1498. /**
  1499. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1500. * @param otherColor defines the second operand
  1501. * @param result defines Color3 object to store the result into
  1502. * @returns the unmodified current Color3
  1503. */
  1504. Color3.prototype.addToRef = function (otherColor, result) {
  1505. result.r = this.r + otherColor.r;
  1506. result.g = this.g + otherColor.g;
  1507. result.b = this.b + otherColor.b;
  1508. return this;
  1509. };
  1510. /**
  1511. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1512. * @param otherColor defines the second operand
  1513. * @returns the new Color3
  1514. */
  1515. Color3.prototype.subtract = function (otherColor) {
  1516. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1517. };
  1518. /**
  1519. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1520. * @param otherColor defines the second operand
  1521. * @param result defines Color3 object to store the result into
  1522. * @returns the unmodified current Color3
  1523. */
  1524. Color3.prototype.subtractToRef = function (otherColor, result) {
  1525. result.r = this.r - otherColor.r;
  1526. result.g = this.g - otherColor.g;
  1527. result.b = this.b - otherColor.b;
  1528. return this;
  1529. };
  1530. /**
  1531. * Copy the current object
  1532. * @returns a new Color3 copied the current one
  1533. */
  1534. Color3.prototype.clone = function () {
  1535. return new Color3(this.r, this.g, this.b);
  1536. };
  1537. /**
  1538. * Copies the rgb values from the source in the current Color3
  1539. * @param source defines the source Color3 object
  1540. * @returns the updated Color3 object
  1541. */
  1542. Color3.prototype.copyFrom = function (source) {
  1543. this.r = source.r;
  1544. this.g = source.g;
  1545. this.b = source.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Updates the Color3 rgb values from the passed floats
  1550. * @param r defines the red component to read from
  1551. * @param g defines the green component to read from
  1552. * @param b defines the blue component to read from
  1553. * @returns the current Color3 object
  1554. */
  1555. Color3.prototype.copyFromFloats = function (r, g, b) {
  1556. this.r = r;
  1557. this.g = g;
  1558. this.b = b;
  1559. return this;
  1560. };
  1561. /**
  1562. * Updates the Color3 rgb values from the passed floats
  1563. * @param r defines the red component to read from
  1564. * @param g defines the green component to read from
  1565. * @param b defines the blue component to read from
  1566. * @returns the current Color3 object
  1567. */
  1568. Color3.prototype.set = function (r, g, b) {
  1569. return this.copyFromFloats(r, g, b);
  1570. };
  1571. /**
  1572. * Compute the Color3 hexadecimal code as a string
  1573. * @returns a string containing the hexadecimal representation of the Color3 object
  1574. */
  1575. Color3.prototype.toHexString = function () {
  1576. var intR = (this.r * 255) | 0;
  1577. var intG = (this.g * 255) | 0;
  1578. var intB = (this.b * 255) | 0;
  1579. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1580. };
  1581. /**
  1582. * Computes a new Color3 converted from the current one to linear space
  1583. * @returns a new Color3 object
  1584. */
  1585. Color3.prototype.toLinearSpace = function () {
  1586. var convertedColor = new Color3();
  1587. this.toLinearSpaceToRef(convertedColor);
  1588. return convertedColor;
  1589. };
  1590. /**
  1591. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1592. * @param convertedColor defines the Color3 object where to store the linear space version
  1593. * @returns the unmodified Color3
  1594. */
  1595. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1596. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1597. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1598. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1599. return this;
  1600. };
  1601. /**
  1602. * Computes a new Color3 converted from the current one to gamma space
  1603. * @returns a new Color3 object
  1604. */
  1605. Color3.prototype.toGammaSpace = function () {
  1606. var convertedColor = new Color3();
  1607. this.toGammaSpaceToRef(convertedColor);
  1608. return convertedColor;
  1609. };
  1610. /**
  1611. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1612. * @param convertedColor defines the Color3 object where to store the gamma space version
  1613. * @returns the unmodified Color3
  1614. */
  1615. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1616. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1617. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1618. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1619. return this;
  1620. };
  1621. // Statics
  1622. /**
  1623. * Creates a new Color3 from the string containing valid hexadecimal values
  1624. * @param hex defines a string containing valid hexadecimal values
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.FromHexString = function (hex) {
  1628. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1629. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1630. return new Color3(0, 0, 0);
  1631. }
  1632. var r = parseInt(hex.substring(1, 3), 16);
  1633. var g = parseInt(hex.substring(3, 5), 16);
  1634. var b = parseInt(hex.substring(5, 7), 16);
  1635. return Color3.FromInts(r, g, b);
  1636. };
  1637. /**
  1638. * Creates a new Vector3 from the starting index of the passed array
  1639. * @param array defines the source array
  1640. * @param offset defines an offset in the source array
  1641. * @returns a new Color3 object
  1642. */
  1643. Color3.FromArray = function (array, offset) {
  1644. if (offset === void 0) { offset = 0; }
  1645. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1646. };
  1647. /**
  1648. * Creates a new Color3 from integer values (< 256)
  1649. * @param r defines the red component to read from (value between 0 and 255)
  1650. * @param g defines the green component to read from (value between 0 and 255)
  1651. * @param b defines the blue component to read from (value between 0 and 255)
  1652. * @returns a new Color3 object
  1653. */
  1654. Color3.FromInts = function (r, g, b) {
  1655. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1656. };
  1657. /**
  1658. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1659. * @param start defines the start Color3 value
  1660. * @param end defines the end Color3 value
  1661. * @param amount defines the gradient value between start and end
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.Lerp = function (start, end, amount) {
  1665. var r = start.r + ((end.r - start.r) * amount);
  1666. var g = start.g + ((end.g - start.g) * amount);
  1667. var b = start.b + ((end.b - start.b) * amount);
  1668. return new Color3(r, g, b);
  1669. };
  1670. /**
  1671. * Returns a Color3 value containing a red color
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.Red = function () { return new Color3(1, 0, 0); };
  1675. /**
  1676. * Returns a Color3 value containing a green color
  1677. * @returns a new Color3 object
  1678. */
  1679. Color3.Green = function () { return new Color3(0, 1, 0); };
  1680. /**
  1681. * Returns a Color3 value containing a blue color
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1685. /**
  1686. * Returns a Color3 value containing a black color
  1687. * @returns a new Color3 object
  1688. */
  1689. Color3.Black = function () { return new Color3(0, 0, 0); };
  1690. /**
  1691. * Returns a Color3 value containing a white color
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.White = function () { return new Color3(1, 1, 1); };
  1695. /**
  1696. * Returns a Color3 value containing a purple color
  1697. * @returns a new Color3 object
  1698. */
  1699. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1700. /**
  1701. * Returns a Color3 value containing a magenta color
  1702. * @returns a new Color3 object
  1703. */
  1704. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1705. /**
  1706. * Returns a Color3 value containing a yellow color
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1710. /**
  1711. * Returns a Color3 value containing a gray color
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1715. /**
  1716. * Returns a Color3 value containing a teal color
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1720. /**
  1721. * Returns a Color3 value containing a random color
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1725. return Color3;
  1726. }());
  1727. BABYLON.Color3 = Color3;
  1728. /**
  1729. * Class used to hold a RBGA color
  1730. */
  1731. var Color4 = /** @class */ (function () {
  1732. /**
  1733. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1734. * @param r defines the red component (between 0 and 1, default is 0)
  1735. * @param g defines the green component (between 0 and 1, default is 0)
  1736. * @param b defines the blue component (between 0 and 1, default is 0)
  1737. * @param a defines the alpha component (between 0 and 1, default is 1)
  1738. */
  1739. function Color4(
  1740. /**
  1741. * Defines the red component (between 0 and 1, default is 0)
  1742. */
  1743. r,
  1744. /**
  1745. * Defines the green component (between 0 and 1, default is 0)
  1746. */
  1747. g,
  1748. /**
  1749. * Defines the blue component (between 0 and 1, default is 0)
  1750. */
  1751. b,
  1752. /**
  1753. * Defines the alpha component (between 0 and 1, default is 1)
  1754. */
  1755. a) {
  1756. if (r === void 0) { r = 0; }
  1757. if (g === void 0) { g = 0; }
  1758. if (b === void 0) { b = 0; }
  1759. if (a === void 0) { a = 1; }
  1760. this.r = r;
  1761. this.g = g;
  1762. this.b = b;
  1763. this.a = a;
  1764. }
  1765. // Operators
  1766. /**
  1767. * Adds in place the passed Color4 values to the current Color4 object
  1768. * @param right defines the second operand
  1769. * @returns the current updated Color4 object
  1770. */
  1771. Color4.prototype.addInPlace = function (right) {
  1772. this.r += right.r;
  1773. this.g += right.g;
  1774. this.b += right.b;
  1775. this.a += right.a;
  1776. return this;
  1777. };
  1778. /**
  1779. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1780. * @returns the new array
  1781. */
  1782. Color4.prototype.asArray = function () {
  1783. var result = new Array();
  1784. this.toArray(result, 0);
  1785. return result;
  1786. };
  1787. /**
  1788. * Stores from the starting index in the passed array the Color4 successive values
  1789. * @param array defines the array where to store the r,g,b components
  1790. * @param index defines an optional index in the target array to define where to start storing values
  1791. * @returns the current Color4 object
  1792. */
  1793. Color4.prototype.toArray = function (array, index) {
  1794. if (index === undefined) {
  1795. index = 0;
  1796. }
  1797. array[index] = this.r;
  1798. array[index + 1] = this.g;
  1799. array[index + 2] = this.b;
  1800. array[index + 3] = this.a;
  1801. return this;
  1802. };
  1803. /**
  1804. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1805. * @param right defines the second operand
  1806. * @returns a new Color4 object
  1807. */
  1808. Color4.prototype.add = function (right) {
  1809. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1810. };
  1811. /**
  1812. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1813. * @param right defines the second operand
  1814. * @returns a new Color4 object
  1815. */
  1816. Color4.prototype.subtract = function (right) {
  1817. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1818. };
  1819. /**
  1820. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1821. * @param right defines the second operand
  1822. * @param result defines the Color4 object where to store the result
  1823. * @returns the current Color4 object
  1824. */
  1825. Color4.prototype.subtractToRef = function (right, result) {
  1826. result.r = this.r - right.r;
  1827. result.g = this.g - right.g;
  1828. result.b = this.b - right.b;
  1829. result.a = this.a - right.a;
  1830. return this;
  1831. };
  1832. /**
  1833. * Creates a new Color4 with the current Color4 values multiplied by scale
  1834. * @param scale defines the scaling factor to apply
  1835. * @returns a new Color4 object
  1836. */
  1837. Color4.prototype.scale = function (scale) {
  1838. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1839. };
  1840. /**
  1841. * Multiplies the current Color4 values by scale and stores the result in "result"
  1842. * @param scale defines the scaling factor to apply
  1843. * @param result defines the Color4 object where to store the result
  1844. * @returns the current Color4.
  1845. */
  1846. Color4.prototype.scaleToRef = function (scale, result) {
  1847. result.r = this.r * scale;
  1848. result.g = this.g * scale;
  1849. result.b = this.b * scale;
  1850. result.a = this.a * scale;
  1851. return this;
  1852. };
  1853. /**
  1854. * Clamps the rgb values by the min and max values and stores the result into "result"
  1855. * @param min defines minimum clamping value (default is 0)
  1856. * @param max defines maximum clamping value (default is 1)
  1857. * @param result defines color to store the result into.
  1858. * @returns the cuurent Color4
  1859. */
  1860. Color4.prototype.clampToRef = function (min, max, result) {
  1861. if (min === void 0) { min = 0; }
  1862. if (max === void 0) { max = 1; }
  1863. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1864. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1865. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1866. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1867. return this;
  1868. };
  1869. /**
  1870. * Multipy an Color4 value by another and return a new Color4 object
  1871. * @param color defines the Color4 value to multiply by
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.multiply = function (color) {
  1875. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1876. };
  1877. /**
  1878. * Multipy a Color4 value by another and push the result in a reference value
  1879. * @param color defines the Color4 value to multiply by
  1880. * @param result defines the Color4 to fill the result in
  1881. * @returns the result Color4
  1882. */
  1883. Color4.prototype.multiplyToRef = function (color, result) {
  1884. result.r = this.r * color.r;
  1885. result.g = this.g * color.g;
  1886. result.b = this.b * color.b;
  1887. result.a = this.a * color.a;
  1888. return result;
  1889. };
  1890. /**
  1891. * Creates a string with the Color4 current values
  1892. * @returns the string representation of the Color4 object
  1893. */
  1894. Color4.prototype.toString = function () {
  1895. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1896. };
  1897. /**
  1898. * Returns the string "Color4"
  1899. * @returns "Color4"
  1900. */
  1901. Color4.prototype.getClassName = function () {
  1902. return "Color4";
  1903. };
  1904. /**
  1905. * Compute the Color4 hash code
  1906. * @returns an unique number that can be used to hash Color4 objects
  1907. */
  1908. Color4.prototype.getHashCode = function () {
  1909. var hash = this.r || 0;
  1910. hash = (hash * 397) ^ (this.g || 0);
  1911. hash = (hash * 397) ^ (this.b || 0);
  1912. hash = (hash * 397) ^ (this.a || 0);
  1913. return hash;
  1914. };
  1915. /**
  1916. * Creates a new Color4 copied from the current one
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.clone = function () {
  1920. return new Color4(this.r, this.g, this.b, this.a);
  1921. };
  1922. /**
  1923. * Copies the passed Color4 values into the current one
  1924. * @param source defines the source Color4 object
  1925. * @returns the current updated Color4 object
  1926. */
  1927. Color4.prototype.copyFrom = function (source) {
  1928. this.r = source.r;
  1929. this.g = source.g;
  1930. this.b = source.b;
  1931. this.a = source.a;
  1932. return this;
  1933. };
  1934. /**
  1935. * Copies the passed float values into the current one
  1936. * @param r defines the red component to read from
  1937. * @param g defines the green component to read from
  1938. * @param b defines the blue component to read from
  1939. * @param a defines the alpha component to read from
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1943. this.r = r;
  1944. this.g = g;
  1945. this.b = b;
  1946. this.a = a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Copies the passed float values into the current one
  1951. * @param r defines the red component to read from
  1952. * @param g defines the green component to read from
  1953. * @param b defines the blue component to read from
  1954. * @param a defines the alpha component to read from
  1955. * @returns the current updated Color4 object
  1956. */
  1957. Color4.prototype.set = function (r, g, b, a) {
  1958. return this.copyFromFloats(r, g, b, a);
  1959. };
  1960. /**
  1961. * Compute the Color4 hexadecimal code as a string
  1962. * @returns a string containing the hexadecimal representation of the Color4 object
  1963. */
  1964. Color4.prototype.toHexString = function () {
  1965. var intR = (this.r * 255) | 0;
  1966. var intG = (this.g * 255) | 0;
  1967. var intB = (this.b * 255) | 0;
  1968. var intA = (this.a * 255) | 0;
  1969. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1970. };
  1971. /**
  1972. * Computes a new Color4 converted from the current one to linear space
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.toLinearSpace = function () {
  1976. var convertedColor = new Color4();
  1977. this.toLinearSpaceToRef(convertedColor);
  1978. return convertedColor;
  1979. };
  1980. /**
  1981. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1982. * @param convertedColor defines the Color4 object where to store the linear space version
  1983. * @returns the unmodified Color4
  1984. */
  1985. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1986. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1987. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1988. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1989. convertedColor.a = this.a;
  1990. return this;
  1991. };
  1992. /**
  1993. * Computes a new Color4 converted from the current one to gamma space
  1994. * @returns a new Color4 object
  1995. */
  1996. Color4.prototype.toGammaSpace = function () {
  1997. var convertedColor = new Color4();
  1998. this.toGammaSpaceToRef(convertedColor);
  1999. return convertedColor;
  2000. };
  2001. /**
  2002. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2003. * @param convertedColor defines the Color4 object where to store the gamma space version
  2004. * @returns the unmodified Color4
  2005. */
  2006. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2007. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2008. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2009. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2010. convertedColor.a = this.a;
  2011. return this;
  2012. };
  2013. // Statics
  2014. /**
  2015. * Creates a new Color4 from the string containing valid hexadecimal values
  2016. * @param hex defines a string containing valid hexadecimal values
  2017. * @returns a new Color4 object
  2018. */
  2019. Color4.FromHexString = function (hex) {
  2020. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2021. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2022. return new Color4(0.0, 0.0, 0.0, 0.0);
  2023. }
  2024. var r = parseInt(hex.substring(1, 3), 16);
  2025. var g = parseInt(hex.substring(3, 5), 16);
  2026. var b = parseInt(hex.substring(5, 7), 16);
  2027. var a = parseInt(hex.substring(7, 9), 16);
  2028. return Color4.FromInts(r, g, b, a);
  2029. };
  2030. /**
  2031. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2032. * @param left defines the start value
  2033. * @param right defines the end value
  2034. * @param amount defines the gradient factor
  2035. * @returns a new Color4 object
  2036. */
  2037. Color4.Lerp = function (left, right, amount) {
  2038. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2039. Color4.LerpToRef(left, right, amount, result);
  2040. return result;
  2041. };
  2042. /**
  2043. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2044. * @param left defines the start value
  2045. * @param right defines the end value
  2046. * @param amount defines the gradient factor
  2047. * @param result defines the Color4 object where to store data
  2048. */
  2049. Color4.LerpToRef = function (left, right, amount, result) {
  2050. result.r = left.r + (right.r - left.r) * amount;
  2051. result.g = left.g + (right.g - left.g) * amount;
  2052. result.b = left.b + (right.b - left.b) * amount;
  2053. result.a = left.a + (right.a - left.a) * amount;
  2054. };
  2055. /**
  2056. * Creates a new Color4 from the starting index element of the passed array
  2057. * @param array defines the source array to read from
  2058. * @param offset defines the offset in the source array
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.FromArray = function (array, offset) {
  2062. if (offset === void 0) { offset = 0; }
  2063. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2064. };
  2065. /**
  2066. * Creates a new Color3 from integer values (< 256)
  2067. * @param r defines the red component to read from (value between 0 and 255)
  2068. * @param g defines the green component to read from (value between 0 and 255)
  2069. * @param b defines the blue component to read from (value between 0 and 255)
  2070. * @param a defines the alpha component to read from (value between 0 and 255)
  2071. * @returns a new Color3 object
  2072. */
  2073. Color4.FromInts = function (r, g, b, a) {
  2074. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2075. };
  2076. /**
  2077. * Check the content of a given array and convert it to an array containing RGBA data
  2078. * If the original array was already containing count * 4 values then it is returned directly
  2079. * @param colors defines the array to check
  2080. * @param count defines the number of RGBA data to expect
  2081. * @returns an array containing count * 4 values (RGBA)
  2082. */
  2083. Color4.CheckColors4 = function (colors, count) {
  2084. // Check if color3 was used
  2085. if (colors.length === count * 3) {
  2086. var colors4 = [];
  2087. for (var index = 0; index < colors.length; index += 3) {
  2088. var newIndex = (index / 3) * 4;
  2089. colors4[newIndex] = colors[index];
  2090. colors4[newIndex + 1] = colors[index + 1];
  2091. colors4[newIndex + 2] = colors[index + 2];
  2092. colors4[newIndex + 3] = 1.0;
  2093. }
  2094. return colors4;
  2095. }
  2096. return colors;
  2097. };
  2098. return Color4;
  2099. }());
  2100. BABYLON.Color4 = Color4;
  2101. var Vector2 = /** @class */ (function () {
  2102. /**
  2103. * Creates a new Vector2 from the passed x and y coordinates.
  2104. */
  2105. function Vector2(x, y) {
  2106. this.x = x;
  2107. this.y = y;
  2108. }
  2109. /**
  2110. * Returns a string with the Vector2 coordinates.
  2111. */
  2112. Vector2.prototype.toString = function () {
  2113. return "{X: " + this.x + " Y:" + this.y + "}";
  2114. };
  2115. /**
  2116. * Returns the string "Vector2"
  2117. */
  2118. Vector2.prototype.getClassName = function () {
  2119. return "Vector2";
  2120. };
  2121. /**
  2122. * Returns the Vector2 hash code as a number.
  2123. */
  2124. Vector2.prototype.getHashCode = function () {
  2125. var hash = this.x || 0;
  2126. hash = (hash * 397) ^ (this.y || 0);
  2127. return hash;
  2128. };
  2129. // Operators
  2130. /**
  2131. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2132. * Returns the Vector2.
  2133. */
  2134. Vector2.prototype.toArray = function (array, index) {
  2135. if (index === void 0) { index = 0; }
  2136. array[index] = this.x;
  2137. array[index + 1] = this.y;
  2138. return this;
  2139. };
  2140. /**
  2141. * Returns a new array with 2 elements : the Vector2 coordinates.
  2142. */
  2143. Vector2.prototype.asArray = function () {
  2144. var result = new Array();
  2145. this.toArray(result, 0);
  2146. return result;
  2147. };
  2148. /**
  2149. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2150. * Returns the updated Vector2.
  2151. */
  2152. Vector2.prototype.copyFrom = function (source) {
  2153. this.x = source.x;
  2154. this.y = source.y;
  2155. return this;
  2156. };
  2157. /**
  2158. * Sets the Vector2 coordinates with the passed floats.
  2159. * Returns the updated Vector2.
  2160. */
  2161. Vector2.prototype.copyFromFloats = function (x, y) {
  2162. this.x = x;
  2163. this.y = y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Sets the Vector2 coordinates with the passed floats.
  2168. * Returns the updated Vector2.
  2169. */
  2170. Vector2.prototype.set = function (x, y) {
  2171. return this.copyFromFloats(x, y);
  2172. };
  2173. /**
  2174. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2175. */
  2176. Vector2.prototype.add = function (otherVector) {
  2177. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2178. };
  2179. /**
  2180. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2181. * Returns the Vector2.
  2182. */
  2183. Vector2.prototype.addToRef = function (otherVector, result) {
  2184. result.x = this.x + otherVector.x;
  2185. result.y = this.y + otherVector.y;
  2186. return this;
  2187. };
  2188. /**
  2189. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2190. * Returns the updated Vector2.
  2191. */
  2192. Vector2.prototype.addInPlace = function (otherVector) {
  2193. this.x += otherVector.x;
  2194. this.y += otherVector.y;
  2195. return this;
  2196. };
  2197. /**
  2198. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2199. */
  2200. Vector2.prototype.addVector3 = function (otherVector) {
  2201. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2202. };
  2203. /**
  2204. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2205. */
  2206. Vector2.prototype.subtract = function (otherVector) {
  2207. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2208. };
  2209. /**
  2210. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2211. * Returns the Vector2.
  2212. */
  2213. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2214. result.x = this.x - otherVector.x;
  2215. result.y = this.y - otherVector.y;
  2216. return this;
  2217. };
  2218. /**
  2219. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2220. * Returns the updated Vector2.
  2221. */
  2222. Vector2.prototype.subtractInPlace = function (otherVector) {
  2223. this.x -= otherVector.x;
  2224. this.y -= otherVector.y;
  2225. return this;
  2226. };
  2227. /**
  2228. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2229. * Returns the updated Vector2.
  2230. */
  2231. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2232. this.x *= otherVector.x;
  2233. this.y *= otherVector.y;
  2234. return this;
  2235. };
  2236. /**
  2237. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2238. */
  2239. Vector2.prototype.multiply = function (otherVector) {
  2240. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2241. };
  2242. /**
  2243. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2244. * Returns the Vector2.
  2245. */
  2246. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2247. result.x = this.x * otherVector.x;
  2248. result.y = this.y * otherVector.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2253. */
  2254. Vector2.prototype.multiplyByFloats = function (x, y) {
  2255. return new Vector2(this.x * x, this.y * y);
  2256. };
  2257. /**
  2258. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2259. */
  2260. Vector2.prototype.divide = function (otherVector) {
  2261. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2262. };
  2263. /**
  2264. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2265. * Returns the Vector2.
  2266. */
  2267. Vector2.prototype.divideToRef = function (otherVector, result) {
  2268. result.x = this.x / otherVector.x;
  2269. result.y = this.y / otherVector.y;
  2270. return this;
  2271. };
  2272. /**
  2273. * Divides the current Vector3 coordinates by the passed ones.
  2274. * Returns the updated Vector3.
  2275. */
  2276. Vector2.prototype.divideInPlace = function (otherVector) {
  2277. return this.divideToRef(otherVector, this);
  2278. };
  2279. /**
  2280. * Returns a new Vector2 with current Vector2 negated coordinates.
  2281. */
  2282. Vector2.prototype.negate = function () {
  2283. return new Vector2(-this.x, -this.y);
  2284. };
  2285. /**
  2286. * Multiply the Vector2 coordinates by scale.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.scaleInPlace = function (scale) {
  2290. this.x *= scale;
  2291. this.y *= scale;
  2292. return this;
  2293. };
  2294. /**
  2295. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2296. */
  2297. Vector2.prototype.scale = function (scale) {
  2298. return new Vector2(this.x * scale, this.y * scale);
  2299. };
  2300. /**
  2301. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2302. */
  2303. Vector2.prototype.equals = function (otherVector) {
  2304. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2305. };
  2306. /**
  2307. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2308. */
  2309. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2310. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2311. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2312. };
  2313. // Properties
  2314. /**
  2315. * Returns the vector length (float).
  2316. */
  2317. Vector2.prototype.length = function () {
  2318. return Math.sqrt(this.x * this.x + this.y * this.y);
  2319. };
  2320. /**
  2321. * Returns the vector squared length (float);
  2322. */
  2323. Vector2.prototype.lengthSquared = function () {
  2324. return (this.x * this.x + this.y * this.y);
  2325. };
  2326. // Methods
  2327. /**
  2328. * Normalize the vector.
  2329. * Returns the updated Vector2.
  2330. */
  2331. Vector2.prototype.normalize = function () {
  2332. var len = this.length();
  2333. if (len === 0)
  2334. return this;
  2335. var num = 1.0 / len;
  2336. this.x *= num;
  2337. this.y *= num;
  2338. return this;
  2339. };
  2340. /**
  2341. * Returns a new Vector2 copied from the Vector2.
  2342. */
  2343. Vector2.prototype.clone = function () {
  2344. return new Vector2(this.x, this.y);
  2345. };
  2346. // Statics
  2347. /**
  2348. * Returns a new Vector2(0, 0)
  2349. */
  2350. Vector2.Zero = function () {
  2351. return new Vector2(0, 0);
  2352. };
  2353. /**
  2354. * Returns a new Vector2(1, 1)
  2355. */
  2356. Vector2.One = function () {
  2357. return new Vector2(1, 1);
  2358. };
  2359. /**
  2360. * Returns a new Vector2 set from the passed index element of the passed array.
  2361. */
  2362. Vector2.FromArray = function (array, offset) {
  2363. if (offset === void 0) { offset = 0; }
  2364. return new Vector2(array[offset], array[offset + 1]);
  2365. };
  2366. /**
  2367. * Sets "result" from the passed index element of the passed array.
  2368. */
  2369. Vector2.FromArrayToRef = function (array, offset, result) {
  2370. result.x = array[offset];
  2371. result.y = array[offset + 1];
  2372. };
  2373. /**
  2374. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2375. */
  2376. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2377. var squared = amount * amount;
  2378. var cubed = amount * squared;
  2379. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2380. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2381. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2382. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2383. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2384. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2385. return new Vector2(x, y);
  2386. };
  2387. /**
  2388. * 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".
  2389. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2390. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2391. */
  2392. Vector2.Clamp = function (value, min, max) {
  2393. var x = value.x;
  2394. x = (x > max.x) ? max.x : x;
  2395. x = (x < min.x) ? min.x : x;
  2396. var y = value.y;
  2397. y = (y > max.y) ? max.y : y;
  2398. y = (y < min.y) ? min.y : y;
  2399. return new Vector2(x, y);
  2400. };
  2401. /**
  2402. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2403. */
  2404. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2405. var squared = amount * amount;
  2406. var cubed = amount * squared;
  2407. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2408. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2409. var part3 = (cubed - (2.0 * squared)) + amount;
  2410. var part4 = cubed - squared;
  2411. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2412. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2417. */
  2418. Vector2.Lerp = function (start, end, amount) {
  2419. var x = start.x + ((end.x - start.x) * amount);
  2420. var y = start.y + ((end.y - start.y) * amount);
  2421. return new Vector2(x, y);
  2422. };
  2423. /**
  2424. * Returns the dot product (float) of the vector "left" and the vector "right".
  2425. */
  2426. Vector2.Dot = function (left, right) {
  2427. return left.x * right.x + left.y * right.y;
  2428. };
  2429. /**
  2430. * Returns a new Vector2 equal to the normalized passed vector.
  2431. */
  2432. Vector2.Normalize = function (vector) {
  2433. var newVector = vector.clone();
  2434. newVector.normalize();
  2435. return newVector;
  2436. };
  2437. /**
  2438. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2439. */
  2440. Vector2.Minimize = function (left, right) {
  2441. var x = (left.x < right.x) ? left.x : right.x;
  2442. var y = (left.y < right.y) ? left.y : right.y;
  2443. return new Vector2(x, y);
  2444. };
  2445. /**
  2446. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2447. */
  2448. Vector2.Maximize = function (left, right) {
  2449. var x = (left.x > right.x) ? left.x : right.x;
  2450. var y = (left.y > right.y) ? left.y : right.y;
  2451. return new Vector2(x, y);
  2452. };
  2453. /**
  2454. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2455. */
  2456. Vector2.Transform = function (vector, transformation) {
  2457. var r = Vector2.Zero();
  2458. Vector2.TransformToRef(vector, transformation, r);
  2459. return r;
  2460. };
  2461. /**
  2462. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2463. */
  2464. Vector2.TransformToRef = function (vector, transformation, result) {
  2465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2467. result.x = x;
  2468. result.y = y;
  2469. };
  2470. /**
  2471. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2472. */
  2473. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2474. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2475. var sign = a < 0 ? -1 : 1;
  2476. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2477. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2478. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2479. };
  2480. /**
  2481. * Returns the distance (float) between the vectors "value1" and "value2".
  2482. */
  2483. Vector2.Distance = function (value1, value2) {
  2484. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2485. };
  2486. /**
  2487. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2488. */
  2489. Vector2.DistanceSquared = function (value1, value2) {
  2490. var x = value1.x - value2.x;
  2491. var y = value1.y - value2.y;
  2492. return (x * x) + (y * y);
  2493. };
  2494. /**
  2495. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2496. */
  2497. Vector2.Center = function (value1, value2) {
  2498. var center = value1.add(value2);
  2499. center.scaleInPlace(0.5);
  2500. return center;
  2501. };
  2502. /**
  2503. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2504. */
  2505. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2506. var l2 = Vector2.DistanceSquared(segA, segB);
  2507. if (l2 === 0.0) {
  2508. return Vector2.Distance(p, segA);
  2509. }
  2510. var v = segB.subtract(segA);
  2511. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2512. var proj = segA.add(v.multiplyByFloats(t, t));
  2513. return Vector2.Distance(p, proj);
  2514. };
  2515. return Vector2;
  2516. }());
  2517. BABYLON.Vector2 = Vector2;
  2518. /**
  2519. * Classed used to store (x,y,z) vector representation
  2520. * A Vector3 is the main object used in 3D geometry
  2521. * It can represent etiher the coordinates of a point the space, either a direction
  2522. * Reminder: Babylon.js uses a left handed forward facing system
  2523. */
  2524. var Vector3 = /** @class */ (function () {
  2525. /**
  2526. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2527. * @param x defines the first coordinates (on X axis)
  2528. * @param y defines the second coordinates (on Y axis)
  2529. * @param z defines the third coordinates (on Z axis)
  2530. */
  2531. function Vector3(
  2532. /**
  2533. * Defines the first coordinates (on X axis)
  2534. */
  2535. x,
  2536. /**
  2537. * Defines the second coordinates (on Y axis)
  2538. */
  2539. y,
  2540. /**
  2541. * Defines the third coordinates (on Z axis)
  2542. */
  2543. z) {
  2544. this.x = x;
  2545. this.y = y;
  2546. this.z = z;
  2547. }
  2548. /**
  2549. * Creates a string representation of the Vector3
  2550. * @returns a string with the Vector3 coordinates.
  2551. */
  2552. Vector3.prototype.toString = function () {
  2553. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2554. };
  2555. /**
  2556. * Gets the class name
  2557. * @returns the string "Vector3"
  2558. */
  2559. Vector3.prototype.getClassName = function () {
  2560. return "Vector3";
  2561. };
  2562. /**
  2563. * Creates the Vector3 hash code
  2564. * @returns a number which tends to be unique between Vector3 instances
  2565. */
  2566. Vector3.prototype.getHashCode = function () {
  2567. var hash = this.x || 0;
  2568. hash = (hash * 397) ^ (this.y || 0);
  2569. hash = (hash * 397) ^ (this.z || 0);
  2570. return hash;
  2571. };
  2572. // Operators
  2573. /**
  2574. * Creates an array containing three elements : the coordinates of the Vector3
  2575. * @returns a new array of numbers
  2576. */
  2577. Vector3.prototype.asArray = function () {
  2578. var result = [];
  2579. this.toArray(result, 0);
  2580. return result;
  2581. };
  2582. /**
  2583. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2584. * @param array defines the destination array
  2585. * @param index defines the offset in the destination array
  2586. * @returns the current Vector3
  2587. */
  2588. Vector3.prototype.toArray = function (array, index) {
  2589. if (index === void 0) { index = 0; }
  2590. array[index] = this.x;
  2591. array[index + 1] = this.y;
  2592. array[index + 2] = this.z;
  2593. return this;
  2594. };
  2595. /**
  2596. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2597. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2598. */
  2599. Vector3.prototype.toQuaternion = function () {
  2600. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2601. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2602. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2603. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2604. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2605. var cosy = Math.cos(this.y * 0.5);
  2606. var siny = Math.sin(this.y * 0.5);
  2607. result.x = coszMinusx * siny;
  2608. result.y = -sinzMinusx * siny;
  2609. result.z = sinxPlusz * cosy;
  2610. result.w = cosxPlusz * cosy;
  2611. return result;
  2612. };
  2613. /**
  2614. * Adds the passed vector to the current Vector3
  2615. * @param otherVector defines the second operand
  2616. * @returns the current updated Vector3
  2617. */
  2618. Vector3.prototype.addInPlace = function (otherVector) {
  2619. this.x += otherVector.x;
  2620. this.y += otherVector.y;
  2621. this.z += otherVector.z;
  2622. return this;
  2623. };
  2624. /**
  2625. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2626. * @param otherVector defines the second operand
  2627. * @returns the resulting Vector3
  2628. */
  2629. Vector3.prototype.add = function (otherVector) {
  2630. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2631. };
  2632. /**
  2633. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2634. * @param otherVector defines the second operand
  2635. * @param result defines the Vector3 object where to store the result
  2636. * @returns the current Vector3
  2637. */
  2638. Vector3.prototype.addToRef = function (otherVector, result) {
  2639. result.x = this.x + otherVector.x;
  2640. result.y = this.y + otherVector.y;
  2641. result.z = this.z + otherVector.z;
  2642. return this;
  2643. };
  2644. /**
  2645. * Subtract the passed vector from the current Vector3
  2646. * @param otherVector defines the second operand
  2647. * @returns the current updated Vector3
  2648. */
  2649. Vector3.prototype.subtractInPlace = function (otherVector) {
  2650. this.x -= otherVector.x;
  2651. this.y -= otherVector.y;
  2652. this.z -= otherVector.z;
  2653. return this;
  2654. };
  2655. /**
  2656. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2657. * @param otherVector defines the second operand
  2658. * @returns the resulting Vector3
  2659. */
  2660. Vector3.prototype.subtract = function (otherVector) {
  2661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2662. };
  2663. /**
  2664. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2665. * @param otherVector defines the second operand
  2666. * @param result defines the Vector3 object where to store the result
  2667. * @returns the current Vector3
  2668. */
  2669. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2670. result.x = this.x - otherVector.x;
  2671. result.y = this.y - otherVector.y;
  2672. result.z = this.z - otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2677. * @param x defines the x coordinate of the operand
  2678. * @param y defines the y coordinate of the operand
  2679. * @param z defines the z coordinate of the operand
  2680. * @returns the resulting Vector3
  2681. */
  2682. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2683. return new Vector3(this.x - x, this.y - y, this.z - z);
  2684. };
  2685. /**
  2686. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2687. * @param x defines the x coordinate of the operand
  2688. * @param y defines the y coordinate of the operand
  2689. * @param z defines the z coordinate of the operand
  2690. * @param result defines the Vector3 object where to store the result
  2691. * @returns the current Vector3
  2692. */
  2693. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2694. result.x = this.x - x;
  2695. result.y = this.y - y;
  2696. result.z = this.z - z;
  2697. return this;
  2698. };
  2699. /**
  2700. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2701. * @returns a new Vector3
  2702. */
  2703. Vector3.prototype.negate = function () {
  2704. return new Vector3(-this.x, -this.y, -this.z);
  2705. };
  2706. /**
  2707. * Multiplies the Vector3 coordinates by the float "scale"
  2708. * @param scale defines the multiplier factor
  2709. * @returns the current updated Vector3
  2710. */
  2711. Vector3.prototype.scaleInPlace = function (scale) {
  2712. this.x *= scale;
  2713. this.y *= scale;
  2714. this.z *= scale;
  2715. return this;
  2716. };
  2717. /**
  2718. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2719. * @param scale defines the multiplier factor
  2720. * @returns a new Vector3
  2721. */
  2722. Vector3.prototype.scale = function (scale) {
  2723. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2724. };
  2725. /**
  2726. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2727. * @param scale defines the multiplier factor
  2728. * @param result defines the Vector3 object where to store the result
  2729. * @returns the current Vector3
  2730. */
  2731. Vector3.prototype.scaleToRef = function (scale, result) {
  2732. result.x = this.x * scale;
  2733. result.y = this.y * scale;
  2734. result.z = this.z * scale;
  2735. return this;
  2736. };
  2737. /**
  2738. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2739. * @param otherVector defines the second operand
  2740. * @returns true if both vectors are equals
  2741. */
  2742. Vector3.prototype.equals = function (otherVector) {
  2743. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2744. };
  2745. /**
  2746. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2747. * @param otherVector defines the second operand
  2748. * @param epsilon defines the minimal distance to define values as equals
  2749. * @returns true if both vectors are distant less than epsilon
  2750. */
  2751. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2752. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2753. 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);
  2754. };
  2755. /**
  2756. * Returns true if the current Vector3 coordinates equals the passed floats
  2757. * @param x defines the x coordinate of the operand
  2758. * @param y defines the y coordinate of the operand
  2759. * @param z defines the z coordinate of the operand
  2760. * @returns true if both vectors are equals
  2761. */
  2762. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2763. return this.x === x && this.y === y && this.z === z;
  2764. };
  2765. /**
  2766. * Multiplies the current Vector3 coordinates by the passed ones
  2767. * @param otherVector defines the second operand
  2768. * @returns the current updated Vector3
  2769. */
  2770. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2771. this.x *= otherVector.x;
  2772. this.y *= otherVector.y;
  2773. this.z *= otherVector.z;
  2774. return this;
  2775. };
  2776. /**
  2777. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2778. * @param otherVector defines the second operand
  2779. * @returns the new Vector3
  2780. */
  2781. Vector3.prototype.multiply = function (otherVector) {
  2782. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2783. };
  2784. /**
  2785. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2786. * @param otherVector defines the second operand
  2787. * @param result defines the Vector3 object where to store the result
  2788. * @returns the current Vector3
  2789. */
  2790. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2791. result.x = this.x * otherVector.x;
  2792. result.y = this.y * otherVector.y;
  2793. result.z = this.z * otherVector.z;
  2794. return this;
  2795. };
  2796. /**
  2797. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2798. * @param x defines the x coordinate of the operand
  2799. * @param y defines the y coordinate of the operand
  2800. * @param z defines the z coordinate of the operand
  2801. * @returns the new Vector3
  2802. */
  2803. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2804. return new Vector3(this.x * x, this.y * y, this.z * z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2808. * @param otherVector defines the second operand
  2809. * @returns the new Vector3
  2810. */
  2811. Vector3.prototype.divide = function (otherVector) {
  2812. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2813. };
  2814. /**
  2815. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.divideToRef = function (otherVector, result) {
  2821. result.x = this.x / otherVector.x;
  2822. result.y = this.y / otherVector.y;
  2823. result.z = this.z / otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Divides the current Vector3 coordinates by the passed ones.
  2828. * @param otherVector defines the second operand
  2829. * @returns the current updated Vector3
  2830. */
  2831. Vector3.prototype.divideInPlace = function (otherVector) {
  2832. return this.divideToRef(otherVector, this);
  2833. };
  2834. /**
  2835. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2836. * @param other defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.minimizeInPlace = function (other) {
  2840. if (other.x < this.x)
  2841. this.x = other.x;
  2842. if (other.y < this.y)
  2843. this.y = other.y;
  2844. if (other.z < this.z)
  2845. this.z = other.z;
  2846. return this;
  2847. };
  2848. /**
  2849. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2850. * @param other defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.maximizeInPlace = function (other) {
  2854. if (other.x > this.x)
  2855. this.x = other.x;
  2856. if (other.y > this.y)
  2857. this.y = other.y;
  2858. if (other.z > this.z)
  2859. this.z = other.z;
  2860. return this;
  2861. };
  2862. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2863. /**
  2864. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2865. */
  2866. get: function () {
  2867. var absX = Math.abs(this.x);
  2868. var absY = Math.abs(this.y);
  2869. if (absX !== absY) {
  2870. return true;
  2871. }
  2872. var absZ = Math.abs(this.z);
  2873. if (absX !== absZ) {
  2874. return true;
  2875. }
  2876. if (absY !== absZ) {
  2877. return true;
  2878. }
  2879. return false;
  2880. },
  2881. enumerable: true,
  2882. configurable: true
  2883. });
  2884. // Properties
  2885. /**
  2886. * Gets the length of the Vector3
  2887. * @returns the length of the Vecto3
  2888. */
  2889. Vector3.prototype.length = function () {
  2890. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2891. };
  2892. /**
  2893. * Gets the squared length of the Vector3
  2894. * @returns squared length of the Vector3
  2895. */
  2896. Vector3.prototype.lengthSquared = function () {
  2897. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2898. };
  2899. /**
  2900. * Normalize the current Vector3.
  2901. * Please note that this is an in place operation.
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.normalize = function () {
  2905. var len = this.length();
  2906. if (len === 0 || len === 1.0)
  2907. return this;
  2908. var num = 1.0 / len;
  2909. this.x *= num;
  2910. this.y *= num;
  2911. this.z *= num;
  2912. return this;
  2913. };
  2914. /**
  2915. * Normalize the current Vector3 to a new vector
  2916. * @returns the new Vector3
  2917. */
  2918. Vector3.prototype.normalizeToNew = function () {
  2919. var normalized = new Vector3(0, 0, 0);
  2920. this.normalizeToRef(normalized);
  2921. return normalized;
  2922. };
  2923. /**
  2924. * Normalize the current Vector3 to the reference
  2925. * @param reference define the Vector3 to update
  2926. * @returns the updated Vector3
  2927. */
  2928. Vector3.prototype.normalizeToRef = function (reference) {
  2929. var len = this.length();
  2930. if (len === 0 || len === 1.0) {
  2931. reference.set(this.x, this.y, this.z);
  2932. return reference;
  2933. }
  2934. var scale = 1.0 / len;
  2935. this.scaleToRef(scale, reference);
  2936. return reference;
  2937. };
  2938. /**
  2939. * Creates a new Vector3 copied from the current Vector3
  2940. * @returns the new Vector3
  2941. */
  2942. Vector3.prototype.clone = function () {
  2943. return new Vector3(this.x, this.y, this.z);
  2944. };
  2945. /**
  2946. * Copies the passed vector coordinates to the current Vector3 ones
  2947. * @param source defines the source Vector3
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.copyFrom = function (source) {
  2951. this.x = source.x;
  2952. this.y = source.y;
  2953. this.z = source.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Copies the passed floats to the current Vector3 coordinates
  2958. * @param x defines the x coordinate of the operand
  2959. * @param y defines the y coordinate of the operand
  2960. * @param z defines the z coordinate of the operand
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2964. this.x = x;
  2965. this.y = y;
  2966. this.z = z;
  2967. return this;
  2968. };
  2969. /**
  2970. * Copies the passed floats to the current Vector3 coordinates
  2971. * @param x defines the x coordinate of the operand
  2972. * @param y defines the y coordinate of the operand
  2973. * @param z defines the z coordinate of the operand
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.set = function (x, y, z) {
  2977. return this.copyFromFloats(x, y, z);
  2978. };
  2979. // Statics
  2980. /**
  2981. * Get the clip factor between two vectors
  2982. * @param vector0 defines the first operand
  2983. * @param vector1 defines the second operand
  2984. * @param axis defines the axis to use
  2985. * @param size defines the size along the axis
  2986. * @returns the clip factor
  2987. */
  2988. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2989. var d0 = Vector3.Dot(vector0, axis) - size;
  2990. var d1 = Vector3.Dot(vector1, axis) - size;
  2991. var s = d0 / (d0 - d1);
  2992. return s;
  2993. };
  2994. /**
  2995. * Get angle between two vectors
  2996. * @param vector0 angle between vector0 and vector1
  2997. * @param vector1 angle between vector0 and vector1
  2998. * @param normal direction of the normal
  2999. * @return the angle between vector0 and vector1
  3000. */
  3001. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3002. var v0 = vector0.clone().normalize();
  3003. var v1 = vector1.clone().normalize();
  3004. var dot = Vector3.Dot(v0, v1);
  3005. var n = Vector3.Cross(v0, v1);
  3006. if (Vector3.Dot(n, normal) > 0) {
  3007. return Math.acos(dot);
  3008. }
  3009. return -Math.acos(dot);
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set from the index "offset" of the passed array
  3013. * @param array defines the source array
  3014. * @param offset defines the offset in the source array
  3015. * @returns the new Vector3
  3016. */
  3017. Vector3.FromArray = function (array, offset) {
  3018. if (!offset) {
  3019. offset = 0;
  3020. }
  3021. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3025. * This function is deprecated. Use FromArray instead
  3026. * @param array defines the source array
  3027. * @param offset defines the offset in the source array
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.FromFloatArray = function (array, offset) {
  3031. return Vector3.FromArray(array, offset);
  3032. };
  3033. /**
  3034. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3035. * @param array defines the source array
  3036. * @param offset defines the offset in the source array
  3037. * @param result defines the Vector3 where to store the result
  3038. */
  3039. Vector3.FromArrayToRef = function (array, offset, result) {
  3040. result.x = array[offset];
  3041. result.y = array[offset + 1];
  3042. result.z = array[offset + 2];
  3043. };
  3044. /**
  3045. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3046. * This function is deprecated. Use FromArrayToRef instead.
  3047. * @param array defines the source array
  3048. * @param offset defines the offset in the source array
  3049. * @param result defines the Vector3 where to store the result
  3050. */
  3051. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3052. return Vector3.FromArrayToRef(array, offset, result);
  3053. };
  3054. /**
  3055. * Sets the passed vector "result" with the passed floats.
  3056. * @param x defines the x coordinate of the source
  3057. * @param y defines the y coordinate of the source
  3058. * @param z defines the z coordinate of the source
  3059. * @param result defines the Vector3 where to store the result
  3060. */
  3061. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3062. result.x = x;
  3063. result.y = y;
  3064. result.z = z;
  3065. };
  3066. /**
  3067. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3068. * @returns a new empty Vector3
  3069. */
  3070. Vector3.Zero = function () {
  3071. return new Vector3(0.0, 0.0, 0.0);
  3072. };
  3073. /**
  3074. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3075. * @returns a new unit Vector3
  3076. */
  3077. Vector3.One = function () {
  3078. return new Vector3(1.0, 1.0, 1.0);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3082. * @returns a new up Vector3
  3083. */
  3084. Vector3.Up = function () {
  3085. return new Vector3(0.0, 1.0, 0.0);
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3089. * @returns a new forward Vector3
  3090. */
  3091. Vector3.Forward = function () {
  3092. return new Vector3(0.0, 0.0, 1.0);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3096. * @returns a new right Vector3
  3097. */
  3098. Vector3.Right = function () {
  3099. return new Vector3(1.0, 0.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3103. * @returns a new left Vector3
  3104. */
  3105. Vector3.Left = function () {
  3106. return new Vector3(-1.0, 0.0, 0.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3110. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3111. * @param vector defines the Vector3 to transform
  3112. * @param transformation defines the transformation matrix
  3113. * @returns the transformed Vector3
  3114. */
  3115. Vector3.TransformCoordinates = function (vector, transformation) {
  3116. var result = Vector3.Zero();
  3117. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3122. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3123. * @param vector defines the Vector3 to transform
  3124. * @param transformation defines the transformation matrix
  3125. * @param result defines the Vector3 where to store the result
  3126. */
  3127. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3128. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3129. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3130. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3131. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3132. result.x = x / w;
  3133. result.y = y / w;
  3134. result.z = z / w;
  3135. };
  3136. /**
  3137. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3138. * This method computes tranformed coordinates only, not transformed direction vectors
  3139. * @param x define the x coordinate of the source vector
  3140. * @param y define the y coordinate of the source vector
  3141. * @param z define the z coordinate of the source vector
  3142. * @param transformation defines the transformation matrix
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3146. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3147. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3148. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3149. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3150. result.x = rx / rw;
  3151. result.y = ry / rw;
  3152. result.z = rz / rw;
  3153. };
  3154. /**
  3155. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3156. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3157. * @param vector defines the Vector3 to transform
  3158. * @param transformation defines the transformation matrix
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.TransformNormal = function (vector, transformation) {
  3162. var result = Vector3.Zero();
  3163. Vector3.TransformNormalToRef(vector, transformation, result);
  3164. return result;
  3165. };
  3166. /**
  3167. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3168. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3169. * @param vector defines the Vector3 to transform
  3170. * @param transformation defines the transformation matrix
  3171. * @param result defines the Vector3 where to store the result
  3172. */
  3173. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3174. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3175. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3176. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3177. result.x = x;
  3178. result.y = y;
  3179. result.z = z;
  3180. };
  3181. /**
  3182. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3183. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3184. * @param x define the x coordinate of the source vector
  3185. * @param y define the y coordinate of the source vector
  3186. * @param z define the z coordinate of the source vector
  3187. * @param transformation defines the transformation matrix
  3188. * @param result defines the Vector3 where to store the result
  3189. */
  3190. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3191. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3192. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3193. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3197. * @param value1 defines the first control point
  3198. * @param value2 defines the second control point
  3199. * @param value3 defines the third control point
  3200. * @param value4 defines the fourth control point
  3201. * @param amount defines the amount on the spline to use
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3205. var squared = amount * amount;
  3206. var cubed = amount * squared;
  3207. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3208. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3209. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3210. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3211. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3212. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3213. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3214. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3215. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3216. return new Vector3(x, y, z);
  3217. };
  3218. /**
  3219. * 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"
  3220. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3221. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3222. * @param value defines the current value
  3223. * @param min defines the lower range value
  3224. * @param max defines the upper range value
  3225. * @returns the new Vector3
  3226. */
  3227. Vector3.Clamp = function (value, min, max) {
  3228. var x = value.x;
  3229. x = (x > max.x) ? max.x : x;
  3230. x = (x < min.x) ? min.x : x;
  3231. var y = value.y;
  3232. y = (y > max.y) ? max.y : y;
  3233. y = (y < min.y) ? min.y : y;
  3234. var z = value.z;
  3235. z = (z > max.z) ? max.z : z;
  3236. z = (z < min.z) ? min.z : z;
  3237. return new Vector3(x, y, z);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3241. * @param value1 defines the first control point
  3242. * @param tangent1 defines the first tangent vector
  3243. * @param value2 defines the second control point
  3244. * @param tangent2 defines the second tangent vector
  3245. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3246. * @returns the new Vector3
  3247. */
  3248. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3249. var squared = amount * amount;
  3250. var cubed = amount * squared;
  3251. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3252. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3253. var part3 = (cubed - (2.0 * squared)) + amount;
  3254. var part4 = cubed - squared;
  3255. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3256. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3257. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3258. return new Vector3(x, y, z);
  3259. };
  3260. /**
  3261. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3262. * @param start defines the start value
  3263. * @param end defines the end value
  3264. * @param amount max defines amount between both (between 0 and 1)
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.Lerp = function (start, end, amount) {
  3268. var result = new Vector3(0, 0, 0);
  3269. Vector3.LerpToRef(start, end, amount, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3274. * @param start defines the start value
  3275. * @param end defines the end value
  3276. * @param amount max defines amount between both (between 0 and 1)
  3277. * @param result defines the Vector3 where to store the result
  3278. */
  3279. Vector3.LerpToRef = function (start, end, amount, result) {
  3280. result.x = start.x + ((end.x - start.x) * amount);
  3281. result.y = start.y + ((end.y - start.y) * amount);
  3282. result.z = start.z + ((end.z - start.z) * amount);
  3283. };
  3284. /**
  3285. * Returns the dot product (float) between the vectors "left" and "right"
  3286. * @param left defines the left operand
  3287. * @param right defines the right operand
  3288. * @returns the dot product
  3289. */
  3290. Vector3.Dot = function (left, right) {
  3291. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3292. };
  3293. /**
  3294. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3295. * The cross product is then orthogonal to both "left" and "right"
  3296. * @param left defines the left operand
  3297. * @param right defines the right operand
  3298. * @returns the cross product
  3299. */
  3300. Vector3.Cross = function (left, right) {
  3301. var result = Vector3.Zero();
  3302. Vector3.CrossToRef(left, right, result);
  3303. return result;
  3304. };
  3305. /**
  3306. * Sets the passed vector "result" with the cross product of "left" and "right"
  3307. * The cross product is then orthogonal to both "left" and "right"
  3308. * @param left defines the left operand
  3309. * @param right defines the right operand
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.CrossToRef = function (left, right, result) {
  3313. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3314. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3315. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3316. result.copyFrom(MathTmp.Vector3[0]);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 as the normalization of the passed vector
  3320. * @param vector defines the Vector3 to normalize
  3321. * @returns the new Vector3
  3322. */
  3323. Vector3.Normalize = function (vector) {
  3324. var result = Vector3.Zero();
  3325. Vector3.NormalizeToRef(vector, result);
  3326. return result;
  3327. };
  3328. /**
  3329. * Sets the passed vector "result" with the normalization of the passed first vector
  3330. * @param vector defines the Vector3 to normalize
  3331. * @param result defines the Vector3 where to store the result
  3332. */
  3333. Vector3.NormalizeToRef = function (vector, result) {
  3334. result.copyFrom(vector);
  3335. result.normalize();
  3336. };
  3337. /**
  3338. * Project a Vector3 onto screen space
  3339. * @param vector defines the Vector3 to project
  3340. * @param world defines the world matrix to use
  3341. * @param transform defines the transform (view x projection) matrix to use
  3342. * @param viewport defines the screen viewport to use
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.Project = function (vector, world, transform, viewport) {
  3346. var cw = viewport.width;
  3347. var ch = viewport.height;
  3348. var cx = viewport.x;
  3349. var cy = viewport.y;
  3350. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3351. 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);
  3352. var matrix = MathTmp.Matrix[0];
  3353. world.multiplyToRef(transform, matrix);
  3354. matrix.multiplyToRef(viewportMatrix, matrix);
  3355. return Vector3.TransformCoordinates(vector, matrix);
  3356. };
  3357. /**
  3358. * Unproject from screen space to object space
  3359. * @param source defines the screen space Vector3 to use
  3360. * @param viewportWidth defines the current width of the viewport
  3361. * @param viewportHeight defines the current height of the viewport
  3362. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3363. * @param transform defines the transform (view x projection) matrix to use
  3364. * @returns the new Vector3
  3365. */
  3366. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3367. var matrix = MathTmp.Matrix[0];
  3368. world.multiplyToRef(transform, matrix);
  3369. matrix.invert();
  3370. source.x = source.x / viewportWidth * 2 - 1;
  3371. source.y = -(source.y / viewportHeight * 2 - 1);
  3372. var vector = Vector3.TransformCoordinates(source, matrix);
  3373. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3374. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3375. vector = vector.scale(1.0 / num);
  3376. }
  3377. return vector;
  3378. };
  3379. /**
  3380. * Unproject from screen space to object space
  3381. * @param source defines the screen space Vector3 to use
  3382. * @param viewportWidth defines the current width of the viewport
  3383. * @param viewportHeight defines the current height of the viewport
  3384. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3385. * @param view defines the view matrix to use
  3386. * @param projection defines the projection matrix to use
  3387. * @returns the new Vector3
  3388. */
  3389. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3390. var result = Vector3.Zero();
  3391. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3392. return result;
  3393. };
  3394. /**
  3395. * Unproject from screen space to object space
  3396. * @param source defines the screen space Vector3 to use
  3397. * @param viewportWidth defines the current width of the viewport
  3398. * @param viewportHeight defines the current height of the viewport
  3399. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3400. * @param view defines the view matrix to use
  3401. * @param projection defines the projection matrix to use
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3405. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3406. };
  3407. /**
  3408. * Unproject from screen space to object space
  3409. * @param sourceX defines the screen space x coordinate to use
  3410. * @param sourceY defines the screen space y coordinate to use
  3411. * @param sourceZ defines the screen space z coordinate to use
  3412. * @param viewportWidth defines the current width of the viewport
  3413. * @param viewportHeight defines the current height of the viewport
  3414. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3415. * @param view defines the view matrix to use
  3416. * @param projection defines the projection matrix to use
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3420. var matrix = MathTmp.Matrix[0];
  3421. world.multiplyToRef(view, matrix);
  3422. matrix.multiplyToRef(projection, matrix);
  3423. matrix.invert();
  3424. var screenSource = MathTmp.Vector3[0];
  3425. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3426. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3427. screenSource.z = 2 * sourceZ - 1.0;
  3428. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3429. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3430. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3431. result.scaleInPlace(1.0 / num);
  3432. }
  3433. };
  3434. /**
  3435. * Gets the minimal coordinate values between two Vector3
  3436. * @param left defines the first operand
  3437. * @param right defines the second operand
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Minimize = function (left, right) {
  3441. var min = left.clone();
  3442. min.minimizeInPlace(right);
  3443. return min;
  3444. };
  3445. /**
  3446. * Gets the maximal coordinate values between two Vector3
  3447. * @param left defines the first operand
  3448. * @param right defines the second operand
  3449. * @returns the new Vector3
  3450. */
  3451. Vector3.Maximize = function (left, right) {
  3452. var max = left.clone();
  3453. max.maximizeInPlace(right);
  3454. return max;
  3455. };
  3456. /**
  3457. * Returns the distance between the vectors "value1" and "value2"
  3458. * @param value1 defines the first operand
  3459. * @param value2 defines the second operand
  3460. * @returns the distance
  3461. */
  3462. Vector3.Distance = function (value1, value2) {
  3463. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3464. };
  3465. /**
  3466. * Returns the squared distance between the vectors "value1" and "value2"
  3467. * @param value1 defines the first operand
  3468. * @param value2 defines the second operand
  3469. * @returns the squared distance
  3470. */
  3471. Vector3.DistanceSquared = function (value1, value2) {
  3472. var x = value1.x - value2.x;
  3473. var y = value1.y - value2.y;
  3474. var z = value1.z - value2.z;
  3475. return (x * x) + (y * y) + (z * z);
  3476. };
  3477. /**
  3478. * Returns a new Vector3 located at the center between "value1" and "value2"
  3479. * @param value1 defines the first operand
  3480. * @param value2 defines the second operand
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Center = function (value1, value2) {
  3484. var center = value1.add(value2);
  3485. center.scaleInPlace(0.5);
  3486. return center;
  3487. };
  3488. /**
  3489. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3490. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3491. * to something in order to rotate it from its local system to the given target system
  3492. * Note: axis1, axis2 and axis3 are normalized during this operation
  3493. * @param axis1 defines the first axis
  3494. * @param axis2 defines the second axis
  3495. * @param axis3 defines the third axis
  3496. * @returns a new Vector3
  3497. */
  3498. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3499. var rotation = Vector3.Zero();
  3500. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3501. return rotation;
  3502. };
  3503. /**
  3504. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3505. * @param axis1 defines the first axis
  3506. * @param axis2 defines the second axis
  3507. * @param axis3 defines the third axis
  3508. * @param ref defines the Vector3 where to store the result
  3509. */
  3510. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3511. var quat = MathTmp.Quaternion[0];
  3512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3513. quat.toEulerAnglesToRef(ref);
  3514. };
  3515. return Vector3;
  3516. }());
  3517. BABYLON.Vector3 = Vector3;
  3518. //Vector4 class created for EulerAngle class conversion to Quaternion
  3519. var Vector4 = /** @class */ (function () {
  3520. /**
  3521. * Creates a Vector4 object from the passed floats.
  3522. */
  3523. function Vector4(x, y, z, w) {
  3524. this.x = x;
  3525. this.y = y;
  3526. this.z = z;
  3527. this.w = w;
  3528. }
  3529. /**
  3530. * Returns the string with the Vector4 coordinates.
  3531. */
  3532. Vector4.prototype.toString = function () {
  3533. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3534. };
  3535. /**
  3536. * Returns the string "Vector4".
  3537. */
  3538. Vector4.prototype.getClassName = function () {
  3539. return "Vector4";
  3540. };
  3541. /**
  3542. * Returns the Vector4 hash code.
  3543. */
  3544. Vector4.prototype.getHashCode = function () {
  3545. var hash = this.x || 0;
  3546. hash = (hash * 397) ^ (this.y || 0);
  3547. hash = (hash * 397) ^ (this.z || 0);
  3548. hash = (hash * 397) ^ (this.w || 0);
  3549. return hash;
  3550. };
  3551. // Operators
  3552. /**
  3553. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3554. */
  3555. Vector4.prototype.asArray = function () {
  3556. var result = new Array();
  3557. this.toArray(result, 0);
  3558. return result;
  3559. };
  3560. /**
  3561. * Populates the passed array from the passed index with the Vector4 coordinates.
  3562. * Returns the Vector4.
  3563. */
  3564. Vector4.prototype.toArray = function (array, index) {
  3565. if (index === undefined) {
  3566. index = 0;
  3567. }
  3568. array[index] = this.x;
  3569. array[index + 1] = this.y;
  3570. array[index + 2] = this.z;
  3571. array[index + 3] = this.w;
  3572. return this;
  3573. };
  3574. /**
  3575. * Adds the passed vector to the current Vector4.
  3576. * Returns the updated Vector4.
  3577. */
  3578. Vector4.prototype.addInPlace = function (otherVector) {
  3579. this.x += otherVector.x;
  3580. this.y += otherVector.y;
  3581. this.z += otherVector.z;
  3582. this.w += otherVector.w;
  3583. return this;
  3584. };
  3585. /**
  3586. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3587. */
  3588. Vector4.prototype.add = function (otherVector) {
  3589. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3590. };
  3591. /**
  3592. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3593. * Returns the current Vector4.
  3594. */
  3595. Vector4.prototype.addToRef = function (otherVector, result) {
  3596. result.x = this.x + otherVector.x;
  3597. result.y = this.y + otherVector.y;
  3598. result.z = this.z + otherVector.z;
  3599. result.w = this.w + otherVector.w;
  3600. return this;
  3601. };
  3602. /**
  3603. * Subtract in place the passed vector from the current Vector4.
  3604. * Returns the updated Vector4.
  3605. */
  3606. Vector4.prototype.subtractInPlace = function (otherVector) {
  3607. this.x -= otherVector.x;
  3608. this.y -= otherVector.y;
  3609. this.z -= otherVector.z;
  3610. this.w -= otherVector.w;
  3611. return this;
  3612. };
  3613. /**
  3614. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3615. */
  3616. Vector4.prototype.subtract = function (otherVector) {
  3617. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3618. };
  3619. /**
  3620. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3621. * Returns the current Vector4.
  3622. */
  3623. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3624. result.x = this.x - otherVector.x;
  3625. result.y = this.y - otherVector.y;
  3626. result.z = this.z - otherVector.z;
  3627. result.w = this.w - otherVector.w;
  3628. return this;
  3629. };
  3630. /**
  3631. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3632. */
  3633. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3634. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3635. };
  3636. /**
  3637. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3638. * Returns the current Vector4.
  3639. */
  3640. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3641. result.x = this.x - x;
  3642. result.y = this.y - y;
  3643. result.z = this.z - z;
  3644. result.w = this.w - w;
  3645. return this;
  3646. };
  3647. /**
  3648. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3649. */
  3650. Vector4.prototype.negate = function () {
  3651. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3652. };
  3653. /**
  3654. * Multiplies the current Vector4 coordinates by scale (float).
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.scaleInPlace = function (scale) {
  3658. this.x *= scale;
  3659. this.y *= scale;
  3660. this.z *= scale;
  3661. this.w *= scale;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3666. */
  3667. Vector4.prototype.scale = function (scale) {
  3668. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.scaleToRef = function (scale, result) {
  3675. result.x = this.x * scale;
  3676. result.y = this.y * scale;
  3677. result.z = this.z * scale;
  3678. result.w = this.w * scale;
  3679. return this;
  3680. };
  3681. /**
  3682. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3683. */
  3684. Vector4.prototype.equals = function (otherVector) {
  3685. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3686. };
  3687. /**
  3688. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3689. */
  3690. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3691. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3692. return otherVector
  3693. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3694. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3695. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3696. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3697. };
  3698. /**
  3699. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3700. */
  3701. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3702. return this.x === x && this.y === y && this.z === z && this.w === w;
  3703. };
  3704. /**
  3705. * Multiplies in place the current Vector4 by the passed one.
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3709. this.x *= otherVector.x;
  3710. this.y *= otherVector.y;
  3711. this.z *= otherVector.z;
  3712. this.w *= otherVector.w;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3717. */
  3718. Vector4.prototype.multiply = function (otherVector) {
  3719. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3720. };
  3721. /**
  3722. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3726. result.x = this.x * otherVector.x;
  3727. result.y = this.y * otherVector.y;
  3728. result.z = this.z * otherVector.z;
  3729. result.w = this.w * otherVector.w;
  3730. return this;
  3731. };
  3732. /**
  3733. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3734. */
  3735. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3736. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3740. */
  3741. Vector4.prototype.divide = function (otherVector) {
  3742. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3743. };
  3744. /**
  3745. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.divideToRef = function (otherVector, result) {
  3749. result.x = this.x / otherVector.x;
  3750. result.y = this.y / otherVector.y;
  3751. result.z = this.z / otherVector.z;
  3752. result.w = this.w / otherVector.w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Divides the current Vector3 coordinates by the passed ones.
  3757. * @returns the updated Vector3.
  3758. */
  3759. Vector4.prototype.divideInPlace = function (otherVector) {
  3760. return this.divideToRef(otherVector, this);
  3761. };
  3762. /**
  3763. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3764. * @param other defines the second operand
  3765. * @returns the current updated Vector4
  3766. */
  3767. Vector4.prototype.minimizeInPlace = function (other) {
  3768. if (other.x < this.x)
  3769. this.x = other.x;
  3770. if (other.y < this.y)
  3771. this.y = other.y;
  3772. if (other.z < this.z)
  3773. this.z = other.z;
  3774. if (other.w < this.w)
  3775. this.w = other.w;
  3776. return this;
  3777. };
  3778. /**
  3779. * Updates the Vector4 coordinates with the maximum 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.maximizeInPlace = 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. // Properties
  3795. /**
  3796. * Returns the Vector4 length (float).
  3797. */
  3798. Vector4.prototype.length = function () {
  3799. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3800. };
  3801. /**
  3802. * Returns the Vector4 squared length (float).
  3803. */
  3804. Vector4.prototype.lengthSquared = function () {
  3805. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3806. };
  3807. // Methods
  3808. /**
  3809. * Normalizes in place the Vector4.
  3810. * Returns the updated Vector4.
  3811. */
  3812. Vector4.prototype.normalize = function () {
  3813. var len = this.length();
  3814. if (len === 0)
  3815. return this;
  3816. var num = 1.0 / len;
  3817. this.x *= num;
  3818. this.y *= num;
  3819. this.z *= num;
  3820. this.w *= num;
  3821. return this;
  3822. };
  3823. /**
  3824. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3825. */
  3826. Vector4.prototype.toVector3 = function () {
  3827. return new Vector3(this.x, this.y, this.z);
  3828. };
  3829. /**
  3830. * Returns a new Vector4 copied from the current one.
  3831. */
  3832. Vector4.prototype.clone = function () {
  3833. return new Vector4(this.x, this.y, this.z, this.w);
  3834. };
  3835. /**
  3836. * Updates the current Vector4 with the passed one coordinates.
  3837. * Returns the updated Vector4.
  3838. */
  3839. Vector4.prototype.copyFrom = function (source) {
  3840. this.x = source.x;
  3841. this.y = source.y;
  3842. this.z = source.z;
  3843. this.w = source.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Updates the current Vector4 coordinates with the passed floats.
  3848. * Returns the updated Vector4.
  3849. */
  3850. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3851. this.x = x;
  3852. this.y = y;
  3853. this.z = z;
  3854. this.w = w;
  3855. return this;
  3856. };
  3857. /**
  3858. * Updates the current Vector4 coordinates with the passed floats.
  3859. * Returns the updated Vector4.
  3860. */
  3861. Vector4.prototype.set = function (x, y, z, w) {
  3862. return this.copyFromFloats(x, y, z, w);
  3863. };
  3864. // Statics
  3865. /**
  3866. * Returns a new Vector4 set from the starting index of the passed array.
  3867. */
  3868. Vector4.FromArray = function (array, offset) {
  3869. if (!offset) {
  3870. offset = 0;
  3871. }
  3872. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3873. };
  3874. /**
  3875. * Updates the passed vector "result" from the starting index of the passed array.
  3876. */
  3877. Vector4.FromArrayToRef = function (array, offset, result) {
  3878. result.x = array[offset];
  3879. result.y = array[offset + 1];
  3880. result.z = array[offset + 2];
  3881. result.w = array[offset + 3];
  3882. };
  3883. /**
  3884. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3885. */
  3886. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3887. Vector4.FromArrayToRef(array, offset, result);
  3888. };
  3889. /**
  3890. * Updates the passed vector "result" coordinates from the passed floats.
  3891. */
  3892. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3893. result.x = x;
  3894. result.y = y;
  3895. result.z = z;
  3896. result.w = w;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3900. */
  3901. Vector4.Zero = function () {
  3902. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3903. };
  3904. /**
  3905. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3906. */
  3907. Vector4.One = function () {
  3908. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3909. };
  3910. /**
  3911. * Returns a new normalized Vector4 from the passed one.
  3912. */
  3913. Vector4.Normalize = function (vector) {
  3914. var result = Vector4.Zero();
  3915. Vector4.NormalizeToRef(vector, result);
  3916. return result;
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" from the normalization of the passed one.
  3920. */
  3921. Vector4.NormalizeToRef = function (vector, result) {
  3922. result.copyFrom(vector);
  3923. result.normalize();
  3924. };
  3925. Vector4.Minimize = function (left, right) {
  3926. var min = left.clone();
  3927. min.minimizeInPlace(right);
  3928. return min;
  3929. };
  3930. Vector4.Maximize = function (left, right) {
  3931. var max = left.clone();
  3932. max.maximizeInPlace(right);
  3933. return max;
  3934. };
  3935. /**
  3936. * Returns the distance (float) between the vectors "value1" and "value2".
  3937. */
  3938. Vector4.Distance = function (value1, value2) {
  3939. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3940. };
  3941. /**
  3942. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3943. */
  3944. Vector4.DistanceSquared = function (value1, value2) {
  3945. var x = value1.x - value2.x;
  3946. var y = value1.y - value2.y;
  3947. var z = value1.z - value2.z;
  3948. var w = value1.w - value2.w;
  3949. return (x * x) + (y * y) + (z * z) + (w * w);
  3950. };
  3951. /**
  3952. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3953. */
  3954. Vector4.Center = function (value1, value2) {
  3955. var center = value1.add(value2);
  3956. center.scaleInPlace(0.5);
  3957. return center;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3961. * This methods computes transformed normalized direction vectors only.
  3962. */
  3963. Vector4.TransformNormal = function (vector, transformation) {
  3964. var result = Vector4.Zero();
  3965. Vector4.TransformNormalToRef(vector, transformation, result);
  3966. return result;
  3967. };
  3968. /**
  3969. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3970. * This methods computes transformed normalized direction vectors only.
  3971. */
  3972. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3973. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3974. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3975. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3976. result.x = x;
  3977. result.y = y;
  3978. result.z = z;
  3979. result.w = vector.w;
  3980. };
  3981. /**
  3982. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3983. * This methods computes transformed normalized direction vectors only.
  3984. */
  3985. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3986. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3987. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3988. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3989. result.w = w;
  3990. };
  3991. return Vector4;
  3992. }());
  3993. BABYLON.Vector4 = Vector4;
  3994. var Size = /** @class */ (function () {
  3995. /**
  3996. * Creates a Size object from the passed width and height (floats).
  3997. */
  3998. function Size(width, height) {
  3999. this.width = width;
  4000. this.height = height;
  4001. }
  4002. // Returns a string with the Size width and height.
  4003. Size.prototype.toString = function () {
  4004. return "{W: " + this.width + ", H: " + this.height + "}";
  4005. };
  4006. /**
  4007. * Returns the string "Size"
  4008. */
  4009. Size.prototype.getClassName = function () {
  4010. return "Size";
  4011. };
  4012. /**
  4013. * Returns the Size hash code.
  4014. */
  4015. Size.prototype.getHashCode = function () {
  4016. var hash = this.width || 0;
  4017. hash = (hash * 397) ^ (this.height || 0);
  4018. return hash;
  4019. };
  4020. /**
  4021. * Updates the current size from the passed one.
  4022. * Returns the updated Size.
  4023. */
  4024. Size.prototype.copyFrom = function (src) {
  4025. this.width = src.width;
  4026. this.height = src.height;
  4027. };
  4028. /**
  4029. * Updates in place the current Size from the passed floats.
  4030. * Returns the updated Size.
  4031. */
  4032. Size.prototype.copyFromFloats = function (width, height) {
  4033. this.width = width;
  4034. this.height = height;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates in place the current Size from the passed floats.
  4039. * Returns the updated Size.
  4040. */
  4041. Size.prototype.set = function (width, height) {
  4042. return this.copyFromFloats(width, height);
  4043. };
  4044. /**
  4045. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4046. */
  4047. Size.prototype.multiplyByFloats = function (w, h) {
  4048. return new Size(this.width * w, this.height * h);
  4049. };
  4050. /**
  4051. * Returns a new Size copied from the passed one.
  4052. */
  4053. Size.prototype.clone = function () {
  4054. return new Size(this.width, this.height);
  4055. };
  4056. /**
  4057. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4058. */
  4059. Size.prototype.equals = function (other) {
  4060. if (!other) {
  4061. return false;
  4062. }
  4063. return (this.width === other.width) && (this.height === other.height);
  4064. };
  4065. Object.defineProperty(Size.prototype, "surface", {
  4066. /**
  4067. * Returns the surface of the Size : width * height (float).
  4068. */
  4069. get: function () {
  4070. return this.width * this.height;
  4071. },
  4072. enumerable: true,
  4073. configurable: true
  4074. });
  4075. /**
  4076. * Returns a new Size set to (0.0, 0.0)
  4077. */
  4078. Size.Zero = function () {
  4079. return new Size(0.0, 0.0);
  4080. };
  4081. /**
  4082. * Returns a new Size set as the addition result of the current Size and the passed one.
  4083. */
  4084. Size.prototype.add = function (otherSize) {
  4085. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4086. return r;
  4087. };
  4088. /**
  4089. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4090. */
  4091. Size.prototype.subtract = function (otherSize) {
  4092. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4093. return r;
  4094. };
  4095. /**
  4096. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4097. */
  4098. Size.Lerp = function (start, end, amount) {
  4099. var w = start.width + ((end.width - start.width) * amount);
  4100. var h = start.height + ((end.height - start.height) * amount);
  4101. return new Size(w, h);
  4102. };
  4103. return Size;
  4104. }());
  4105. BABYLON.Size = Size;
  4106. var Quaternion = /** @class */ (function () {
  4107. /**
  4108. * Creates a new Quaternion from the passed floats.
  4109. */
  4110. function Quaternion(x, y, z, w) {
  4111. if (x === void 0) { x = 0.0; }
  4112. if (y === void 0) { y = 0.0; }
  4113. if (z === void 0) { z = 0.0; }
  4114. if (w === void 0) { w = 1.0; }
  4115. this.x = x;
  4116. this.y = y;
  4117. this.z = z;
  4118. this.w = w;
  4119. }
  4120. /**
  4121. * Returns a string with the Quaternion coordinates.
  4122. */
  4123. Quaternion.prototype.toString = function () {
  4124. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4125. };
  4126. /**
  4127. * Returns the string "Quaternion".
  4128. */
  4129. Quaternion.prototype.getClassName = function () {
  4130. return "Quaternion";
  4131. };
  4132. /**
  4133. * Returns the Quaternion hash code.
  4134. */
  4135. Quaternion.prototype.getHashCode = function () {
  4136. var hash = this.x || 0;
  4137. hash = (hash * 397) ^ (this.y || 0);
  4138. hash = (hash * 397) ^ (this.z || 0);
  4139. hash = (hash * 397) ^ (this.w || 0);
  4140. return hash;
  4141. };
  4142. /**
  4143. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4144. */
  4145. Quaternion.prototype.asArray = function () {
  4146. return [this.x, this.y, this.z, this.w];
  4147. };
  4148. /**
  4149. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4150. */
  4151. Quaternion.prototype.equals = function (otherQuaternion) {
  4152. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4153. };
  4154. /**
  4155. * Returns a new Quaternion copied from the current one.
  4156. */
  4157. Quaternion.prototype.clone = function () {
  4158. return new Quaternion(this.x, this.y, this.z, this.w);
  4159. };
  4160. /**
  4161. * Updates the current Quaternion from the passed one coordinates.
  4162. * Returns the updated Quaterion.
  4163. */
  4164. Quaternion.prototype.copyFrom = function (other) {
  4165. this.x = other.x;
  4166. this.y = other.y;
  4167. this.z = other.z;
  4168. this.w = other.w;
  4169. return this;
  4170. };
  4171. /**
  4172. * Updates the current Quaternion from the passed float coordinates.
  4173. * Returns the updated Quaterion.
  4174. */
  4175. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4176. this.x = x;
  4177. this.y = y;
  4178. this.z = z;
  4179. this.w = w;
  4180. return this;
  4181. };
  4182. /**
  4183. * Updates the current Quaternion from the passed float coordinates.
  4184. * Returns the updated Quaterion.
  4185. */
  4186. Quaternion.prototype.set = function (x, y, z, w) {
  4187. return this.copyFromFloats(x, y, z, w);
  4188. };
  4189. /**
  4190. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4191. */
  4192. Quaternion.prototype.add = function (other) {
  4193. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4194. };
  4195. /**
  4196. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4197. */
  4198. Quaternion.prototype.subtract = function (other) {
  4199. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4200. };
  4201. /**
  4202. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4203. */
  4204. Quaternion.prototype.scale = function (value) {
  4205. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4206. };
  4207. /**
  4208. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4209. */
  4210. Quaternion.prototype.multiply = function (q1) {
  4211. var result = new Quaternion(0, 0, 0, 1.0);
  4212. this.multiplyToRef(q1, result);
  4213. return result;
  4214. };
  4215. /**
  4216. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4217. * Returns the current Quaternion.
  4218. */
  4219. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4220. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4221. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4222. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4223. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4224. result.copyFromFloats(x, y, z, w);
  4225. return this;
  4226. };
  4227. /**
  4228. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4229. * Returns the updated Quaternion.
  4230. */
  4231. Quaternion.prototype.multiplyInPlace = function (q1) {
  4232. this.multiplyToRef(q1, this);
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4237. * Returns the current Quaternion.
  4238. */
  4239. Quaternion.prototype.conjugateToRef = function (ref) {
  4240. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4241. return this;
  4242. };
  4243. /**
  4244. * Conjugates in place the current Quaternion.
  4245. * Returns the updated Quaternion.
  4246. */
  4247. Quaternion.prototype.conjugateInPlace = function () {
  4248. this.x *= -1;
  4249. this.y *= -1;
  4250. this.z *= -1;
  4251. return this;
  4252. };
  4253. /**
  4254. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4255. */
  4256. Quaternion.prototype.conjugate = function () {
  4257. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4258. return result;
  4259. };
  4260. /**
  4261. * Returns the Quaternion length (float).
  4262. */
  4263. Quaternion.prototype.length = function () {
  4264. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4265. };
  4266. /**
  4267. * Normalize in place the current Quaternion.
  4268. * Returns the updated Quaternion.
  4269. */
  4270. Quaternion.prototype.normalize = function () {
  4271. var length = 1.0 / this.length();
  4272. this.x *= length;
  4273. this.y *= length;
  4274. this.z *= length;
  4275. this.w *= length;
  4276. return this;
  4277. };
  4278. /**
  4279. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4280. */
  4281. Quaternion.prototype.toEulerAngles = function (order) {
  4282. if (order === void 0) { order = "YZX"; }
  4283. var result = Vector3.Zero();
  4284. this.toEulerAnglesToRef(result, order);
  4285. return result;
  4286. };
  4287. /**
  4288. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4289. * Returns the current Quaternion.
  4290. */
  4291. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4292. if (order === void 0) { order = "YZX"; }
  4293. var qz = this.z;
  4294. var qx = this.x;
  4295. var qy = this.y;
  4296. var qw = this.w;
  4297. var sqw = qw * qw;
  4298. var sqz = qz * qz;
  4299. var sqx = qx * qx;
  4300. var sqy = qy * qy;
  4301. var zAxisY = qy * qz - qx * qw;
  4302. var limit = .4999999;
  4303. if (zAxisY < -limit) {
  4304. result.y = 2 * Math.atan2(qy, qw);
  4305. result.x = Math.PI / 2;
  4306. result.z = 0;
  4307. }
  4308. else if (zAxisY > limit) {
  4309. result.y = 2 * Math.atan2(qy, qw);
  4310. result.x = -Math.PI / 2;
  4311. result.z = 0;
  4312. }
  4313. else {
  4314. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4315. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4316. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4317. }
  4318. return this;
  4319. };
  4320. /**
  4321. * Updates the passed rotation matrix with the current Quaternion values.
  4322. * Returns the current Quaternion.
  4323. */
  4324. Quaternion.prototype.toRotationMatrix = function (result) {
  4325. var xx = this.x * this.x;
  4326. var yy = this.y * this.y;
  4327. var zz = this.z * this.z;
  4328. var xy = this.x * this.y;
  4329. var zw = this.z * this.w;
  4330. var zx = this.z * this.x;
  4331. var yw = this.y * this.w;
  4332. var yz = this.y * this.z;
  4333. var xw = this.x * this.w;
  4334. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4335. result.m[1] = 2.0 * (xy + zw);
  4336. result.m[2] = 2.0 * (zx - yw);
  4337. result.m[3] = 0;
  4338. result.m[4] = 2.0 * (xy - zw);
  4339. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4340. result.m[6] = 2.0 * (yz + xw);
  4341. result.m[7] = 0;
  4342. result.m[8] = 2.0 * (zx + yw);
  4343. result.m[9] = 2.0 * (yz - xw);
  4344. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4345. result.m[11] = 0;
  4346. result.m[12] = 0;
  4347. result.m[13] = 0;
  4348. result.m[14] = 0;
  4349. result.m[15] = 1.0;
  4350. result._markAsUpdated();
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Quaternion from the passed rotation matrix values.
  4355. * Returns the updated Quaternion.
  4356. */
  4357. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4358. Quaternion.FromRotationMatrixToRef(matrix, this);
  4359. return this;
  4360. };
  4361. // Statics
  4362. /**
  4363. * Returns a new Quaternion set from the passed rotation matrix values.
  4364. */
  4365. Quaternion.FromRotationMatrix = function (matrix) {
  4366. var result = new Quaternion();
  4367. Quaternion.FromRotationMatrixToRef(matrix, result);
  4368. return result;
  4369. };
  4370. /**
  4371. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4372. */
  4373. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4374. var data = matrix.m;
  4375. var m11 = data[0], m12 = data[4], m13 = data[8];
  4376. var m21 = data[1], m22 = data[5], m23 = data[9];
  4377. var m31 = data[2], m32 = data[6], m33 = data[10];
  4378. var trace = m11 + m22 + m33;
  4379. var s;
  4380. if (trace > 0) {
  4381. s = 0.5 / Math.sqrt(trace + 1.0);
  4382. result.w = 0.25 / s;
  4383. result.x = (m32 - m23) * s;
  4384. result.y = (m13 - m31) * s;
  4385. result.z = (m21 - m12) * s;
  4386. }
  4387. else if (m11 > m22 && m11 > m33) {
  4388. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4389. result.w = (m32 - m23) / s;
  4390. result.x = 0.25 * s;
  4391. result.y = (m12 + m21) / s;
  4392. result.z = (m13 + m31) / s;
  4393. }
  4394. else if (m22 > m33) {
  4395. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4396. result.w = (m13 - m31) / s;
  4397. result.x = (m12 + m21) / s;
  4398. result.y = 0.25 * s;
  4399. result.z = (m23 + m32) / s;
  4400. }
  4401. else {
  4402. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4403. result.w = (m21 - m12) / s;
  4404. result.x = (m13 + m31) / s;
  4405. result.y = (m23 + m32) / s;
  4406. result.z = 0.25 * s;
  4407. }
  4408. };
  4409. /**
  4410. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4411. */
  4412. Quaternion.Zero = function () {
  4413. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Quaternion as the inverted current Quaternion.
  4417. */
  4418. Quaternion.Inverse = function (q) {
  4419. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4420. };
  4421. /**
  4422. * Returns the identity Quaternion.
  4423. */
  4424. Quaternion.Identity = function () {
  4425. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4426. };
  4427. Quaternion.IsIdentity = function (quaternion) {
  4428. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4429. };
  4430. /**
  4431. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4432. */
  4433. Quaternion.RotationAxis = function (axis, angle) {
  4434. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4435. };
  4436. /**
  4437. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4438. */
  4439. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4440. var sin = Math.sin(angle / 2);
  4441. axis.normalize();
  4442. result.w = Math.cos(angle / 2);
  4443. result.x = axis.x * sin;
  4444. result.y = axis.y * sin;
  4445. result.z = axis.z * sin;
  4446. return result;
  4447. };
  4448. /**
  4449. * Retuns a new Quaternion set from the starting index of the passed array.
  4450. */
  4451. Quaternion.FromArray = function (array, offset) {
  4452. if (!offset) {
  4453. offset = 0;
  4454. }
  4455. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4459. */
  4460. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4461. var q = new Quaternion();
  4462. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4463. return q;
  4464. };
  4465. /**
  4466. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4467. */
  4468. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4469. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4470. var halfRoll = roll * 0.5;
  4471. var halfPitch = pitch * 0.5;
  4472. var halfYaw = yaw * 0.5;
  4473. var sinRoll = Math.sin(halfRoll);
  4474. var cosRoll = Math.cos(halfRoll);
  4475. var sinPitch = Math.sin(halfPitch);
  4476. var cosPitch = Math.cos(halfPitch);
  4477. var sinYaw = Math.sin(halfYaw);
  4478. var cosYaw = Math.cos(halfYaw);
  4479. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4480. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4481. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4482. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4483. };
  4484. /**
  4485. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4486. */
  4487. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4488. var result = new Quaternion();
  4489. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4490. return result;
  4491. };
  4492. /**
  4493. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4494. */
  4495. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4496. // Produces a quaternion from Euler angles in the z-x-z orientation
  4497. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4498. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4499. var halfBeta = beta * 0.5;
  4500. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4501. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4502. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4503. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4504. };
  4505. /**
  4506. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4507. * cf to Vector3.RotationFromAxis() documentation.
  4508. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4509. */
  4510. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4511. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4513. return quat;
  4514. };
  4515. /**
  4516. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4517. * cf to Vector3.RotationFromAxis() documentation.
  4518. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4519. */
  4520. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4521. var rotMat = MathTmp.Matrix[0];
  4522. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4523. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4524. };
  4525. Quaternion.Slerp = function (left, right, amount) {
  4526. var result = Quaternion.Identity();
  4527. Quaternion.SlerpToRef(left, right, amount, result);
  4528. return result;
  4529. };
  4530. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4531. var num2;
  4532. var num3;
  4533. var num = amount;
  4534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4535. var flag = false;
  4536. if (num4 < 0) {
  4537. flag = true;
  4538. num4 = -num4;
  4539. }
  4540. if (num4 > 0.999999) {
  4541. num3 = 1 - num;
  4542. num2 = flag ? -num : num;
  4543. }
  4544. else {
  4545. var num5 = Math.acos(num4);
  4546. var num6 = (1.0 / Math.sin(num5));
  4547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4549. }
  4550. result.x = (num3 * left.x) + (num2 * right.x);
  4551. result.y = (num3 * left.y) + (num2 * right.y);
  4552. result.z = (num3 * left.z) + (num2 * right.z);
  4553. result.w = (num3 * left.w) + (num2 * right.w);
  4554. };
  4555. /**
  4556. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4557. */
  4558. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4559. var squared = amount * amount;
  4560. var cubed = amount * squared;
  4561. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4562. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4563. var part3 = (cubed - (2.0 * squared)) + amount;
  4564. var part4 = cubed - squared;
  4565. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4566. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4567. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4568. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4569. return new Quaternion(x, y, z, w);
  4570. };
  4571. return Quaternion;
  4572. }());
  4573. BABYLON.Quaternion = Quaternion;
  4574. var Matrix = /** @class */ (function () {
  4575. function Matrix() {
  4576. this._isIdentity = false;
  4577. this._isIdentityDirty = true;
  4578. this.m = new Float32Array(16);
  4579. this._markAsUpdated();
  4580. }
  4581. Matrix.prototype._markAsUpdated = function () {
  4582. this.updateFlag = Matrix._updateFlagSeed++;
  4583. this._isIdentityDirty = true;
  4584. };
  4585. // Properties
  4586. /**
  4587. * Boolean : True is the matrix is the identity matrix
  4588. */
  4589. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4590. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4591. if (this._isIdentityDirty) {
  4592. this._isIdentityDirty = false;
  4593. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4594. this._isIdentity = false;
  4595. }
  4596. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4597. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4598. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4599. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4600. this._isIdentity = false;
  4601. }
  4602. else {
  4603. this._isIdentity = true;
  4604. }
  4605. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4606. this._isIdentity = false;
  4607. }
  4608. }
  4609. return this._isIdentity;
  4610. };
  4611. /**
  4612. * Returns the matrix determinant (float).
  4613. */
  4614. Matrix.prototype.determinant = function () {
  4615. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4616. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4617. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4618. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4619. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4620. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4621. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4622. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4623. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4624. };
  4625. // Methods
  4626. /**
  4627. * Returns the matrix underlying array.
  4628. */
  4629. Matrix.prototype.toArray = function () {
  4630. return this.m;
  4631. };
  4632. /**
  4633. * Returns the matrix underlying array.
  4634. */
  4635. Matrix.prototype.asArray = function () {
  4636. return this.toArray();
  4637. };
  4638. /**
  4639. * Inverts in place the Matrix.
  4640. * Returns the Matrix inverted.
  4641. */
  4642. Matrix.prototype.invert = function () {
  4643. this.invertToRef(this);
  4644. return this;
  4645. };
  4646. /**
  4647. * Sets all the matrix elements to zero.
  4648. * Returns the Matrix.
  4649. */
  4650. Matrix.prototype.reset = function () {
  4651. for (var index = 0; index < 16; index++) {
  4652. this.m[index] = 0.0;
  4653. }
  4654. this._markAsUpdated();
  4655. return this;
  4656. };
  4657. /**
  4658. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4659. */
  4660. Matrix.prototype.add = function (other) {
  4661. var result = new Matrix();
  4662. this.addToRef(other, result);
  4663. return result;
  4664. };
  4665. /**
  4666. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4667. * Returns the Matrix.
  4668. */
  4669. Matrix.prototype.addToRef = function (other, result) {
  4670. for (var index = 0; index < 16; index++) {
  4671. result.m[index] = this.m[index] + other.m[index];
  4672. }
  4673. result._markAsUpdated();
  4674. return this;
  4675. };
  4676. /**
  4677. * Adds in place the passed matrix to the current Matrix.
  4678. * Returns the updated Matrix.
  4679. */
  4680. Matrix.prototype.addToSelf = function (other) {
  4681. for (var index = 0; index < 16; index++) {
  4682. this.m[index] += other.m[index];
  4683. }
  4684. this._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Sets the passed matrix with the current inverted Matrix.
  4689. * Returns the unmodified current Matrix.
  4690. */
  4691. Matrix.prototype.invertToRef = function (other) {
  4692. var l1 = this.m[0];
  4693. var l2 = this.m[1];
  4694. var l3 = this.m[2];
  4695. var l4 = this.m[3];
  4696. var l5 = this.m[4];
  4697. var l6 = this.m[5];
  4698. var l7 = this.m[6];
  4699. var l8 = this.m[7];
  4700. var l9 = this.m[8];
  4701. var l10 = this.m[9];
  4702. var l11 = this.m[10];
  4703. var l12 = this.m[11];
  4704. var l13 = this.m[12];
  4705. var l14 = this.m[13];
  4706. var l15 = this.m[14];
  4707. var l16 = this.m[15];
  4708. var l17 = (l11 * l16) - (l12 * l15);
  4709. var l18 = (l10 * l16) - (l12 * l14);
  4710. var l19 = (l10 * l15) - (l11 * l14);
  4711. var l20 = (l9 * l16) - (l12 * l13);
  4712. var l21 = (l9 * l15) - (l11 * l13);
  4713. var l22 = (l9 * l14) - (l10 * l13);
  4714. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4715. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4716. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4717. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4718. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4719. var l28 = (l7 * l16) - (l8 * l15);
  4720. var l29 = (l6 * l16) - (l8 * l14);
  4721. var l30 = (l6 * l15) - (l7 * l14);
  4722. var l31 = (l5 * l16) - (l8 * l13);
  4723. var l32 = (l5 * l15) - (l7 * l13);
  4724. var l33 = (l5 * l14) - (l6 * l13);
  4725. var l34 = (l7 * l12) - (l8 * l11);
  4726. var l35 = (l6 * l12) - (l8 * l10);
  4727. var l36 = (l6 * l11) - (l7 * l10);
  4728. var l37 = (l5 * l12) - (l8 * l9);
  4729. var l38 = (l5 * l11) - (l7 * l9);
  4730. var l39 = (l5 * l10) - (l6 * l9);
  4731. other.m[0] = l23 * l27;
  4732. other.m[4] = l24 * l27;
  4733. other.m[8] = l25 * l27;
  4734. other.m[12] = l26 * l27;
  4735. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4736. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4737. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4738. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4739. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4740. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4741. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4742. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4743. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4744. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4745. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4746. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4747. other._markAsUpdated();
  4748. return this;
  4749. };
  4750. /**
  4751. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4752. * Returns the updated Matrix.
  4753. */
  4754. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4755. this.m[12] = x;
  4756. this.m[13] = y;
  4757. this.m[14] = z;
  4758. this._markAsUpdated();
  4759. return this;
  4760. };
  4761. /**
  4762. * Inserts the translation vector in the current Matrix.
  4763. * Returns the updated Matrix.
  4764. */
  4765. Matrix.prototype.setTranslation = function (vector3) {
  4766. this.m[12] = vector3.x;
  4767. this.m[13] = vector3.y;
  4768. this.m[14] = vector3.z;
  4769. this._markAsUpdated();
  4770. return this;
  4771. };
  4772. /**
  4773. * Returns a new Vector3 as the extracted translation from the Matrix.
  4774. */
  4775. Matrix.prototype.getTranslation = function () {
  4776. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4777. };
  4778. /**
  4779. * Fill a Vector3 with the extracted translation from the Matrix.
  4780. */
  4781. Matrix.prototype.getTranslationToRef = function (result) {
  4782. result.x = this.m[12];
  4783. result.y = this.m[13];
  4784. result.z = this.m[14];
  4785. return this;
  4786. };
  4787. /**
  4788. * Remove rotation and scaling part from the Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.removeRotationAndScaling = function () {
  4792. this.setRowFromFloats(0, 1, 0, 0, 0);
  4793. this.setRowFromFloats(1, 0, 1, 0, 0);
  4794. this.setRowFromFloats(2, 0, 0, 1, 0);
  4795. return this;
  4796. };
  4797. /**
  4798. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4799. */
  4800. Matrix.prototype.multiply = function (other) {
  4801. var result = new Matrix();
  4802. this.multiplyToRef(other, result);
  4803. return result;
  4804. };
  4805. /**
  4806. * Updates the current Matrix from the passed one values.
  4807. * Returns the updated Matrix.
  4808. */
  4809. Matrix.prototype.copyFrom = function (other) {
  4810. for (var index = 0; index < 16; index++) {
  4811. this.m[index] = other.m[index];
  4812. }
  4813. this._markAsUpdated();
  4814. return this;
  4815. };
  4816. /**
  4817. * Populates the passed array from the starting index with the Matrix values.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.copyToArray = function (array, offset) {
  4821. if (offset === void 0) { offset = 0; }
  4822. for (var index = 0; index < 16; index++) {
  4823. array[offset + index] = this.m[index];
  4824. }
  4825. return this;
  4826. };
  4827. /**
  4828. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4829. */
  4830. Matrix.prototype.multiplyToRef = function (other, result) {
  4831. this.multiplyToArray(other, result.m, 0);
  4832. result._markAsUpdated();
  4833. return this;
  4834. };
  4835. /**
  4836. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4837. */
  4838. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4839. var tm0 = this.m[0];
  4840. var tm1 = this.m[1];
  4841. var tm2 = this.m[2];
  4842. var tm3 = this.m[3];
  4843. var tm4 = this.m[4];
  4844. var tm5 = this.m[5];
  4845. var tm6 = this.m[6];
  4846. var tm7 = this.m[7];
  4847. var tm8 = this.m[8];
  4848. var tm9 = this.m[9];
  4849. var tm10 = this.m[10];
  4850. var tm11 = this.m[11];
  4851. var tm12 = this.m[12];
  4852. var tm13 = this.m[13];
  4853. var tm14 = this.m[14];
  4854. var tm15 = this.m[15];
  4855. var om0 = other.m[0];
  4856. var om1 = other.m[1];
  4857. var om2 = other.m[2];
  4858. var om3 = other.m[3];
  4859. var om4 = other.m[4];
  4860. var om5 = other.m[5];
  4861. var om6 = other.m[6];
  4862. var om7 = other.m[7];
  4863. var om8 = other.m[8];
  4864. var om9 = other.m[9];
  4865. var om10 = other.m[10];
  4866. var om11 = other.m[11];
  4867. var om12 = other.m[12];
  4868. var om13 = other.m[13];
  4869. var om14 = other.m[14];
  4870. var om15 = other.m[15];
  4871. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4872. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4873. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4874. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4875. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4876. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4877. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4878. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4879. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4880. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4881. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4882. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4883. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4884. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4885. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4886. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4887. return this;
  4888. };
  4889. /**
  4890. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4891. */
  4892. Matrix.prototype.equals = function (value) {
  4893. return value &&
  4894. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4895. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4896. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4897. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4898. };
  4899. /**
  4900. * Returns a new Matrix from the current Matrix.
  4901. */
  4902. Matrix.prototype.clone = function () {
  4903. 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]);
  4904. };
  4905. /**
  4906. * Returns the string "Matrix"
  4907. */
  4908. Matrix.prototype.getClassName = function () {
  4909. return "Matrix";
  4910. };
  4911. /**
  4912. * Returns the Matrix hash code.
  4913. */
  4914. Matrix.prototype.getHashCode = function () {
  4915. var hash = this.m[0] || 0;
  4916. for (var i = 1; i < 16; i++) {
  4917. hash = (hash * 397) ^ (this.m[i] || 0);
  4918. }
  4919. return hash;
  4920. };
  4921. /**
  4922. * Decomposes the current Matrix into :
  4923. * - a scale vector3 passed as a reference to update,
  4924. * - a rotation quaternion passed as a reference to update,
  4925. * - a translation vector3 passed as a reference to update.
  4926. * Returns the true if operation was successful.
  4927. */
  4928. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4929. translation.x = this.m[12];
  4930. translation.y = this.m[13];
  4931. translation.z = this.m[14];
  4932. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4933. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4934. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4935. if (this.determinant() <= 0) {
  4936. scale.y *= -1;
  4937. }
  4938. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4939. rotation.x = 0;
  4940. rotation.y = 0;
  4941. rotation.z = 0;
  4942. rotation.w = 1;
  4943. return false;
  4944. }
  4945. 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]);
  4946. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4947. return true;
  4948. };
  4949. /**
  4950. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4951. */
  4952. Matrix.prototype.getRotationMatrix = function () {
  4953. var result = Matrix.Identity();
  4954. this.getRotationMatrixToRef(result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4959. * Returns the current Matrix.
  4960. */
  4961. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4962. var m = this.m;
  4963. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4964. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4965. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4966. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4967. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4968. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4969. 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);
  4970. return this;
  4971. };
  4972. // Statics
  4973. /**
  4974. * Returns a new Matrix set from the starting index of the passed array.
  4975. */
  4976. Matrix.FromArray = function (array, offset) {
  4977. var result = new Matrix();
  4978. if (!offset) {
  4979. offset = 0;
  4980. }
  4981. Matrix.FromArrayToRef(array, offset, result);
  4982. return result;
  4983. };
  4984. /**
  4985. * Sets the passed "result" matrix from the starting index of the passed array.
  4986. */
  4987. Matrix.FromArrayToRef = function (array, offset, result) {
  4988. for (var index = 0; index < 16; index++) {
  4989. result.m[index] = array[index + offset];
  4990. }
  4991. result._markAsUpdated();
  4992. };
  4993. /**
  4994. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4995. */
  4996. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4997. for (var index = 0; index < 16; index++) {
  4998. result.m[index] = array[index + offset] * scale;
  4999. }
  5000. result._markAsUpdated();
  5001. };
  5002. /**
  5003. * Sets the passed matrix "result" with the 16 passed floats.
  5004. */
  5005. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5006. result.m[0] = initialM11;
  5007. result.m[1] = initialM12;
  5008. result.m[2] = initialM13;
  5009. result.m[3] = initialM14;
  5010. result.m[4] = initialM21;
  5011. result.m[5] = initialM22;
  5012. result.m[6] = initialM23;
  5013. result.m[7] = initialM24;
  5014. result.m[8] = initialM31;
  5015. result.m[9] = initialM32;
  5016. result.m[10] = initialM33;
  5017. result.m[11] = initialM34;
  5018. result.m[12] = initialM41;
  5019. result.m[13] = initialM42;
  5020. result.m[14] = initialM43;
  5021. result.m[15] = initialM44;
  5022. result._markAsUpdated();
  5023. };
  5024. /**
  5025. * Returns the index-th row of the current matrix as a new Vector4.
  5026. */
  5027. Matrix.prototype.getRow = function (index) {
  5028. if (index < 0 || index > 3) {
  5029. return null;
  5030. }
  5031. var i = index * 4;
  5032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5033. };
  5034. /**
  5035. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5036. * Returns the updated Matrix.
  5037. */
  5038. Matrix.prototype.setRow = function (index, row) {
  5039. if (index < 0 || index > 3) {
  5040. return this;
  5041. }
  5042. var i = index * 4;
  5043. this.m[i + 0] = row.x;
  5044. this.m[i + 1] = row.y;
  5045. this.m[i + 2] = row.z;
  5046. this.m[i + 3] = row.w;
  5047. this._markAsUpdated();
  5048. return this;
  5049. };
  5050. /**
  5051. * Compute the transpose of the matrix.
  5052. * Returns a new Matrix.
  5053. */
  5054. Matrix.prototype.transpose = function () {
  5055. return Matrix.Transpose(this);
  5056. };
  5057. /**
  5058. * Compute the transpose of the matrix.
  5059. * Returns the current matrix.
  5060. */
  5061. Matrix.prototype.transposeToRef = function (result) {
  5062. Matrix.TransposeToRef(this, result);
  5063. return this;
  5064. };
  5065. /**
  5066. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5067. * Returns the updated Matrix.
  5068. */
  5069. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5070. if (index < 0 || index > 3) {
  5071. return this;
  5072. }
  5073. var i = index * 4;
  5074. this.m[i + 0] = x;
  5075. this.m[i + 1] = y;
  5076. this.m[i + 2] = z;
  5077. this.m[i + 3] = w;
  5078. this._markAsUpdated();
  5079. return this;
  5080. };
  5081. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5082. /**
  5083. * Static identity matrix to be used as readonly matrix
  5084. * Must not be updated.
  5085. */
  5086. get: function () {
  5087. return Matrix._identityReadOnly;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. /**
  5093. * Returns a new Matrix set from the 16 passed floats.
  5094. */
  5095. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5096. var result = new Matrix();
  5097. result.m[0] = initialM11;
  5098. result.m[1] = initialM12;
  5099. result.m[2] = initialM13;
  5100. result.m[3] = initialM14;
  5101. result.m[4] = initialM21;
  5102. result.m[5] = initialM22;
  5103. result.m[6] = initialM23;
  5104. result.m[7] = initialM24;
  5105. result.m[8] = initialM31;
  5106. result.m[9] = initialM32;
  5107. result.m[10] = initialM33;
  5108. result.m[11] = initialM34;
  5109. result.m[12] = initialM41;
  5110. result.m[13] = initialM42;
  5111. result.m[14] = initialM43;
  5112. result.m[15] = initialM44;
  5113. return result;
  5114. };
  5115. /**
  5116. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5117. */
  5118. Matrix.Compose = function (scale, rotation, translation) {
  5119. var result = Matrix.Identity();
  5120. Matrix.ComposeToRef(scale, rotation, translation, result);
  5121. return result;
  5122. };
  5123. /**
  5124. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5125. */
  5126. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5127. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5128. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5129. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5130. result.setTranslation(translation);
  5131. };
  5132. /**
  5133. * Returns a new indentity Matrix.
  5134. */
  5135. Matrix.Identity = function () {
  5136. 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);
  5137. };
  5138. /**
  5139. * Sets the passed "result" as an identity matrix.
  5140. */
  5141. Matrix.IdentityToRef = function (result) {
  5142. 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);
  5143. };
  5144. /**
  5145. * Returns a new zero Matrix.
  5146. */
  5147. Matrix.Zero = function () {
  5148. 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);
  5149. };
  5150. /**
  5151. * Returns a new rotation matrix for "angle" radians around the X axis.
  5152. */
  5153. Matrix.RotationX = function (angle) {
  5154. var result = new Matrix();
  5155. Matrix.RotationXToRef(angle, result);
  5156. return result;
  5157. };
  5158. /**
  5159. * Returns a new Matrix as the passed inverted one.
  5160. */
  5161. Matrix.Invert = function (source) {
  5162. var result = new Matrix();
  5163. source.invertToRef(result);
  5164. return result;
  5165. };
  5166. /**
  5167. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5168. */
  5169. Matrix.RotationXToRef = function (angle, result) {
  5170. var s = Math.sin(angle);
  5171. var c = Math.cos(angle);
  5172. result.m[0] = 1.0;
  5173. result.m[15] = 1.0;
  5174. result.m[5] = c;
  5175. result.m[10] = c;
  5176. result.m[9] = -s;
  5177. result.m[6] = s;
  5178. result.m[1] = 0.0;
  5179. result.m[2] = 0.0;
  5180. result.m[3] = 0.0;
  5181. result.m[4] = 0.0;
  5182. result.m[7] = 0.0;
  5183. result.m[8] = 0.0;
  5184. result.m[11] = 0.0;
  5185. result.m[12] = 0.0;
  5186. result.m[13] = 0.0;
  5187. result.m[14] = 0.0;
  5188. result._markAsUpdated();
  5189. };
  5190. /**
  5191. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5192. */
  5193. Matrix.RotationY = function (angle) {
  5194. var result = new Matrix();
  5195. Matrix.RotationYToRef(angle, result);
  5196. return result;
  5197. };
  5198. /**
  5199. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5200. */
  5201. Matrix.RotationYToRef = function (angle, result) {
  5202. var s = Math.sin(angle);
  5203. var c = Math.cos(angle);
  5204. result.m[5] = 1.0;
  5205. result.m[15] = 1.0;
  5206. result.m[0] = c;
  5207. result.m[2] = -s;
  5208. result.m[8] = s;
  5209. result.m[10] = c;
  5210. result.m[1] = 0.0;
  5211. result.m[3] = 0.0;
  5212. result.m[4] = 0.0;
  5213. result.m[6] = 0.0;
  5214. result.m[7] = 0.0;
  5215. result.m[9] = 0.0;
  5216. result.m[11] = 0.0;
  5217. result.m[12] = 0.0;
  5218. result.m[13] = 0.0;
  5219. result.m[14] = 0.0;
  5220. result._markAsUpdated();
  5221. };
  5222. /**
  5223. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5224. */
  5225. Matrix.RotationZ = function (angle) {
  5226. var result = new Matrix();
  5227. Matrix.RotationZToRef(angle, result);
  5228. return result;
  5229. };
  5230. /**
  5231. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5232. */
  5233. Matrix.RotationZToRef = function (angle, result) {
  5234. var s = Math.sin(angle);
  5235. var c = Math.cos(angle);
  5236. result.m[10] = 1.0;
  5237. result.m[15] = 1.0;
  5238. result.m[0] = c;
  5239. result.m[1] = s;
  5240. result.m[4] = -s;
  5241. result.m[5] = c;
  5242. result.m[2] = 0.0;
  5243. result.m[3] = 0.0;
  5244. result.m[6] = 0.0;
  5245. result.m[7] = 0.0;
  5246. result.m[8] = 0.0;
  5247. result.m[9] = 0.0;
  5248. result.m[11] = 0.0;
  5249. result.m[12] = 0.0;
  5250. result.m[13] = 0.0;
  5251. result.m[14] = 0.0;
  5252. result._markAsUpdated();
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5256. */
  5257. Matrix.RotationAxis = function (axis, angle) {
  5258. var result = Matrix.Zero();
  5259. Matrix.RotationAxisToRef(axis, angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5264. */
  5265. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5266. var s = Math.sin(-angle);
  5267. var c = Math.cos(-angle);
  5268. var c1 = 1 - c;
  5269. axis.normalize();
  5270. result.m[0] = (axis.x * axis.x) * c1 + c;
  5271. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5272. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5273. result.m[3] = 0.0;
  5274. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5275. result.m[5] = (axis.y * axis.y) * c1 + c;
  5276. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5277. result.m[7] = 0.0;
  5278. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5279. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5280. result.m[10] = (axis.z * axis.z) * c1 + c;
  5281. result.m[11] = 0.0;
  5282. result.m[15] = 1.0;
  5283. result._markAsUpdated();
  5284. };
  5285. /**
  5286. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5287. */
  5288. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5289. var result = new Matrix();
  5290. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5291. return result;
  5292. };
  5293. /**
  5294. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5295. */
  5296. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5297. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5298. this._tempQuaternion.toRotationMatrix(result);
  5299. };
  5300. /**
  5301. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5302. */
  5303. Matrix.Scaling = function (x, y, z) {
  5304. var result = Matrix.Zero();
  5305. Matrix.ScalingToRef(x, y, z, result);
  5306. return result;
  5307. };
  5308. /**
  5309. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5310. */
  5311. Matrix.ScalingToRef = function (x, y, z, result) {
  5312. result.m[0] = x;
  5313. result.m[1] = 0.0;
  5314. result.m[2] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[5] = y;
  5318. result.m[6] = 0.0;
  5319. result.m[7] = 0.0;
  5320. result.m[8] = 0.0;
  5321. result.m[9] = 0.0;
  5322. result.m[10] = z;
  5323. result.m[11] = 0.0;
  5324. result.m[12] = 0.0;
  5325. result.m[13] = 0.0;
  5326. result.m[14] = 0.0;
  5327. result.m[15] = 1.0;
  5328. result._markAsUpdated();
  5329. };
  5330. /**
  5331. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5332. */
  5333. Matrix.Translation = function (x, y, z) {
  5334. var result = Matrix.Identity();
  5335. Matrix.TranslationToRef(x, y, z, result);
  5336. return result;
  5337. };
  5338. /**
  5339. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5340. */
  5341. Matrix.TranslationToRef = function (x, y, z, result) {
  5342. 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);
  5343. };
  5344. /**
  5345. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5346. */
  5347. Matrix.Lerp = function (startValue, endValue, gradient) {
  5348. var result = Matrix.Zero();
  5349. for (var index = 0; index < 16; index++) {
  5350. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5351. }
  5352. result._markAsUpdated();
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix whose values are computed by :
  5357. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5358. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5359. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5360. */
  5361. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5362. var startScale = new Vector3(0, 0, 0);
  5363. var startRotation = new Quaternion();
  5364. var startTranslation = new Vector3(0, 0, 0);
  5365. startValue.decompose(startScale, startRotation, startTranslation);
  5366. var endScale = new Vector3(0, 0, 0);
  5367. var endRotation = new Quaternion();
  5368. var endTranslation = new Vector3(0, 0, 0);
  5369. endValue.decompose(endScale, endRotation, endTranslation);
  5370. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5371. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5372. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5373. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5374. };
  5375. /**
  5376. * 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".
  5377. * This methods works for a Left-Handed system.
  5378. */
  5379. Matrix.LookAtLH = function (eye, target, up) {
  5380. var result = Matrix.Zero();
  5381. Matrix.LookAtLHToRef(eye, target, up, result);
  5382. return result;
  5383. };
  5384. /**
  5385. * 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".
  5386. * This methods works for a Left-Handed system.
  5387. */
  5388. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5389. // Z axis
  5390. target.subtractToRef(eye, this._zAxis);
  5391. this._zAxis.normalize();
  5392. // X axis
  5393. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5394. if (this._xAxis.lengthSquared() === 0) {
  5395. this._xAxis.x = 1.0;
  5396. }
  5397. else {
  5398. this._xAxis.normalize();
  5399. }
  5400. // Y axis
  5401. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5402. this._yAxis.normalize();
  5403. // Eye angles
  5404. var ex = -Vector3.Dot(this._xAxis, eye);
  5405. var ey = -Vector3.Dot(this._yAxis, eye);
  5406. var ez = -Vector3.Dot(this._zAxis, eye);
  5407. 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);
  5408. };
  5409. /**
  5410. * 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".
  5411. * This methods works for a Right-Handed system.
  5412. */
  5413. Matrix.LookAtRH = function (eye, target, up) {
  5414. var result = Matrix.Zero();
  5415. Matrix.LookAtRHToRef(eye, target, up, result);
  5416. return result;
  5417. };
  5418. /**
  5419. * 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".
  5420. * This methods works for a Left-Handed system.
  5421. */
  5422. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5423. // Z axis
  5424. eye.subtractToRef(target, this._zAxis);
  5425. this._zAxis.normalize();
  5426. // X axis
  5427. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5428. if (this._xAxis.lengthSquared() === 0) {
  5429. this._xAxis.x = 1.0;
  5430. }
  5431. else {
  5432. this._xAxis.normalize();
  5433. }
  5434. // Y axis
  5435. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5436. this._yAxis.normalize();
  5437. // Eye angles
  5438. var ex = -Vector3.Dot(this._xAxis, eye);
  5439. var ey = -Vector3.Dot(this._yAxis, eye);
  5440. var ez = -Vector3.Dot(this._zAxis, eye);
  5441. 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);
  5442. };
  5443. /**
  5444. * 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.
  5445. */
  5446. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5447. var matrix = Matrix.Zero();
  5448. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5449. return matrix;
  5450. };
  5451. /**
  5452. * 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.
  5453. */
  5454. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5455. var n = znear;
  5456. var f = zfar;
  5457. var a = 2.0 / width;
  5458. var b = 2.0 / height;
  5459. var c = 2.0 / (f - n);
  5460. var d = -(f + n) / (f - n);
  5461. 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);
  5462. };
  5463. /**
  5464. * 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.
  5465. */
  5466. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5467. var matrix = Matrix.Zero();
  5468. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5469. return matrix;
  5470. };
  5471. /**
  5472. * 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.
  5473. */
  5474. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5475. var n = znear;
  5476. var f = zfar;
  5477. var a = 2.0 / (right - left);
  5478. var b = 2.0 / (top - bottom);
  5479. var c = 2.0 / (f - n);
  5480. var d = -(f + n) / (f - n);
  5481. var i0 = (left + right) / (left - right);
  5482. var i1 = (top + bottom) / (bottom - top);
  5483. 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);
  5484. };
  5485. /**
  5486. * 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.
  5487. */
  5488. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5489. var matrix = Matrix.Zero();
  5490. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5491. return matrix;
  5492. };
  5493. /**
  5494. * 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.
  5495. */
  5496. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5497. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5498. result.m[10] *= -1.0;
  5499. };
  5500. /**
  5501. * 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.
  5502. */
  5503. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5504. var matrix = Matrix.Zero();
  5505. var n = znear;
  5506. var f = zfar;
  5507. var a = 2.0 * n / width;
  5508. var b = 2.0 * n / height;
  5509. var c = (f + n) / (f - n);
  5510. var d = -2.0 * f * n / (f - n);
  5511. 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);
  5512. return matrix;
  5513. };
  5514. /**
  5515. * 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.
  5516. */
  5517. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5518. var matrix = Matrix.Zero();
  5519. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5520. return matrix;
  5521. };
  5522. /**
  5523. * 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.
  5524. */
  5525. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5526. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5527. var n = znear;
  5528. var f = zfar;
  5529. var t = 1.0 / (Math.tan(fov * 0.5));
  5530. var a = isVerticalFovFixed ? (t / aspect) : t;
  5531. var b = isVerticalFovFixed ? t : (t * aspect);
  5532. var c = (f + n) / (f - n);
  5533. var d = -2.0 * f * n / (f - n);
  5534. 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);
  5535. };
  5536. /**
  5537. * 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.
  5538. */
  5539. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5542. return matrix;
  5543. };
  5544. /**
  5545. * 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.
  5546. */
  5547. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5548. //alternatively this could be expressed as:
  5549. // m = PerspectiveFovLHToRef
  5550. // m[10] *= -1.0;
  5551. // m[11] *= -1.0;
  5552. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5553. var n = znear;
  5554. var f = zfar;
  5555. var t = 1.0 / (Math.tan(fov * 0.5));
  5556. var a = isVerticalFovFixed ? (t / aspect) : t;
  5557. var b = isVerticalFovFixed ? t : (t * aspect);
  5558. var c = -(f + n) / (f - n);
  5559. var d = -2 * f * n / (f - n);
  5560. 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);
  5561. };
  5562. /**
  5563. * 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.
  5564. */
  5565. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5566. if (rightHanded === void 0) { rightHanded = false; }
  5567. var rightHandedFactor = rightHanded ? -1 : 1;
  5568. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5569. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5570. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5571. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5572. var xScale = 2.0 / (leftTan + rightTan);
  5573. var yScale = 2.0 / (upTan + downTan);
  5574. result.m[0] = xScale;
  5575. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5576. result.m[5] = yScale;
  5577. result.m[6] = result.m[7] = 0.0;
  5578. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5579. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5580. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5581. result.m[10] = -zfar / (znear - zfar);
  5582. result.m[11] = 1.0 * rightHandedFactor;
  5583. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5584. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5585. // result.m[14] = (znear * zfar) / (znear - zfar);
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Returns the final transformation matrix : world * view * projection * viewport
  5590. */
  5591. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5592. var cw = viewport.width;
  5593. var ch = viewport.height;
  5594. var cx = viewport.x;
  5595. var cy = viewport.y;
  5596. 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);
  5597. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5598. };
  5599. /**
  5600. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5601. */
  5602. Matrix.GetAsMatrix2x2 = function (matrix) {
  5603. return new Float32Array([
  5604. matrix.m[0], matrix.m[1],
  5605. matrix.m[4], matrix.m[5]
  5606. ]);
  5607. };
  5608. /**
  5609. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5610. */
  5611. Matrix.GetAsMatrix3x3 = function (matrix) {
  5612. return new Float32Array([
  5613. matrix.m[0], matrix.m[1], matrix.m[2],
  5614. matrix.m[4], matrix.m[5], matrix.m[6],
  5615. matrix.m[8], matrix.m[9], matrix.m[10]
  5616. ]);
  5617. };
  5618. /**
  5619. * Compute the transpose of the passed Matrix.
  5620. * Returns a new Matrix.
  5621. */
  5622. Matrix.Transpose = function (matrix) {
  5623. var result = new Matrix();
  5624. Matrix.TransposeToRef(matrix, result);
  5625. return result;
  5626. };
  5627. /**
  5628. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5629. */
  5630. Matrix.TransposeToRef = function (matrix, result) {
  5631. result.m[0] = matrix.m[0];
  5632. result.m[1] = matrix.m[4];
  5633. result.m[2] = matrix.m[8];
  5634. result.m[3] = matrix.m[12];
  5635. result.m[4] = matrix.m[1];
  5636. result.m[5] = matrix.m[5];
  5637. result.m[6] = matrix.m[9];
  5638. result.m[7] = matrix.m[13];
  5639. result.m[8] = matrix.m[2];
  5640. result.m[9] = matrix.m[6];
  5641. result.m[10] = matrix.m[10];
  5642. result.m[11] = matrix.m[14];
  5643. result.m[12] = matrix.m[3];
  5644. result.m[13] = matrix.m[7];
  5645. result.m[14] = matrix.m[11];
  5646. result.m[15] = matrix.m[15];
  5647. };
  5648. /**
  5649. * Returns a new Matrix as the reflection matrix across the passed plane.
  5650. */
  5651. Matrix.Reflection = function (plane) {
  5652. var matrix = new Matrix();
  5653. Matrix.ReflectionToRef(plane, matrix);
  5654. return matrix;
  5655. };
  5656. /**
  5657. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5658. */
  5659. Matrix.ReflectionToRef = function (plane, result) {
  5660. plane.normalize();
  5661. var x = plane.normal.x;
  5662. var y = plane.normal.y;
  5663. var z = plane.normal.z;
  5664. var temp = -2 * x;
  5665. var temp2 = -2 * y;
  5666. var temp3 = -2 * z;
  5667. result.m[0] = (temp * x) + 1;
  5668. result.m[1] = temp2 * x;
  5669. result.m[2] = temp3 * x;
  5670. result.m[3] = 0.0;
  5671. result.m[4] = temp * y;
  5672. result.m[5] = (temp2 * y) + 1;
  5673. result.m[6] = temp3 * y;
  5674. result.m[7] = 0.0;
  5675. result.m[8] = temp * z;
  5676. result.m[9] = temp2 * z;
  5677. result.m[10] = (temp3 * z) + 1;
  5678. result.m[11] = 0.0;
  5679. result.m[12] = temp * plane.d;
  5680. result.m[13] = temp2 * plane.d;
  5681. result.m[14] = temp3 * plane.d;
  5682. result.m[15] = 1.0;
  5683. result._markAsUpdated();
  5684. };
  5685. /**
  5686. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5687. */
  5688. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5689. result.m[0] = xaxis.x;
  5690. result.m[1] = xaxis.y;
  5691. result.m[2] = xaxis.z;
  5692. result.m[3] = 0.0;
  5693. result.m[4] = yaxis.x;
  5694. result.m[5] = yaxis.y;
  5695. result.m[6] = yaxis.z;
  5696. result.m[7] = 0.0;
  5697. result.m[8] = zaxis.x;
  5698. result.m[9] = zaxis.y;
  5699. result.m[10] = zaxis.z;
  5700. result.m[11] = 0.0;
  5701. result.m[12] = 0.0;
  5702. result.m[13] = 0.0;
  5703. result.m[14] = 0.0;
  5704. result.m[15] = 1.0;
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5709. */
  5710. Matrix.FromQuaternionToRef = function (quat, result) {
  5711. var xx = quat.x * quat.x;
  5712. var yy = quat.y * quat.y;
  5713. var zz = quat.z * quat.z;
  5714. var xy = quat.x * quat.y;
  5715. var zw = quat.z * quat.w;
  5716. var zx = quat.z * quat.x;
  5717. var yw = quat.y * quat.w;
  5718. var yz = quat.y * quat.z;
  5719. var xw = quat.x * quat.w;
  5720. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5721. result.m[1] = 2.0 * (xy + zw);
  5722. result.m[2] = 2.0 * (zx - yw);
  5723. result.m[3] = 0.0;
  5724. result.m[4] = 2.0 * (xy - zw);
  5725. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5726. result.m[6] = 2.0 * (yz + xw);
  5727. result.m[7] = 0.0;
  5728. result.m[8] = 2.0 * (zx + yw);
  5729. result.m[9] = 2.0 * (yz - xw);
  5730. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5731. result.m[11] = 0.0;
  5732. result.m[12] = 0.0;
  5733. result.m[13] = 0.0;
  5734. result.m[14] = 0.0;
  5735. result.m[15] = 1.0;
  5736. result._markAsUpdated();
  5737. };
  5738. Matrix._tempQuaternion = new Quaternion();
  5739. Matrix._xAxis = Vector3.Zero();
  5740. Matrix._yAxis = Vector3.Zero();
  5741. Matrix._zAxis = Vector3.Zero();
  5742. Matrix._updateFlagSeed = 0;
  5743. Matrix._identityReadOnly = Matrix.Identity();
  5744. return Matrix;
  5745. }());
  5746. BABYLON.Matrix = Matrix;
  5747. var Plane = /** @class */ (function () {
  5748. /**
  5749. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5750. */
  5751. function Plane(a, b, c, d) {
  5752. this.normal = new Vector3(a, b, c);
  5753. this.d = d;
  5754. }
  5755. /**
  5756. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5757. */
  5758. Plane.prototype.asArray = function () {
  5759. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5760. };
  5761. // Methods
  5762. /**
  5763. * Returns a new plane copied from the current Plane.
  5764. */
  5765. Plane.prototype.clone = function () {
  5766. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5767. };
  5768. /**
  5769. * Returns the string "Plane".
  5770. */
  5771. Plane.prototype.getClassName = function () {
  5772. return "Plane";
  5773. };
  5774. /**
  5775. * Returns the Plane hash code.
  5776. */
  5777. Plane.prototype.getHashCode = function () {
  5778. var hash = this.normal.getHashCode();
  5779. hash = (hash * 397) ^ (this.d || 0);
  5780. return hash;
  5781. };
  5782. /**
  5783. * Normalize the current Plane in place.
  5784. * Returns the updated Plane.
  5785. */
  5786. Plane.prototype.normalize = function () {
  5787. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5788. var magnitude = 0.0;
  5789. if (norm !== 0) {
  5790. magnitude = 1.0 / norm;
  5791. }
  5792. this.normal.x *= magnitude;
  5793. this.normal.y *= magnitude;
  5794. this.normal.z *= magnitude;
  5795. this.d *= magnitude;
  5796. return this;
  5797. };
  5798. /**
  5799. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5800. */
  5801. Plane.prototype.transform = function (transformation) {
  5802. var transposedMatrix = Matrix.Transpose(transformation);
  5803. var x = this.normal.x;
  5804. var y = this.normal.y;
  5805. var z = this.normal.z;
  5806. var d = this.d;
  5807. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5808. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5809. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5810. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5811. return new Plane(normalX, normalY, normalZ, finalD);
  5812. };
  5813. /**
  5814. * Returns the dot product (float) of the point coordinates and the plane normal.
  5815. */
  5816. Plane.prototype.dotCoordinate = function (point) {
  5817. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5818. };
  5819. /**
  5820. * Updates the current Plane from the plane defined by the three passed points.
  5821. * Returns the updated Plane.
  5822. */
  5823. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5824. var x1 = point2.x - point1.x;
  5825. var y1 = point2.y - point1.y;
  5826. var z1 = point2.z - point1.z;
  5827. var x2 = point3.x - point1.x;
  5828. var y2 = point3.y - point1.y;
  5829. var z2 = point3.z - point1.z;
  5830. var yz = (y1 * z2) - (z1 * y2);
  5831. var xz = (z1 * x2) - (x1 * z2);
  5832. var xy = (x1 * y2) - (y1 * x2);
  5833. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5834. var invPyth;
  5835. if (pyth !== 0) {
  5836. invPyth = 1.0 / pyth;
  5837. }
  5838. else {
  5839. invPyth = 0.0;
  5840. }
  5841. this.normal.x = yz * invPyth;
  5842. this.normal.y = xz * invPyth;
  5843. this.normal.z = xy * invPyth;
  5844. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5845. return this;
  5846. };
  5847. /**
  5848. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5849. */
  5850. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5851. var dot = Vector3.Dot(this.normal, direction);
  5852. return (dot <= epsilon);
  5853. };
  5854. /**
  5855. * Returns the signed distance (float) from the passed point to the Plane.
  5856. */
  5857. Plane.prototype.signedDistanceTo = function (point) {
  5858. return Vector3.Dot(point, this.normal) + this.d;
  5859. };
  5860. // Statics
  5861. /**
  5862. * Returns a new Plane from the passed array.
  5863. */
  5864. Plane.FromArray = function (array) {
  5865. return new Plane(array[0], array[1], array[2], array[3]);
  5866. };
  5867. /**
  5868. * Returns a new Plane defined by the three passed points.
  5869. */
  5870. Plane.FromPoints = function (point1, point2, point3) {
  5871. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5872. result.copyFromPoints(point1, point2, point3);
  5873. return result;
  5874. };
  5875. /**
  5876. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5877. * Note : the vector "normal" is updated because normalized.
  5878. */
  5879. Plane.FromPositionAndNormal = function (origin, normal) {
  5880. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5881. normal.normalize();
  5882. result.normal = normal;
  5883. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5884. return result;
  5885. };
  5886. /**
  5887. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5888. */
  5889. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5890. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5891. return Vector3.Dot(point, normal) + d;
  5892. };
  5893. return Plane;
  5894. }());
  5895. BABYLON.Plane = Plane;
  5896. var Viewport = /** @class */ (function () {
  5897. /**
  5898. * Creates a Viewport object located at (x, y) and sized (width, height).
  5899. */
  5900. function Viewport(x, y, width, height) {
  5901. this.x = x;
  5902. this.y = y;
  5903. this.width = width;
  5904. this.height = height;
  5905. }
  5906. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5907. if (renderWidthOrEngine.getRenderWidth) {
  5908. var engine = renderWidthOrEngine;
  5909. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5910. }
  5911. var renderWidth = renderWidthOrEngine;
  5912. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5913. };
  5914. /**
  5915. * Returns a new Viewport copied from the current one.
  5916. */
  5917. Viewport.prototype.clone = function () {
  5918. return new Viewport(this.x, this.y, this.width, this.height);
  5919. };
  5920. return Viewport;
  5921. }());
  5922. BABYLON.Viewport = Viewport;
  5923. var Frustum = /** @class */ (function () {
  5924. function Frustum() {
  5925. }
  5926. /**
  5927. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5928. */
  5929. Frustum.GetPlanes = function (transform) {
  5930. var frustumPlanes = [];
  5931. for (var index = 0; index < 6; index++) {
  5932. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5933. }
  5934. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5935. return frustumPlanes;
  5936. };
  5937. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5938. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5939. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5940. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5941. frustumPlane.d = transform.m[15] + transform.m[14];
  5942. frustumPlane.normalize();
  5943. };
  5944. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5945. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5946. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5947. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5948. frustumPlane.d = transform.m[15] - transform.m[14];
  5949. frustumPlane.normalize();
  5950. };
  5951. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5952. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5953. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5954. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5955. frustumPlane.d = transform.m[15] + transform.m[12];
  5956. frustumPlane.normalize();
  5957. };
  5958. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5959. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5960. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5961. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5962. frustumPlane.d = transform.m[15] - transform.m[12];
  5963. frustumPlane.normalize();
  5964. };
  5965. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5966. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5967. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5968. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5969. frustumPlane.d = transform.m[15] - transform.m[13];
  5970. frustumPlane.normalize();
  5971. };
  5972. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5973. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5974. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5975. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5976. frustumPlane.d = transform.m[15] + transform.m[13];
  5977. frustumPlane.normalize();
  5978. };
  5979. /**
  5980. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5981. */
  5982. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5983. // Near
  5984. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5985. // Far
  5986. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5987. // Left
  5988. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5989. // Right
  5990. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5991. // Top
  5992. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5993. // Bottom
  5994. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5995. };
  5996. return Frustum;
  5997. }());
  5998. BABYLON.Frustum = Frustum;
  5999. var Space;
  6000. (function (Space) {
  6001. Space[Space["LOCAL"] = 0] = "LOCAL";
  6002. Space[Space["WORLD"] = 1] = "WORLD";
  6003. Space[Space["BONE"] = 2] = "BONE";
  6004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6005. var Axis = /** @class */ (function () {
  6006. function Axis() {
  6007. }
  6008. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6009. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6010. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6011. return Axis;
  6012. }());
  6013. BABYLON.Axis = Axis;
  6014. ;
  6015. var BezierCurve = /** @class */ (function () {
  6016. function BezierCurve() {
  6017. }
  6018. /**
  6019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6020. */
  6021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6022. // Extract X (which is equal to time here)
  6023. var f0 = 1 - 3 * x2 + 3 * x1;
  6024. var f1 = 3 * x2 - 6 * x1;
  6025. var f2 = 3 * x1;
  6026. var refinedT = t;
  6027. for (var i = 0; i < 5; i++) {
  6028. var refinedT2 = refinedT * refinedT;
  6029. var refinedT3 = refinedT2 * refinedT;
  6030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6032. refinedT -= (x - t) * slope;
  6033. refinedT = Math.min(1, Math.max(0, refinedT));
  6034. }
  6035. // Resolve cubic bezier for the given x
  6036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6038. Math.pow(refinedT, 3);
  6039. };
  6040. return BezierCurve;
  6041. }());
  6042. BABYLON.BezierCurve = BezierCurve;
  6043. var Orientation;
  6044. (function (Orientation) {
  6045. Orientation[Orientation["CW"] = 0] = "CW";
  6046. Orientation[Orientation["CCW"] = 1] = "CCW";
  6047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6048. var Angle = /** @class */ (function () {
  6049. /**
  6050. * Creates an Angle object of "radians" radians (float).
  6051. */
  6052. function Angle(radians) {
  6053. var _this = this;
  6054. /**
  6055. * Returns the Angle value in degrees (float).
  6056. */
  6057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6058. /**
  6059. * Returns the Angle value in radians (float).
  6060. */
  6061. this.radians = function () { return _this._radians; };
  6062. this._radians = radians;
  6063. if (this._radians < 0.0)
  6064. this._radians += (2.0 * Math.PI);
  6065. }
  6066. /**
  6067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6068. */
  6069. Angle.BetweenTwoPoints = function (a, b) {
  6070. var delta = b.subtract(a);
  6071. var theta = Math.atan2(delta.y, delta.x);
  6072. return new Angle(theta);
  6073. };
  6074. /**
  6075. * Returns a new Angle object from the passed float in radians.
  6076. */
  6077. Angle.FromRadians = function (radians) {
  6078. return new Angle(radians);
  6079. };
  6080. /**
  6081. * Returns a new Angle object from the passed float in degrees.
  6082. */
  6083. Angle.FromDegrees = function (degrees) {
  6084. return new Angle(degrees * Math.PI / 180.0);
  6085. };
  6086. return Angle;
  6087. }());
  6088. BABYLON.Angle = Angle;
  6089. var Arc2 = /** @class */ (function () {
  6090. /**
  6091. * Creates an Arc object from the three passed points : start, middle and end.
  6092. */
  6093. function Arc2(startPoint, midPoint, endPoint) {
  6094. this.startPoint = startPoint;
  6095. this.midPoint = midPoint;
  6096. this.endPoint = endPoint;
  6097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6101. 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);
  6102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6104. var a1 = this.startAngle.degrees();
  6105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6107. // angles correction
  6108. if (a2 - a1 > +180.0)
  6109. a2 -= 360.0;
  6110. if (a2 - a1 < -180.0)
  6111. a2 += 360.0;
  6112. if (a3 - a2 > +180.0)
  6113. a3 -= 360.0;
  6114. if (a3 - a2 < -180.0)
  6115. a3 += 360.0;
  6116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6118. }
  6119. return Arc2;
  6120. }());
  6121. BABYLON.Arc2 = Arc2;
  6122. var Path2 = /** @class */ (function () {
  6123. /**
  6124. * Creates a Path2 object from the starting 2D coordinates x and y.
  6125. */
  6126. function Path2(x, y) {
  6127. this._points = new Array();
  6128. this._length = 0.0;
  6129. this.closed = false;
  6130. this._points.push(new Vector2(x, y));
  6131. }
  6132. /**
  6133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6134. * Returns the updated Path2.
  6135. */
  6136. Path2.prototype.addLineTo = function (x, y) {
  6137. if (this.closed) {
  6138. //Tools.Error("cannot add lines to closed paths");
  6139. return this;
  6140. }
  6141. var newPoint = new Vector2(x, y);
  6142. var previousPoint = this._points[this._points.length - 1];
  6143. this._points.push(newPoint);
  6144. this._length += newPoint.subtract(previousPoint).length();
  6145. return this;
  6146. };
  6147. /**
  6148. * 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.
  6149. * Returns the updated Path2.
  6150. */
  6151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6153. if (this.closed) {
  6154. //Tools.Error("cannot add arcs to closed paths");
  6155. return this;
  6156. }
  6157. var startPoint = this._points[this._points.length - 1];
  6158. var midPoint = new Vector2(midX, midY);
  6159. var endPoint = new Vector2(endX, endY);
  6160. var arc = new Arc2(startPoint, midPoint, endPoint);
  6161. var increment = arc.angle.radians() / numberOfSegments;
  6162. if (arc.orientation === Orientation.CW)
  6163. increment *= -1;
  6164. var currentAngle = arc.startAngle.radians() + increment;
  6165. for (var i = 0; i < numberOfSegments; i++) {
  6166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6168. this.addLineTo(x, y);
  6169. currentAngle += increment;
  6170. }
  6171. return this;
  6172. };
  6173. /**
  6174. * Closes the Path2.
  6175. * Returns the Path2.
  6176. */
  6177. Path2.prototype.close = function () {
  6178. this.closed = true;
  6179. return this;
  6180. };
  6181. /**
  6182. * Returns the Path2 total length (float).
  6183. */
  6184. Path2.prototype.length = function () {
  6185. var result = this._length;
  6186. if (!this.closed) {
  6187. var lastPoint = this._points[this._points.length - 1];
  6188. var firstPoint = this._points[0];
  6189. result += (firstPoint.subtract(lastPoint).length());
  6190. }
  6191. return result;
  6192. };
  6193. /**
  6194. * Returns the Path2 internal array of points.
  6195. */
  6196. Path2.prototype.getPoints = function () {
  6197. return this._points;
  6198. };
  6199. /**
  6200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6201. */
  6202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6204. //Tools.Error("normalized length position should be between 0 and 1.");
  6205. return Vector2.Zero();
  6206. }
  6207. var lengthPosition = normalizedLengthPosition * this.length();
  6208. var previousOffset = 0;
  6209. for (var i = 0; i < this._points.length; i++) {
  6210. var j = (i + 1) % this._points.length;
  6211. var a = this._points[i];
  6212. var b = this._points[j];
  6213. var bToA = b.subtract(a);
  6214. var nextOffset = (bToA.length() + previousOffset);
  6215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6216. var dir = bToA.normalize();
  6217. var localOffset = lengthPosition - previousOffset;
  6218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6219. }
  6220. previousOffset = nextOffset;
  6221. }
  6222. //Tools.Error("internal error");
  6223. return Vector2.Zero();
  6224. };
  6225. /**
  6226. * Returns a new Path2 starting at the coordinates (x, y).
  6227. */
  6228. Path2.StartingAt = function (x, y) {
  6229. return new Path2(x, y);
  6230. };
  6231. return Path2;
  6232. }());
  6233. BABYLON.Path2 = Path2;
  6234. var Path3D = /** @class */ (function () {
  6235. /**
  6236. * new Path3D(path, normal, raw)
  6237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6239. * path : an array of Vector3, the curve axis of the Path3D
  6240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6242. */
  6243. function Path3D(path, firstNormal, raw) {
  6244. if (firstNormal === void 0) { firstNormal = null; }
  6245. this.path = path;
  6246. this._curve = new Array();
  6247. this._distances = new Array();
  6248. this._tangents = new Array();
  6249. this._normals = new Array();
  6250. this._binormals = new Array();
  6251. for (var p = 0; p < path.length; p++) {
  6252. this._curve[p] = path[p].clone(); // hard copy
  6253. }
  6254. this._raw = raw || false;
  6255. this._compute(firstNormal);
  6256. }
  6257. /**
  6258. * Returns the Path3D array of successive Vector3 designing its curve.
  6259. */
  6260. Path3D.prototype.getCurve = function () {
  6261. return this._curve;
  6262. };
  6263. /**
  6264. * Returns an array populated with tangent vectors on each Path3D curve point.
  6265. */
  6266. Path3D.prototype.getTangents = function () {
  6267. return this._tangents;
  6268. };
  6269. /**
  6270. * Returns an array populated with normal vectors on each Path3D curve point.
  6271. */
  6272. Path3D.prototype.getNormals = function () {
  6273. return this._normals;
  6274. };
  6275. /**
  6276. * Returns an array populated with binormal vectors on each Path3D curve point.
  6277. */
  6278. Path3D.prototype.getBinormals = function () {
  6279. return this._binormals;
  6280. };
  6281. /**
  6282. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6283. */
  6284. Path3D.prototype.getDistances = function () {
  6285. return this._distances;
  6286. };
  6287. /**
  6288. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6289. * Returns the same object updated.
  6290. */
  6291. Path3D.prototype.update = function (path, firstNormal) {
  6292. if (firstNormal === void 0) { firstNormal = null; }
  6293. for (var p = 0; p < path.length; p++) {
  6294. this._curve[p].x = path[p].x;
  6295. this._curve[p].y = path[p].y;
  6296. this._curve[p].z = path[p].z;
  6297. }
  6298. this._compute(firstNormal);
  6299. return this;
  6300. };
  6301. // private function compute() : computes tangents, normals and binormals
  6302. Path3D.prototype._compute = function (firstNormal) {
  6303. var l = this._curve.length;
  6304. // first and last tangents
  6305. this._tangents[0] = this._getFirstNonNullVector(0);
  6306. if (!this._raw) {
  6307. this._tangents[0].normalize();
  6308. }
  6309. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6310. if (!this._raw) {
  6311. this._tangents[l - 1].normalize();
  6312. }
  6313. // normals and binormals at first point : arbitrary vector with _normalVector()
  6314. var tg0 = this._tangents[0];
  6315. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6316. this._normals[0] = pp0;
  6317. if (!this._raw) {
  6318. this._normals[0].normalize();
  6319. }
  6320. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6321. if (!this._raw) {
  6322. this._binormals[0].normalize();
  6323. }
  6324. this._distances[0] = 0.0;
  6325. // normals and binormals : next points
  6326. var prev; // previous vector (segment)
  6327. var cur; // current vector (segment)
  6328. var curTang; // current tangent
  6329. // previous normal
  6330. var prevBinor; // previous binormal
  6331. for (var i = 1; i < l; i++) {
  6332. // tangents
  6333. prev = this._getLastNonNullVector(i);
  6334. if (i < l - 1) {
  6335. cur = this._getFirstNonNullVector(i);
  6336. this._tangents[i] = prev.add(cur);
  6337. this._tangents[i].normalize();
  6338. }
  6339. this._distances[i] = this._distances[i - 1] + prev.length();
  6340. // normals and binormals
  6341. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6342. curTang = this._tangents[i];
  6343. prevBinor = this._binormals[i - 1];
  6344. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6345. if (!this._raw) {
  6346. this._normals[i].normalize();
  6347. }
  6348. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6349. if (!this._raw) {
  6350. this._binormals[i].normalize();
  6351. }
  6352. }
  6353. };
  6354. // private function getFirstNonNullVector(index)
  6355. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6356. Path3D.prototype._getFirstNonNullVector = function (index) {
  6357. var i = 1;
  6358. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6359. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6360. i++;
  6361. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6362. }
  6363. return nNVector;
  6364. };
  6365. // private function getLastNonNullVector(index)
  6366. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6367. Path3D.prototype._getLastNonNullVector = function (index) {
  6368. var i = 1;
  6369. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6370. while (nLVector.length() === 0 && index > i + 1) {
  6371. i++;
  6372. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6373. }
  6374. return nLVector;
  6375. };
  6376. // private function normalVector(v0, vt, va) :
  6377. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6378. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6379. Path3D.prototype._normalVector = function (v0, vt, va) {
  6380. var normal0;
  6381. var tgl = vt.length();
  6382. if (tgl === 0.0) {
  6383. tgl = 1.0;
  6384. }
  6385. if (va === undefined || va === null) {
  6386. var point;
  6387. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6388. point = new Vector3(0.0, -1.0, 0.0);
  6389. }
  6390. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6391. point = new Vector3(1.0, 0.0, 0.0);
  6392. }
  6393. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6394. point = new Vector3(0.0, 0.0, 1.0);
  6395. }
  6396. else {
  6397. point = Vector3.Zero();
  6398. }
  6399. normal0 = Vector3.Cross(vt, point);
  6400. }
  6401. else {
  6402. normal0 = Vector3.Cross(vt, va);
  6403. Vector3.CrossToRef(normal0, vt, normal0);
  6404. }
  6405. normal0.normalize();
  6406. return normal0;
  6407. };
  6408. return Path3D;
  6409. }());
  6410. BABYLON.Path3D = Path3D;
  6411. var Curve3 = /** @class */ (function () {
  6412. /**
  6413. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6414. * A Curve3 is designed from a series of successive Vector3.
  6415. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6416. */
  6417. function Curve3(points) {
  6418. this._length = 0.0;
  6419. this._points = points;
  6420. this._length = this._computeLength(points);
  6421. }
  6422. /**
  6423. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6424. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6425. * @param v1 (Vector3) the control point
  6426. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6427. * @param nbPoints (integer) the wanted number of points in the curve
  6428. */
  6429. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6430. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6431. var bez = new Array();
  6432. var equation = function (t, val0, val1, val2) {
  6433. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6434. return res;
  6435. };
  6436. for (var i = 0; i <= nbPoints; i++) {
  6437. 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)));
  6438. }
  6439. return new Curve3(bez);
  6440. };
  6441. /**
  6442. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6443. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6444. * @param v1 (Vector3) the first control point
  6445. * @param v2 (Vector3) the second control point
  6446. * @param v3 (Vector3) the end point of the Cubic Bezier
  6447. * @param nbPoints (integer) the wanted number of points in the curve
  6448. */
  6449. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6450. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6451. var bez = new Array();
  6452. var equation = function (t, val0, val1, val2, val3) {
  6453. 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;
  6454. return res;
  6455. };
  6456. for (var i = 0; i <= nbPoints; i++) {
  6457. 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)));
  6458. }
  6459. return new Curve3(bez);
  6460. };
  6461. /**
  6462. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6463. * @param p1 (Vector3) the origin point of the Hermite Spline
  6464. * @param t1 (Vector3) the tangent vector at the origin point
  6465. * @param p2 (Vector3) the end point of the Hermite Spline
  6466. * @param t2 (Vector3) the tangent vector at the end point
  6467. * @param nbPoints (integer) the wanted number of points in the curve
  6468. */
  6469. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6470. var hermite = new Array();
  6471. var step = 1.0 / nbPoints;
  6472. for (var i = 0; i <= nbPoints; i++) {
  6473. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6474. }
  6475. return new Curve3(hermite);
  6476. };
  6477. /**
  6478. * Returns a Curve3 object along a CatmullRom Spline curve :
  6479. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6480. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6481. */
  6482. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6483. var totalPoints = new Array();
  6484. totalPoints.push(points[0].clone());
  6485. Array.prototype.push.apply(totalPoints, points);
  6486. totalPoints.push(points[points.length - 1].clone());
  6487. var catmullRom = new Array();
  6488. var step = 1.0 / nbPoints;
  6489. var amount = 0.0;
  6490. for (var i = 0; i < totalPoints.length - 3; i++) {
  6491. amount = 0;
  6492. for (var c = 0; c < nbPoints; c++) {
  6493. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6494. amount += step;
  6495. }
  6496. }
  6497. i--;
  6498. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6499. return new Curve3(catmullRom);
  6500. };
  6501. /**
  6502. * Returns the Curve3 stored array of successive Vector3
  6503. */
  6504. Curve3.prototype.getPoints = function () {
  6505. return this._points;
  6506. };
  6507. /**
  6508. * Returns the computed length (float) of the curve.
  6509. */
  6510. Curve3.prototype.length = function () {
  6511. return this._length;
  6512. };
  6513. /**
  6514. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6515. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6516. * curveA and curveB keep unchanged.
  6517. */
  6518. Curve3.prototype.continue = function (curve) {
  6519. var lastPoint = this._points[this._points.length - 1];
  6520. var continuedPoints = this._points.slice();
  6521. var curvePoints = curve.getPoints();
  6522. for (var i = 1; i < curvePoints.length; i++) {
  6523. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6524. }
  6525. var continuedCurve = new Curve3(continuedPoints);
  6526. return continuedCurve;
  6527. };
  6528. Curve3.prototype._computeLength = function (path) {
  6529. var l = 0;
  6530. for (var i = 1; i < path.length; i++) {
  6531. l += (path[i].subtract(path[i - 1])).length();
  6532. }
  6533. return l;
  6534. };
  6535. return Curve3;
  6536. }());
  6537. BABYLON.Curve3 = Curve3;
  6538. // Vertex formats
  6539. var PositionNormalVertex = /** @class */ (function () {
  6540. function PositionNormalVertex(position, normal) {
  6541. if (position === void 0) { position = Vector3.Zero(); }
  6542. if (normal === void 0) { normal = Vector3.Up(); }
  6543. this.position = position;
  6544. this.normal = normal;
  6545. }
  6546. PositionNormalVertex.prototype.clone = function () {
  6547. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6548. };
  6549. return PositionNormalVertex;
  6550. }());
  6551. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6552. var PositionNormalTextureVertex = /** @class */ (function () {
  6553. function PositionNormalTextureVertex(position, normal, uv) {
  6554. if (position === void 0) { position = Vector3.Zero(); }
  6555. if (normal === void 0) { normal = Vector3.Up(); }
  6556. if (uv === void 0) { uv = Vector2.Zero(); }
  6557. this.position = position;
  6558. this.normal = normal;
  6559. this.uv = uv;
  6560. }
  6561. PositionNormalTextureVertex.prototype.clone = function () {
  6562. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6563. };
  6564. return PositionNormalTextureVertex;
  6565. }());
  6566. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6567. // Temporary pre-allocated objects for engine internal use
  6568. // usage in any internal function :
  6569. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6570. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6571. var Tmp = /** @class */ (function () {
  6572. function Tmp() {
  6573. }
  6574. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6575. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6576. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6577. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6578. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6579. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6580. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6581. Matrix.Zero(), Matrix.Zero(),
  6582. Matrix.Zero(), Matrix.Zero(),
  6583. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6584. return Tmp;
  6585. }());
  6586. BABYLON.Tmp = Tmp;
  6587. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6588. var MathTmp = /** @class */ (function () {
  6589. function MathTmp() {
  6590. }
  6591. MathTmp.Vector3 = [Vector3.Zero()];
  6592. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6593. MathTmp.Quaternion = [Quaternion.Zero()];
  6594. return MathTmp;
  6595. }());
  6596. })(BABYLON || (BABYLON = {}));
  6597. //# sourceMappingURL=babylon.math.js.map
  6598. var BABYLON;
  6599. (function (BABYLON) {
  6600. var Scalar = /** @class */ (function () {
  6601. function Scalar() {
  6602. }
  6603. /**
  6604. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6605. */
  6606. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6607. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6608. var num = a - b;
  6609. return -epsilon <= num && num <= epsilon;
  6610. };
  6611. /**
  6612. * Returns a string : the upper case translation of the number i to hexadecimal.
  6613. */
  6614. Scalar.ToHex = function (i) {
  6615. var str = i.toString(16);
  6616. if (i <= 15) {
  6617. return ("0" + str).toUpperCase();
  6618. }
  6619. return str.toUpperCase();
  6620. };
  6621. /**
  6622. * Returns -1 if value is negative and +1 is value is positive.
  6623. * Returns the value itself if it's equal to zero.
  6624. */
  6625. Scalar.Sign = function (value) {
  6626. value = +value; // convert to a number
  6627. if (value === 0 || isNaN(value))
  6628. return value;
  6629. return value > 0 ? 1 : -1;
  6630. };
  6631. /**
  6632. * Returns the value itself if it's between min and max.
  6633. * Returns min if the value is lower than min.
  6634. * Returns max if the value is greater than max.
  6635. */
  6636. Scalar.Clamp = function (value, min, max) {
  6637. if (min === void 0) { min = 0; }
  6638. if (max === void 0) { max = 1; }
  6639. return Math.min(max, Math.max(min, value));
  6640. };
  6641. /**
  6642. * Returns the log2 of value.
  6643. */
  6644. Scalar.Log2 = function (value) {
  6645. return Math.log(value) * Math.LOG2E;
  6646. };
  6647. /**
  6648. * Loops the value, so that it is never larger than length and never smaller than 0.
  6649. *
  6650. * This is similar to the modulo operator but it works with floating point numbers.
  6651. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6652. * With t = 5 and length = 2.5, the result would be 0.0.
  6653. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6654. */
  6655. Scalar.Repeat = function (value, length) {
  6656. return value - Math.floor(value / length) * length;
  6657. };
  6658. /**
  6659. * Normalize the value between 0.0 and 1.0 using min and max values
  6660. */
  6661. Scalar.Normalize = function (value, min, max) {
  6662. return (value - min) / (max - min);
  6663. };
  6664. /**
  6665. * Denormalize the value from 0.0 and 1.0 using min and max values
  6666. */
  6667. Scalar.Denormalize = function (normalized, min, max) {
  6668. return (normalized * (max - min) + min);
  6669. };
  6670. /**
  6671. * Calculates the shortest difference between two given angles given in degrees.
  6672. */
  6673. Scalar.DeltaAngle = function (current, target) {
  6674. var num = Scalar.Repeat(target - current, 360.0);
  6675. if (num > 180.0) {
  6676. num -= 360.0;
  6677. }
  6678. return num;
  6679. };
  6680. /**
  6681. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6682. *
  6683. * The returned value will move back and forth between 0 and length
  6684. */
  6685. Scalar.PingPong = function (tx, length) {
  6686. var t = Scalar.Repeat(tx, length * 2.0);
  6687. return length - Math.abs(t - length);
  6688. };
  6689. /**
  6690. * Interpolates between min and max with smoothing at the limits.
  6691. *
  6692. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6693. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6694. */
  6695. Scalar.SmoothStep = function (from, to, tx) {
  6696. var t = Scalar.Clamp(tx);
  6697. t = -2.0 * t * t * t + 3.0 * t * t;
  6698. return to * t + from * (1.0 - t);
  6699. };
  6700. /**
  6701. * Moves a value current towards target.
  6702. *
  6703. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6704. * Negative values of maxDelta pushes the value away from target.
  6705. */
  6706. Scalar.MoveTowards = function (current, target, maxDelta) {
  6707. var result = 0;
  6708. if (Math.abs(target - current) <= maxDelta) {
  6709. result = target;
  6710. }
  6711. else {
  6712. result = current + Scalar.Sign(target - current) * maxDelta;
  6713. }
  6714. return result;
  6715. };
  6716. /**
  6717. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6718. *
  6719. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6720. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6721. */
  6722. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6723. var num = Scalar.DeltaAngle(current, target);
  6724. var result = 0;
  6725. if (-maxDelta < num && num < maxDelta) {
  6726. result = target;
  6727. }
  6728. else {
  6729. target = current + num;
  6730. result = Scalar.MoveTowards(current, target, maxDelta);
  6731. }
  6732. return result;
  6733. };
  6734. /**
  6735. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6736. */
  6737. Scalar.Lerp = function (start, end, amount) {
  6738. return start + ((end - start) * amount);
  6739. };
  6740. /**
  6741. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6742. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6743. */
  6744. Scalar.LerpAngle = function (start, end, amount) {
  6745. var num = Scalar.Repeat(end - start, 360.0);
  6746. if (num > 180.0) {
  6747. num -= 360.0;
  6748. }
  6749. return start + num * Scalar.Clamp(amount);
  6750. };
  6751. /**
  6752. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6753. */
  6754. Scalar.InverseLerp = function (a, b, value) {
  6755. var result = 0;
  6756. if (a != b) {
  6757. result = Scalar.Clamp((value - a) / (b - a));
  6758. }
  6759. else {
  6760. result = 0.0;
  6761. }
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6766. */
  6767. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6768. var squared = amount * amount;
  6769. var cubed = amount * squared;
  6770. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6771. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6772. var part3 = (cubed - (2.0 * squared)) + amount;
  6773. var part4 = cubed - squared;
  6774. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6775. };
  6776. /**
  6777. * Returns a random float number between and min and max values
  6778. */
  6779. Scalar.RandomRange = function (min, max) {
  6780. if (min === max)
  6781. return min;
  6782. return ((Math.random() * (max - min)) + min);
  6783. };
  6784. /**
  6785. * This function returns percentage of a number in a given range.
  6786. *
  6787. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6788. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6789. */
  6790. Scalar.RangeToPercent = function (number, min, max) {
  6791. return ((number - min) / (max - min));
  6792. };
  6793. /**
  6794. * This function returns number that corresponds to the percentage in a given range.
  6795. *
  6796. * PercentToRange(0.34,0,100) will return 34.
  6797. */
  6798. Scalar.PercentToRange = function (percent, min, max) {
  6799. return ((max - min) * percent + min);
  6800. };
  6801. /**
  6802. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6803. * @param angle The angle to normalize in radian.
  6804. * @return The converted angle.
  6805. */
  6806. Scalar.NormalizeRadians = function (angle) {
  6807. // More precise but slower version kept for reference.
  6808. // angle = angle % Tools.TwoPi;
  6809. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6810. //if (angle > Math.PI) {
  6811. // angle -= Tools.TwoPi;
  6812. //}
  6813. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6814. return angle;
  6815. };
  6816. /**
  6817. * Two pi constants convenient for computation.
  6818. */
  6819. Scalar.TwoPi = Math.PI * 2;
  6820. return Scalar;
  6821. }());
  6822. BABYLON.Scalar = Scalar;
  6823. })(BABYLON || (BABYLON = {}));
  6824. //# sourceMappingURL=babylon.math.scalar.js.map
  6825. //# sourceMappingURL=babylon.mixins.js.map
  6826. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6827. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6828. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6829. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6830. //# sourceMappingURL=babylon.webgl2.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var __decoratorInitialStore = {};
  6834. var __mergedStore = {};
  6835. var _copySource = function (creationFunction, source, instanciate) {
  6836. var destination = creationFunction();
  6837. // Tags
  6838. if (BABYLON.Tags) {
  6839. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6840. }
  6841. var classStore = getMergedStore(destination);
  6842. // Properties
  6843. for (var property in classStore) {
  6844. var propertyDescriptor = classStore[property];
  6845. var sourceProperty = source[property];
  6846. var propertyType = propertyDescriptor.type;
  6847. if (sourceProperty !== undefined && sourceProperty !== null) {
  6848. switch (propertyType) {
  6849. case 0: // Value
  6850. case 6:// Mesh reference
  6851. destination[property] = sourceProperty;
  6852. break;
  6853. case 1:// Texture
  6854. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6855. break;
  6856. case 2: // Color3
  6857. case 3: // FresnelParameters
  6858. case 4: // Vector2
  6859. case 5: // Vector3
  6860. case 7: // Color Curves
  6861. case 10:// Quaternion
  6862. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6863. break;
  6864. }
  6865. }
  6866. }
  6867. return destination;
  6868. };
  6869. function getDirectStore(target) {
  6870. var classKey = target.getClassName();
  6871. if (!__decoratorInitialStore[classKey]) {
  6872. __decoratorInitialStore[classKey] = {};
  6873. }
  6874. return __decoratorInitialStore[classKey];
  6875. }
  6876. /**
  6877. * Return the list of properties flagged as serializable
  6878. * @param target: host object
  6879. */
  6880. function getMergedStore(target) {
  6881. var classKey = target.getClassName();
  6882. if (__mergedStore[classKey]) {
  6883. return __mergedStore[classKey];
  6884. }
  6885. __mergedStore[classKey] = {};
  6886. var store = __mergedStore[classKey];
  6887. var currentTarget = target;
  6888. var currentKey = classKey;
  6889. while (currentKey) {
  6890. var initialStore = __decoratorInitialStore[currentKey];
  6891. for (var property in initialStore) {
  6892. store[property] = initialStore[property];
  6893. }
  6894. var parent_1 = void 0;
  6895. var done = false;
  6896. do {
  6897. parent_1 = Object.getPrototypeOf(currentTarget);
  6898. if (!parent_1.getClassName) {
  6899. done = true;
  6900. break;
  6901. }
  6902. if (parent_1.getClassName() !== currentKey) {
  6903. break;
  6904. }
  6905. currentTarget = parent_1;
  6906. } while (parent_1);
  6907. if (done) {
  6908. break;
  6909. }
  6910. currentKey = parent_1.getClassName();
  6911. currentTarget = parent_1;
  6912. }
  6913. return store;
  6914. }
  6915. function generateSerializableMember(type, sourceName) {
  6916. return function (target, propertyKey) {
  6917. var classStore = getDirectStore(target);
  6918. if (!classStore[propertyKey]) {
  6919. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6920. }
  6921. };
  6922. }
  6923. function generateExpandMember(setCallback, targetKey) {
  6924. if (targetKey === void 0) { targetKey = null; }
  6925. return function (target, propertyKey) {
  6926. var key = targetKey || ("_" + propertyKey);
  6927. Object.defineProperty(target, propertyKey, {
  6928. get: function () {
  6929. return this[key];
  6930. },
  6931. set: function (value) {
  6932. if (this[key] === value) {
  6933. return;
  6934. }
  6935. this[key] = value;
  6936. target[setCallback].apply(this);
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. };
  6942. }
  6943. function expandToProperty(callback, targetKey) {
  6944. if (targetKey === void 0) { targetKey = null; }
  6945. return generateExpandMember(callback, targetKey);
  6946. }
  6947. BABYLON.expandToProperty = expandToProperty;
  6948. function serialize(sourceName) {
  6949. return generateSerializableMember(0, sourceName); // value member
  6950. }
  6951. BABYLON.serialize = serialize;
  6952. function serializeAsTexture(sourceName) {
  6953. return generateSerializableMember(1, sourceName); // texture member
  6954. }
  6955. BABYLON.serializeAsTexture = serializeAsTexture;
  6956. function serializeAsColor3(sourceName) {
  6957. return generateSerializableMember(2, sourceName); // color3 member
  6958. }
  6959. BABYLON.serializeAsColor3 = serializeAsColor3;
  6960. function serializeAsFresnelParameters(sourceName) {
  6961. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6962. }
  6963. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6964. function serializeAsVector2(sourceName) {
  6965. return generateSerializableMember(4, sourceName); // vector2 member
  6966. }
  6967. BABYLON.serializeAsVector2 = serializeAsVector2;
  6968. function serializeAsVector3(sourceName) {
  6969. return generateSerializableMember(5, sourceName); // vector3 member
  6970. }
  6971. BABYLON.serializeAsVector3 = serializeAsVector3;
  6972. function serializeAsMeshReference(sourceName) {
  6973. return generateSerializableMember(6, sourceName); // mesh reference member
  6974. }
  6975. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6976. function serializeAsColorCurves(sourceName) {
  6977. return generateSerializableMember(7, sourceName); // color curves
  6978. }
  6979. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6980. function serializeAsColor4(sourceName) {
  6981. return generateSerializableMember(8, sourceName); // color 4
  6982. }
  6983. BABYLON.serializeAsColor4 = serializeAsColor4;
  6984. function serializeAsImageProcessingConfiguration(sourceName) {
  6985. return generateSerializableMember(9, sourceName); // image processing
  6986. }
  6987. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6988. function serializeAsQuaternion(sourceName) {
  6989. return generateSerializableMember(10, sourceName); // quaternion member
  6990. }
  6991. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6992. var SerializationHelper = /** @class */ (function () {
  6993. function SerializationHelper() {
  6994. }
  6995. SerializationHelper.Serialize = function (entity, serializationObject) {
  6996. if (!serializationObject) {
  6997. serializationObject = {};
  6998. }
  6999. // Tags
  7000. if (BABYLON.Tags) {
  7001. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7002. }
  7003. var serializedProperties = getMergedStore(entity);
  7004. // Properties
  7005. for (var property in serializedProperties) {
  7006. var propertyDescriptor = serializedProperties[property];
  7007. var targetPropertyName = propertyDescriptor.sourceName || property;
  7008. var propertyType = propertyDescriptor.type;
  7009. var sourceProperty = entity[property];
  7010. if (sourceProperty !== undefined && sourceProperty !== null) {
  7011. switch (propertyType) {
  7012. case 0:// Value
  7013. serializationObject[targetPropertyName] = sourceProperty;
  7014. break;
  7015. case 1:// Texture
  7016. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7017. break;
  7018. case 2:// Color3
  7019. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7020. break;
  7021. case 3:// FresnelParameters
  7022. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7023. break;
  7024. case 4:// Vector2
  7025. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7026. break;
  7027. case 5:// Vector3
  7028. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7029. break;
  7030. case 6:// Mesh reference
  7031. serializationObject[targetPropertyName] = sourceProperty.id;
  7032. break;
  7033. case 7:// Color Curves
  7034. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7035. break;
  7036. case 8:// Color 4
  7037. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7038. break;
  7039. case 9:// Image Processing
  7040. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7041. break;
  7042. }
  7043. }
  7044. }
  7045. return serializationObject;
  7046. };
  7047. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7048. if (rootUrl === void 0) { rootUrl = null; }
  7049. var destination = creationFunction();
  7050. if (!rootUrl) {
  7051. rootUrl = "";
  7052. }
  7053. // Tags
  7054. if (BABYLON.Tags) {
  7055. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7056. }
  7057. var classStore = getMergedStore(destination);
  7058. // Properties
  7059. for (var property in classStore) {
  7060. var propertyDescriptor = classStore[property];
  7061. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7062. var propertyType = propertyDescriptor.type;
  7063. if (sourceProperty !== undefined && sourceProperty !== null) {
  7064. var dest = destination;
  7065. switch (propertyType) {
  7066. case 0:// Value
  7067. dest[property] = sourceProperty;
  7068. break;
  7069. case 1:// Texture
  7070. if (scene) {
  7071. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7072. }
  7073. break;
  7074. case 2:// Color3
  7075. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7076. break;
  7077. case 3:// FresnelParameters
  7078. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7079. break;
  7080. case 4:// Vector2
  7081. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7082. break;
  7083. case 5:// Vector3
  7084. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7085. break;
  7086. case 6:// Mesh reference
  7087. if (scene) {
  7088. dest[property] = scene.getLastMeshByID(sourceProperty);
  7089. }
  7090. break;
  7091. case 7:// Color Curves
  7092. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7093. break;
  7094. case 8:// Color 4
  7095. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7096. break;
  7097. case 9:// Image Processing
  7098. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7099. break;
  7100. }
  7101. }
  7102. }
  7103. return destination;
  7104. };
  7105. SerializationHelper.Clone = function (creationFunction, source) {
  7106. return _copySource(creationFunction, source, false);
  7107. };
  7108. SerializationHelper.Instanciate = function (creationFunction, source) {
  7109. return _copySource(creationFunction, source, true);
  7110. };
  7111. return SerializationHelper;
  7112. }());
  7113. BABYLON.SerializationHelper = SerializationHelper;
  7114. })(BABYLON || (BABYLON = {}));
  7115. //# sourceMappingURL=babylon.decorators.js.map
  7116. var BABYLON;
  7117. (function (BABYLON) {
  7118. /**
  7119. * A class serves as a medium between the observable and its observers
  7120. */
  7121. var EventState = /** @class */ (function () {
  7122. /**
  7123. * Create a new EventState
  7124. * @param mask defines the mask associated with this state
  7125. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7126. * @param target defines the original target of the state
  7127. * @param currentTarget defines the current target of the state
  7128. */
  7129. function EventState(mask, skipNextObservers, target, currentTarget) {
  7130. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7131. this.initalize(mask, skipNextObservers, target, currentTarget);
  7132. }
  7133. /**
  7134. * Initialize the current event state
  7135. * @param mask defines the mask associated with this state
  7136. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7137. * @param target defines the original target of the state
  7138. * @param currentTarget defines the current target of the state
  7139. * @returns the current event state
  7140. */
  7141. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7142. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7143. this.mask = mask;
  7144. this.skipNextObservers = skipNextObservers;
  7145. this.target = target;
  7146. this.currentTarget = currentTarget;
  7147. return this;
  7148. };
  7149. return EventState;
  7150. }());
  7151. BABYLON.EventState = EventState;
  7152. /**
  7153. * Represent an Observer registered to a given Observable object.
  7154. */
  7155. var Observer = /** @class */ (function () {
  7156. /**
  7157. * Creates a new observer
  7158. * @param callback defines the callback to call when the observer is notified
  7159. * @param mask defines the mask of the observer (used to filter notifications)
  7160. * @param scope defines the current scope used to restore the JS context
  7161. */
  7162. function Observer(
  7163. /**
  7164. * Defines the callback to call when the observer is notified
  7165. */
  7166. callback,
  7167. /**
  7168. * Defines the mask of the observer (used to filter notifications)
  7169. */
  7170. mask,
  7171. /**
  7172. * Defines the current scope used to restore the JS context
  7173. */
  7174. scope) {
  7175. if (scope === void 0) { scope = null; }
  7176. this.callback = callback;
  7177. this.mask = mask;
  7178. this.scope = scope;
  7179. /**
  7180. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7181. */
  7182. this.unregisterOnNextCall = false;
  7183. }
  7184. return Observer;
  7185. }());
  7186. BABYLON.Observer = Observer;
  7187. /**
  7188. * Represent a list of observers registered to multiple Observables object.
  7189. */
  7190. var MultiObserver = /** @class */ (function () {
  7191. function MultiObserver() {
  7192. }
  7193. /**
  7194. * Release associated resources
  7195. */
  7196. MultiObserver.prototype.dispose = function () {
  7197. if (this._observers && this._observables) {
  7198. for (var index = 0; index < this._observers.length; index++) {
  7199. this._observables[index].remove(this._observers[index]);
  7200. }
  7201. }
  7202. this._observers = null;
  7203. this._observables = null;
  7204. };
  7205. /**
  7206. * Raise a callback when one of the observable will notify
  7207. * @param observables defines a list of observables to watch
  7208. * @param callback defines the callback to call on notification
  7209. * @param mask defines the mask used to filter notifications
  7210. * @param scope defines the current scope used to restore the JS context
  7211. * @returns the new MultiObserver
  7212. */
  7213. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7214. if (mask === void 0) { mask = -1; }
  7215. if (scope === void 0) { scope = null; }
  7216. var result = new MultiObserver();
  7217. result._observers = new Array();
  7218. result._observables = observables;
  7219. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7220. var observable = observables_1[_i];
  7221. var observer = observable.add(callback, mask, false, scope);
  7222. if (observer) {
  7223. result._observers.push(observer);
  7224. }
  7225. }
  7226. return result;
  7227. };
  7228. return MultiObserver;
  7229. }());
  7230. BABYLON.MultiObserver = MultiObserver;
  7231. /**
  7232. * The Observable class is a simple implementation of the Observable pattern.
  7233. * 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.
  7234. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7235. * 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).
  7236. * 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.
  7237. */
  7238. var Observable = /** @class */ (function () {
  7239. /**
  7240. * Creates a new observable
  7241. * @param onObserverAdded defines a callback to call when a new observer is added
  7242. */
  7243. function Observable(onObserverAdded) {
  7244. this._observers = new Array();
  7245. this._eventState = new EventState(0);
  7246. if (onObserverAdded) {
  7247. this._onObserverAdded = onObserverAdded;
  7248. }
  7249. }
  7250. /**
  7251. * Create a new Observer with the specified callback
  7252. * @param callback the callback that will be executed for that Observer
  7253. * @param mask the mask used to filter observers
  7254. * @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.
  7255. * @param scope optional scope for the callback to be called from
  7256. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7257. * @returns the new observer created for the callback
  7258. */
  7259. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7260. if (mask === void 0) { mask = -1; }
  7261. if (insertFirst === void 0) { insertFirst = false; }
  7262. if (scope === void 0) { scope = null; }
  7263. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7264. if (!callback) {
  7265. return null;
  7266. }
  7267. var observer = new Observer(callback, mask, scope);
  7268. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7269. if (insertFirst) {
  7270. this._observers.unshift(observer);
  7271. }
  7272. else {
  7273. this._observers.push(observer);
  7274. }
  7275. if (this._onObserverAdded) {
  7276. this._onObserverAdded(observer);
  7277. }
  7278. return observer;
  7279. };
  7280. /**
  7281. * Remove an Observer from the Observable object
  7282. * @param observer the instance of the Observer to remove
  7283. * @returns false if it doesn't belong to this Observable
  7284. */
  7285. Observable.prototype.remove = function (observer) {
  7286. if (!observer) {
  7287. return false;
  7288. }
  7289. var index = this._observers.indexOf(observer);
  7290. if (index !== -1) {
  7291. this._observers.splice(index, 1);
  7292. return true;
  7293. }
  7294. return false;
  7295. };
  7296. /**
  7297. * Remove a callback from the Observable object
  7298. * @param callback the callback to remove
  7299. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7300. * @returns false if it doesn't belong to this Observable
  7301. */
  7302. Observable.prototype.removeCallback = function (callback, scope) {
  7303. for (var index = 0; index < this._observers.length; index++) {
  7304. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7305. this._observers.splice(index, 1);
  7306. return true;
  7307. }
  7308. }
  7309. return false;
  7310. };
  7311. Observable.prototype._deferUnregister = function (observer) {
  7312. var _this = this;
  7313. observer.unregisterOnNextCall = false;
  7314. BABYLON.Tools.SetImmediate(function () {
  7315. _this.remove(observer);
  7316. });
  7317. };
  7318. /**
  7319. * Notify all Observers by calling their respective callback with the given data
  7320. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7321. * @param eventData defines the data to send to all observers
  7322. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7323. * @param target defines the original target of the state
  7324. * @param currentTarget defines the current target of the state
  7325. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7326. */
  7327. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7328. if (mask === void 0) { mask = -1; }
  7329. if (!this._observers.length) {
  7330. return true;
  7331. }
  7332. var state = this._eventState;
  7333. state.mask = mask;
  7334. state.target = target;
  7335. state.currentTarget = currentTarget;
  7336. state.skipNextObservers = false;
  7337. state.lastReturnValue = eventData;
  7338. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7339. var obs = _a[_i];
  7340. if (obs.mask & mask) {
  7341. if (obs.scope) {
  7342. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7343. }
  7344. else {
  7345. state.lastReturnValue = obs.callback(eventData, state);
  7346. }
  7347. if (obs.unregisterOnNextCall) {
  7348. this._deferUnregister(obs);
  7349. }
  7350. }
  7351. if (state.skipNextObservers) {
  7352. return false;
  7353. }
  7354. }
  7355. return true;
  7356. };
  7357. /**
  7358. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7359. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7360. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7361. * and it is crucial that all callbacks will be executed.
  7362. * The order of the callbacks is kept, callbacks are not executed parallel.
  7363. *
  7364. * @param eventData The data to be sent to each callback
  7365. * @param mask is used to filter observers defaults to -1
  7366. * @param target defines the callback target (see EventState)
  7367. * @param currentTarget defines he current object in the bubbling phase
  7368. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7369. */
  7370. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7371. var _this = this;
  7372. if (mask === void 0) { mask = -1; }
  7373. // create an empty promise
  7374. var p = Promise.resolve(eventData);
  7375. // no observers? return this promise.
  7376. if (!this._observers.length) {
  7377. return p;
  7378. }
  7379. var state = this._eventState;
  7380. state.mask = mask;
  7381. state.target = target;
  7382. state.currentTarget = currentTarget;
  7383. state.skipNextObservers = false;
  7384. // execute one callback after another (not using Promise.all, the order is important)
  7385. this._observers.forEach(function (obs) {
  7386. if (state.skipNextObservers) {
  7387. return;
  7388. }
  7389. if (obs.mask & mask) {
  7390. if (obs.scope) {
  7391. p = p.then(function (lastReturnedValue) {
  7392. state.lastReturnValue = lastReturnedValue;
  7393. return obs.callback.apply(obs.scope, [eventData, state]);
  7394. });
  7395. }
  7396. else {
  7397. p = p.then(function (lastReturnedValue) {
  7398. state.lastReturnValue = lastReturnedValue;
  7399. return obs.callback(eventData, state);
  7400. });
  7401. }
  7402. if (obs.unregisterOnNextCall) {
  7403. _this._deferUnregister(obs);
  7404. }
  7405. }
  7406. });
  7407. // return the eventData
  7408. return p.then(function () { return eventData; });
  7409. };
  7410. /**
  7411. * Notify a specific observer
  7412. * @param observer defines the observer to notify
  7413. * @param eventData defines the data to be sent to each callback
  7414. * @param mask is used to filter observers defaults to -1
  7415. */
  7416. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7417. if (mask === void 0) { mask = -1; }
  7418. var state = this._eventState;
  7419. state.mask = mask;
  7420. state.skipNextObservers = false;
  7421. observer.callback(eventData, state);
  7422. };
  7423. /**
  7424. * Gets a boolean indicating if the observable has at least one observer
  7425. * @returns true is the Observable has at least one Observer registered
  7426. */
  7427. Observable.prototype.hasObservers = function () {
  7428. return this._observers.length > 0;
  7429. };
  7430. /**
  7431. * Clear the list of observers
  7432. */
  7433. Observable.prototype.clear = function () {
  7434. this._observers = new Array();
  7435. this._onObserverAdded = null;
  7436. };
  7437. /**
  7438. * Clone the current observable
  7439. * @returns a new observable
  7440. */
  7441. Observable.prototype.clone = function () {
  7442. var result = new Observable();
  7443. result._observers = this._observers.slice(0);
  7444. return result;
  7445. };
  7446. /**
  7447. * Does this observable handles observer registered with a given mask
  7448. * @param mask defines the mask to be tested
  7449. * @return whether or not one observer registered with the given mask is handeled
  7450. **/
  7451. Observable.prototype.hasSpecificMask = function (mask) {
  7452. if (mask === void 0) { mask = -1; }
  7453. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7454. var obs = _a[_i];
  7455. if (obs.mask & mask || obs.mask === mask) {
  7456. return true;
  7457. }
  7458. }
  7459. return false;
  7460. };
  7461. return Observable;
  7462. }());
  7463. BABYLON.Observable = Observable;
  7464. })(BABYLON || (BABYLON = {}));
  7465. //# sourceMappingURL=babylon.observable.js.map
  7466. var BABYLON;
  7467. (function (BABYLON) {
  7468. var SmartArray = /** @class */ (function () {
  7469. function SmartArray(capacity) {
  7470. this.length = 0;
  7471. this.data = new Array(capacity);
  7472. this._id = SmartArray._GlobalId++;
  7473. }
  7474. SmartArray.prototype.push = function (value) {
  7475. this.data[this.length++] = value;
  7476. if (this.length > this.data.length) {
  7477. this.data.length *= 2;
  7478. }
  7479. };
  7480. SmartArray.prototype.forEach = function (func) {
  7481. for (var index = 0; index < this.length; index++) {
  7482. func(this.data[index]);
  7483. }
  7484. };
  7485. SmartArray.prototype.sort = function (compareFn) {
  7486. this.data.sort(compareFn);
  7487. };
  7488. SmartArray.prototype.reset = function () {
  7489. this.length = 0;
  7490. };
  7491. SmartArray.prototype.dispose = function () {
  7492. this.reset();
  7493. if (this.data) {
  7494. this.data.length = 0;
  7495. this.data = [];
  7496. }
  7497. };
  7498. SmartArray.prototype.concat = function (array) {
  7499. if (array.length === 0) {
  7500. return;
  7501. }
  7502. if (this.length + array.length > this.data.length) {
  7503. this.data.length = (this.length + array.length) * 2;
  7504. }
  7505. for (var index = 0; index < array.length; index++) {
  7506. this.data[this.length++] = (array.data || array)[index];
  7507. }
  7508. };
  7509. SmartArray.prototype.indexOf = function (value) {
  7510. var position = this.data.indexOf(value);
  7511. if (position >= this.length) {
  7512. return -1;
  7513. }
  7514. return position;
  7515. };
  7516. SmartArray.prototype.contains = function (value) {
  7517. return this.data.indexOf(value) !== -1;
  7518. };
  7519. // Statics
  7520. SmartArray._GlobalId = 0;
  7521. return SmartArray;
  7522. }());
  7523. BABYLON.SmartArray = SmartArray;
  7524. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7525. __extends(SmartArrayNoDuplicate, _super);
  7526. function SmartArrayNoDuplicate() {
  7527. var _this = _super !== null && _super.apply(this, arguments) || this;
  7528. _this._duplicateId = 0;
  7529. return _this;
  7530. }
  7531. SmartArrayNoDuplicate.prototype.push = function (value) {
  7532. _super.prototype.push.call(this, value);
  7533. if (!value.__smartArrayFlags) {
  7534. value.__smartArrayFlags = {};
  7535. }
  7536. value.__smartArrayFlags[this._id] = this._duplicateId;
  7537. };
  7538. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7539. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7540. return false;
  7541. }
  7542. this.push(value);
  7543. return true;
  7544. };
  7545. SmartArrayNoDuplicate.prototype.reset = function () {
  7546. _super.prototype.reset.call(this);
  7547. this._duplicateId++;
  7548. };
  7549. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7550. if (array.length === 0) {
  7551. return;
  7552. }
  7553. if (this.length + array.length > this.data.length) {
  7554. this.data.length = (this.length + array.length) * 2;
  7555. }
  7556. for (var index = 0; index < array.length; index++) {
  7557. var item = (array.data || array)[index];
  7558. this.pushNoDuplicate(item);
  7559. }
  7560. };
  7561. return SmartArrayNoDuplicate;
  7562. }(SmartArray));
  7563. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7564. })(BABYLON || (BABYLON = {}));
  7565. //# sourceMappingURL=babylon.smartArray.js.map
  7566. var BABYLON;
  7567. (function (BABYLON) {
  7568. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7569. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7570. var LoadFileError = /** @class */ (function (_super) {
  7571. __extends(LoadFileError, _super);
  7572. function LoadFileError(message, request) {
  7573. var _this = _super.call(this, message) || this;
  7574. _this.request = request;
  7575. _this.name = "LoadFileError";
  7576. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7577. return _this;
  7578. }
  7579. // Polyfill for Object.setPrototypeOf if necessary.
  7580. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7581. return LoadFileError;
  7582. }(Error));
  7583. BABYLON.LoadFileError = LoadFileError;
  7584. var RetryStrategy = /** @class */ (function () {
  7585. function RetryStrategy() {
  7586. }
  7587. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7588. if (maxRetries === void 0) { maxRetries = 3; }
  7589. if (baseInterval === void 0) { baseInterval = 500; }
  7590. return function (url, request, retryIndex) {
  7591. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7592. return -1;
  7593. }
  7594. return Math.pow(2, retryIndex) * baseInterval;
  7595. };
  7596. };
  7597. return RetryStrategy;
  7598. }());
  7599. BABYLON.RetryStrategy = RetryStrategy;
  7600. // Screenshots
  7601. var screenshotCanvas;
  7602. var cloneValue = function (source, destinationObject) {
  7603. if (!source)
  7604. return null;
  7605. if (source instanceof BABYLON.Mesh) {
  7606. return null;
  7607. }
  7608. if (source instanceof BABYLON.SubMesh) {
  7609. return source.clone(destinationObject);
  7610. }
  7611. else if (source.clone) {
  7612. return source.clone();
  7613. }
  7614. return null;
  7615. };
  7616. var Tools = /** @class */ (function () {
  7617. function Tools() {
  7618. }
  7619. /**
  7620. * Interpolates between a and b via alpha
  7621. * @param a The lower value (returned when alpha = 0)
  7622. * @param b The upper value (returned when alpha = 1)
  7623. * @param alpha The interpolation-factor
  7624. * @return The mixed value
  7625. */
  7626. Tools.Mix = function (a, b, alpha) {
  7627. return a * (1 - alpha) + b * alpha;
  7628. };
  7629. Tools.Instantiate = function (className) {
  7630. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7631. return Tools.RegisteredExternalClasses[className];
  7632. }
  7633. var arr = className.split(".");
  7634. var fn = (window || this);
  7635. for (var i = 0, len = arr.length; i < len; i++) {
  7636. fn = fn[arr[i]];
  7637. }
  7638. if (typeof fn !== "function") {
  7639. return null;
  7640. }
  7641. return fn;
  7642. };
  7643. /**
  7644. * Provides a slice function that will work even on IE
  7645. * @param data defines the array to slice
  7646. * @returns the new sliced array
  7647. */
  7648. Tools.Slice = function (data) {
  7649. if (data.slice) {
  7650. return data.slice();
  7651. }
  7652. return Array.prototype.slice.call(data);
  7653. };
  7654. Tools.SetImmediate = function (action) {
  7655. if (window.setImmediate) {
  7656. window.setImmediate(action);
  7657. }
  7658. else {
  7659. setTimeout(action, 1);
  7660. }
  7661. };
  7662. Tools.IsExponentOfTwo = function (value) {
  7663. var count = 1;
  7664. do {
  7665. count *= 2;
  7666. } while (count < value);
  7667. return count === value;
  7668. };
  7669. /**
  7670. * Find the next highest power of two.
  7671. * @param x Number to start search from.
  7672. * @return Next highest power of two.
  7673. */
  7674. Tools.CeilingPOT = function (x) {
  7675. x--;
  7676. x |= x >> 1;
  7677. x |= x >> 2;
  7678. x |= x >> 4;
  7679. x |= x >> 8;
  7680. x |= x >> 16;
  7681. x++;
  7682. return x;
  7683. };
  7684. /**
  7685. * Find the next lowest power of two.
  7686. * @param x Number to start search from.
  7687. * @return Next lowest power of two.
  7688. */
  7689. Tools.FloorPOT = function (x) {
  7690. x = x | (x >> 1);
  7691. x = x | (x >> 2);
  7692. x = x | (x >> 4);
  7693. x = x | (x >> 8);
  7694. x = x | (x >> 16);
  7695. return x - (x >> 1);
  7696. };
  7697. /**
  7698. * Find the nearest power of two.
  7699. * @param x Number to start search from.
  7700. * @return Next nearest power of two.
  7701. */
  7702. Tools.NearestPOT = function (x) {
  7703. var c = Tools.CeilingPOT(x);
  7704. var f = Tools.FloorPOT(x);
  7705. return (c - x) > (x - f) ? f : c;
  7706. };
  7707. Tools.GetExponentOfTwo = function (value, max, mode) {
  7708. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7709. var pot;
  7710. switch (mode) {
  7711. case BABYLON.Engine.SCALEMODE_FLOOR:
  7712. pot = Tools.FloorPOT(value);
  7713. break;
  7714. case BABYLON.Engine.SCALEMODE_NEAREST:
  7715. pot = Tools.NearestPOT(value);
  7716. break;
  7717. case BABYLON.Engine.SCALEMODE_CEILING:
  7718. default:
  7719. pot = Tools.CeilingPOT(value);
  7720. break;
  7721. }
  7722. return Math.min(pot, max);
  7723. };
  7724. Tools.GetFilename = function (path) {
  7725. var index = path.lastIndexOf("/");
  7726. if (index < 0)
  7727. return path;
  7728. return path.substring(index + 1);
  7729. };
  7730. /**
  7731. * Extracts the "folder" part of a path (everything before the filename).
  7732. * @param uri The URI to extract the info from
  7733. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7734. * @returns The "folder" part of the path
  7735. */
  7736. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7737. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7738. var index = uri.lastIndexOf("/");
  7739. if (index < 0) {
  7740. if (returnUnchangedIfNoSlash) {
  7741. return uri;
  7742. }
  7743. return "";
  7744. }
  7745. return uri.substring(0, index + 1);
  7746. };
  7747. Tools.GetDOMTextContent = function (element) {
  7748. var result = "";
  7749. var child = element.firstChild;
  7750. while (child) {
  7751. if (child.nodeType === 3) {
  7752. result += child.textContent;
  7753. }
  7754. child = child.nextSibling;
  7755. }
  7756. return result;
  7757. };
  7758. Tools.ToDegrees = function (angle) {
  7759. return angle * 180 / Math.PI;
  7760. };
  7761. Tools.ToRadians = function (angle) {
  7762. return angle * Math.PI / 180;
  7763. };
  7764. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7765. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7766. var output = "";
  7767. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7768. var i = 0;
  7769. var bytes = new Uint8Array(buffer);
  7770. while (i < bytes.length) {
  7771. chr1 = bytes[i++];
  7772. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7773. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7774. enc1 = chr1 >> 2;
  7775. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7776. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7777. enc4 = chr3 & 63;
  7778. if (isNaN(chr2)) {
  7779. enc3 = enc4 = 64;
  7780. }
  7781. else if (isNaN(chr3)) {
  7782. enc4 = 64;
  7783. }
  7784. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7785. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7786. }
  7787. return "data:image/png;base64," + output;
  7788. };
  7789. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7790. if (bias === void 0) { bias = null; }
  7791. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7792. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7793. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7794. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7795. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7796. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7797. }
  7798. if (bias) {
  7799. minimum.x -= minimum.x * bias.x + bias.y;
  7800. minimum.y -= minimum.y * bias.x + bias.y;
  7801. minimum.z -= minimum.z * bias.x + bias.y;
  7802. maximum.x += maximum.x * bias.x + bias.y;
  7803. maximum.y += maximum.y * bias.x + bias.y;
  7804. maximum.z += maximum.z * bias.x + bias.y;
  7805. }
  7806. return {
  7807. minimum: minimum,
  7808. maximum: maximum
  7809. };
  7810. };
  7811. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7812. if (bias === void 0) { bias = null; }
  7813. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7814. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7815. if (!stride) {
  7816. stride = 3;
  7817. }
  7818. for (var index = start; index < start + count; index++) {
  7819. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7820. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7821. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7822. }
  7823. if (bias) {
  7824. minimum.x -= minimum.x * bias.x + bias.y;
  7825. minimum.y -= minimum.y * bias.x + bias.y;
  7826. minimum.z -= minimum.z * bias.x + bias.y;
  7827. maximum.x += maximum.x * bias.x + bias.y;
  7828. maximum.y += maximum.y * bias.x + bias.y;
  7829. maximum.z += maximum.z * bias.x + bias.y;
  7830. }
  7831. return {
  7832. minimum: minimum,
  7833. maximum: maximum
  7834. };
  7835. };
  7836. Tools.Vector2ArrayFeeder = function (array) {
  7837. return function (index) {
  7838. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7839. var length = isFloatArray ? array.length / 2 : array.length;
  7840. if (index >= length) {
  7841. return null;
  7842. }
  7843. if (isFloatArray) {
  7844. var fa = array;
  7845. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7846. }
  7847. var a = array;
  7848. return a[index];
  7849. };
  7850. };
  7851. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7852. if (bias === void 0) { bias = null; }
  7853. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7854. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7855. var i = 0;
  7856. var cur = feeder(i++);
  7857. while (cur) {
  7858. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7859. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7860. cur = feeder(i++);
  7861. }
  7862. if (bias) {
  7863. minimum.x -= minimum.x * bias.x + bias.y;
  7864. minimum.y -= minimum.y * bias.x + bias.y;
  7865. maximum.x += maximum.x * bias.x + bias.y;
  7866. maximum.y += maximum.y * bias.x + bias.y;
  7867. }
  7868. return {
  7869. minimum: minimum,
  7870. maximum: maximum
  7871. };
  7872. };
  7873. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7874. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7875. return null;
  7876. return Array.isArray(obj) ? obj : [obj];
  7877. };
  7878. // Misc.
  7879. Tools.GetPointerPrefix = function () {
  7880. var eventPrefix = "pointer";
  7881. // Check if pointer events are supported
  7882. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7883. eventPrefix = "mouse";
  7884. }
  7885. return eventPrefix;
  7886. };
  7887. /**
  7888. * @param func - the function to be called
  7889. * @param requester - the object that will request the next frame. Falls back to window.
  7890. */
  7891. Tools.QueueNewFrame = function (func, requester) {
  7892. if (!Tools.IsWindowObjectExist()) {
  7893. return setTimeout(func, 16);
  7894. }
  7895. if (!requester) {
  7896. requester = window;
  7897. }
  7898. if (requester.requestAnimationFrame) {
  7899. return requester.requestAnimationFrame(func);
  7900. }
  7901. else if (requester.msRequestAnimationFrame) {
  7902. return requester.msRequestAnimationFrame(func);
  7903. }
  7904. else if (requester.webkitRequestAnimationFrame) {
  7905. return requester.webkitRequestAnimationFrame(func);
  7906. }
  7907. else if (requester.mozRequestAnimationFrame) {
  7908. return requester.mozRequestAnimationFrame(func);
  7909. }
  7910. else if (requester.oRequestAnimationFrame) {
  7911. return requester.oRequestAnimationFrame(func);
  7912. }
  7913. else {
  7914. return window.setTimeout(func, 16);
  7915. }
  7916. };
  7917. Tools.RequestFullscreen = function (element) {
  7918. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7919. if (!requestFunction)
  7920. return;
  7921. requestFunction.call(element);
  7922. };
  7923. Tools.ExitFullscreen = function () {
  7924. if (document.exitFullscreen) {
  7925. document.exitFullscreen();
  7926. }
  7927. else if (document.mozCancelFullScreen) {
  7928. document.mozCancelFullScreen();
  7929. }
  7930. else if (document.webkitCancelFullScreen) {
  7931. document.webkitCancelFullScreen();
  7932. }
  7933. else if (document.msCancelFullScreen) {
  7934. document.msCancelFullScreen();
  7935. }
  7936. };
  7937. Tools.SetCorsBehavior = function (url, element) {
  7938. if (url && url.indexOf("data:") === 0) {
  7939. return;
  7940. }
  7941. if (Tools.CorsBehavior) {
  7942. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7943. element.crossOrigin = Tools.CorsBehavior;
  7944. }
  7945. else {
  7946. var result = Tools.CorsBehavior(url);
  7947. if (result) {
  7948. element.crossOrigin = result;
  7949. }
  7950. }
  7951. }
  7952. };
  7953. // External files
  7954. Tools.CleanUrl = function (url) {
  7955. url = url.replace(/#/mg, "%23");
  7956. return url;
  7957. };
  7958. Tools.LoadImage = function (url, onLoad, onError, database) {
  7959. if (url instanceof ArrayBuffer) {
  7960. url = Tools.EncodeArrayBufferTobase64(url);
  7961. }
  7962. url = Tools.CleanUrl(url);
  7963. url = Tools.PreprocessUrl(url);
  7964. var img = new Image();
  7965. Tools.SetCorsBehavior(url, img);
  7966. img.onload = function () {
  7967. onLoad(img);
  7968. };
  7969. img.onerror = function (err) {
  7970. Tools.Error("Error while trying to load image: " + url);
  7971. if (onError) {
  7972. onError("Error while trying to load image: " + url, err);
  7973. }
  7974. };
  7975. var noIndexedDB = function () {
  7976. img.src = url;
  7977. };
  7978. var loadFromIndexedDB = function () {
  7979. if (database) {
  7980. database.loadImageFromDB(url, img);
  7981. }
  7982. };
  7983. //ANY database to do!
  7984. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7985. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7986. }
  7987. else {
  7988. if (url.indexOf("file:") !== -1) {
  7989. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7990. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7991. try {
  7992. var blobURL;
  7993. try {
  7994. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7995. }
  7996. catch (ex) {
  7997. // Chrome doesn't support oneTimeOnly parameter
  7998. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7999. }
  8000. img.src = blobURL;
  8001. }
  8002. catch (e) {
  8003. img.src = "";
  8004. }
  8005. return img;
  8006. }
  8007. }
  8008. noIndexedDB();
  8009. }
  8010. return img;
  8011. };
  8012. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8013. url = Tools.CleanUrl(url);
  8014. url = Tools.PreprocessUrl(url);
  8015. // If file and file input are set
  8016. if (url.indexOf("file:") !== -1) {
  8017. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8018. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8019. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8020. }
  8021. }
  8022. var loadUrl = Tools.BaseUrl + url;
  8023. var aborted = false;
  8024. var fileRequest = {
  8025. onCompleteObservable: new BABYLON.Observable(),
  8026. abort: function () { return aborted = true; },
  8027. };
  8028. var requestFile = function () {
  8029. var request = new XMLHttpRequest();
  8030. var retryHandle = null;
  8031. fileRequest.abort = function () {
  8032. aborted = true;
  8033. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8034. request.abort();
  8035. }
  8036. if (retryHandle !== null) {
  8037. clearTimeout(retryHandle);
  8038. retryHandle = null;
  8039. }
  8040. };
  8041. var retryLoop = function (retryIndex) {
  8042. request.open('GET', loadUrl, true);
  8043. if (useArrayBuffer) {
  8044. request.responseType = "arraybuffer";
  8045. }
  8046. if (onProgress) {
  8047. request.addEventListener("progress", onProgress);
  8048. }
  8049. var onLoadEnd = function () {
  8050. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8051. };
  8052. request.addEventListener("loadend", onLoadEnd);
  8053. var onReadyStateChange = function () {
  8054. if (aborted) {
  8055. return;
  8056. }
  8057. // In case of undefined state in some browsers.
  8058. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8059. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8060. request.removeEventListener("readystatechange", onReadyStateChange);
  8061. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8062. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8063. return;
  8064. }
  8065. var retryStrategy = Tools.DefaultRetryStrategy;
  8066. if (retryStrategy) {
  8067. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8068. if (waitTime !== -1) {
  8069. // Prevent the request from completing for retry.
  8070. request.removeEventListener("loadend", onLoadEnd);
  8071. request = new XMLHttpRequest();
  8072. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8073. return;
  8074. }
  8075. }
  8076. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8077. if (onError) {
  8078. onError(request, e);
  8079. }
  8080. else {
  8081. throw e;
  8082. }
  8083. }
  8084. };
  8085. request.addEventListener("readystatechange", onReadyStateChange);
  8086. request.send();
  8087. };
  8088. retryLoop(0);
  8089. };
  8090. // Caching all files
  8091. if (database && database.enableSceneOffline) {
  8092. var noIndexedDB_1 = function () {
  8093. if (!aborted) {
  8094. requestFile();
  8095. }
  8096. };
  8097. var loadFromIndexedDB = function () {
  8098. // TODO: database needs to support aborting and should return a IFileRequest
  8099. if (aborted) {
  8100. return;
  8101. }
  8102. if (database) {
  8103. database.loadFileFromDB(url, function (data) {
  8104. if (!aborted) {
  8105. onSuccess(data);
  8106. }
  8107. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8108. }, onProgress ? function (event) {
  8109. if (!aborted) {
  8110. onProgress(event);
  8111. }
  8112. } : undefined, noIndexedDB_1, useArrayBuffer);
  8113. }
  8114. };
  8115. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8116. }
  8117. else {
  8118. requestFile();
  8119. }
  8120. return fileRequest;
  8121. };
  8122. /**
  8123. * Load a script (identified by an url). When the url returns, the
  8124. * content of this file is added into a new script element, attached to the DOM (body element)
  8125. */
  8126. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8127. var head = document.getElementsByTagName('head')[0];
  8128. var script = document.createElement('script');
  8129. script.type = 'text/javascript';
  8130. script.src = scriptUrl;
  8131. script.onload = function () {
  8132. if (onSuccess) {
  8133. onSuccess();
  8134. }
  8135. };
  8136. script.onerror = function (e) {
  8137. if (onError) {
  8138. onError("Unable to load script", e);
  8139. }
  8140. };
  8141. head.appendChild(script);
  8142. };
  8143. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8144. var reader = new FileReader();
  8145. var request = {
  8146. onCompleteObservable: new BABYLON.Observable(),
  8147. abort: function () { return reader.abort(); },
  8148. };
  8149. reader.onloadend = function (e) {
  8150. request.onCompleteObservable.notifyObservers(request);
  8151. };
  8152. reader.onload = function (e) {
  8153. //target doesn't have result from ts 1.3
  8154. callback(e.target['result']);
  8155. };
  8156. reader.onprogress = progressCallback;
  8157. reader.readAsDataURL(fileToLoad);
  8158. return request;
  8159. };
  8160. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8161. var reader = new FileReader();
  8162. var request = {
  8163. onCompleteObservable: new BABYLON.Observable(),
  8164. abort: function () { return reader.abort(); },
  8165. };
  8166. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8167. reader.onerror = function (e) {
  8168. Tools.Log("Error while reading file: " + fileToLoad.name);
  8169. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8170. };
  8171. reader.onload = function (e) {
  8172. //target doesn't have result from ts 1.3
  8173. callback(e.target['result']);
  8174. };
  8175. if (progressCallBack) {
  8176. reader.onprogress = progressCallBack;
  8177. }
  8178. if (!useArrayBuffer) {
  8179. // Asynchronous read
  8180. reader.readAsText(fileToLoad);
  8181. }
  8182. else {
  8183. reader.readAsArrayBuffer(fileToLoad);
  8184. }
  8185. return request;
  8186. };
  8187. //returns a downloadable url to a file content.
  8188. Tools.FileAsURL = function (content) {
  8189. var fileBlob = new Blob([content]);
  8190. var url = window.URL || window.webkitURL;
  8191. var link = url.createObjectURL(fileBlob);
  8192. return link;
  8193. };
  8194. // Misc.
  8195. Tools.Format = function (value, decimals) {
  8196. if (decimals === void 0) { decimals = 2; }
  8197. return value.toFixed(decimals);
  8198. };
  8199. Tools.CheckExtends = function (v, min, max) {
  8200. if (v.x < min.x)
  8201. min.x = v.x;
  8202. if (v.y < min.y)
  8203. min.y = v.y;
  8204. if (v.z < min.z)
  8205. min.z = v.z;
  8206. if (v.x > max.x)
  8207. max.x = v.x;
  8208. if (v.y > max.y)
  8209. max.y = v.y;
  8210. if (v.z > max.z)
  8211. max.z = v.z;
  8212. };
  8213. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8214. for (var prop in source) {
  8215. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8216. continue;
  8217. }
  8218. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8219. continue;
  8220. }
  8221. var sourceValue = source[prop];
  8222. var typeOfSourceValue = typeof sourceValue;
  8223. if (typeOfSourceValue === "function") {
  8224. continue;
  8225. }
  8226. if (typeOfSourceValue === "object") {
  8227. if (sourceValue instanceof Array) {
  8228. destination[prop] = [];
  8229. if (sourceValue.length > 0) {
  8230. if (typeof sourceValue[0] == "object") {
  8231. for (var index = 0; index < sourceValue.length; index++) {
  8232. var clonedValue = cloneValue(sourceValue[index], destination);
  8233. if (destination[prop].indexOf(clonedValue) === -1) {
  8234. destination[prop].push(clonedValue);
  8235. }
  8236. }
  8237. }
  8238. else {
  8239. destination[prop] = sourceValue.slice(0);
  8240. }
  8241. }
  8242. }
  8243. else {
  8244. destination[prop] = cloneValue(sourceValue, destination);
  8245. }
  8246. }
  8247. else {
  8248. destination[prop] = sourceValue;
  8249. }
  8250. }
  8251. };
  8252. Tools.IsEmpty = function (obj) {
  8253. for (var i in obj) {
  8254. if (obj.hasOwnProperty(i)) {
  8255. return false;
  8256. }
  8257. }
  8258. return true;
  8259. };
  8260. Tools.RegisterTopRootEvents = function (events) {
  8261. for (var index = 0; index < events.length; index++) {
  8262. var event = events[index];
  8263. window.addEventListener(event.name, event.handler, false);
  8264. try {
  8265. if (window.parent) {
  8266. window.parent.addEventListener(event.name, event.handler, false);
  8267. }
  8268. }
  8269. catch (e) {
  8270. // Silently fails...
  8271. }
  8272. }
  8273. };
  8274. Tools.UnregisterTopRootEvents = function (events) {
  8275. for (var index = 0; index < events.length; index++) {
  8276. var event = events[index];
  8277. window.removeEventListener(event.name, event.handler);
  8278. try {
  8279. if (window.parent) {
  8280. window.parent.removeEventListener(event.name, event.handler);
  8281. }
  8282. }
  8283. catch (e) {
  8284. // Silently fails...
  8285. }
  8286. }
  8287. };
  8288. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8289. if (mimeType === void 0) { mimeType = "image/png"; }
  8290. // Read the contents of the framebuffer
  8291. var numberOfChannelsByLine = width * 4;
  8292. var halfHeight = height / 2;
  8293. //Reading datas from WebGL
  8294. var data = engine.readPixels(0, 0, width, height);
  8295. //To flip image on Y axis.
  8296. for (var i = 0; i < halfHeight; i++) {
  8297. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8298. var currentCell = j + i * numberOfChannelsByLine;
  8299. var targetLine = height - i - 1;
  8300. var targetCell = j + targetLine * numberOfChannelsByLine;
  8301. var temp = data[currentCell];
  8302. data[currentCell] = data[targetCell];
  8303. data[targetCell] = temp;
  8304. }
  8305. }
  8306. // Create a 2D canvas to store the result
  8307. if (!screenshotCanvas) {
  8308. screenshotCanvas = document.createElement('canvas');
  8309. }
  8310. screenshotCanvas.width = width;
  8311. screenshotCanvas.height = height;
  8312. var context = screenshotCanvas.getContext('2d');
  8313. if (context) {
  8314. // Copy the pixels to a 2D canvas
  8315. var imageData = context.createImageData(width, height);
  8316. var castData = (imageData.data);
  8317. castData.set(data);
  8318. context.putImageData(imageData, 0, 0);
  8319. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8320. }
  8321. };
  8322. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8323. if (mimeType === void 0) { mimeType = "image/png"; }
  8324. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8325. if (successCallback) {
  8326. successCallback(base64Image);
  8327. }
  8328. else {
  8329. // We need HTMLCanvasElement.toBlob for HD screenshots
  8330. if (!screenshotCanvas.toBlob) {
  8331. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8332. screenshotCanvas.toBlob = function (callback, type, quality) {
  8333. var _this = this;
  8334. setTimeout(function () {
  8335. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8336. for (var i = 0; i < len; i++) {
  8337. arr[i] = binStr.charCodeAt(i);
  8338. }
  8339. callback(new Blob([arr], { type: type || 'image/png' }));
  8340. });
  8341. };
  8342. }
  8343. screenshotCanvas.toBlob(function (blob) {
  8344. var url = URL.createObjectURL(blob);
  8345. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8346. if (("download" in document.createElement("a"))) {
  8347. var a = window.document.createElement("a");
  8348. a.href = url;
  8349. if (fileName) {
  8350. a.setAttribute("download", fileName);
  8351. }
  8352. else {
  8353. var date = new Date();
  8354. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8355. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8356. }
  8357. window.document.body.appendChild(a);
  8358. a.addEventListener("click", function () {
  8359. if (a.parentElement) {
  8360. a.parentElement.removeChild(a);
  8361. }
  8362. });
  8363. a.click();
  8364. }
  8365. else {
  8366. var newWindow = window.open("");
  8367. if (!newWindow)
  8368. return;
  8369. var img = newWindow.document.createElement("img");
  8370. img.onload = function () {
  8371. // no longer need to read the blob so it's revoked
  8372. URL.revokeObjectURL(url);
  8373. };
  8374. img.src = url;
  8375. newWindow.document.body.appendChild(img);
  8376. }
  8377. });
  8378. }
  8379. };
  8380. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8381. if (mimeType === void 0) { mimeType = "image/png"; }
  8382. var width;
  8383. var height;
  8384. // If a precision value is specified
  8385. if (size.precision) {
  8386. width = Math.round(engine.getRenderWidth() * size.precision);
  8387. height = Math.round(width / engine.getAspectRatio(camera));
  8388. }
  8389. else if (size.width && size.height) {
  8390. width = size.width;
  8391. height = size.height;
  8392. }
  8393. else if (size.width && !size.height) {
  8394. width = size.width;
  8395. height = Math.round(width / engine.getAspectRatio(camera));
  8396. }
  8397. else if (size.height && !size.width) {
  8398. height = size.height;
  8399. width = Math.round(height * engine.getAspectRatio(camera));
  8400. }
  8401. else if (!isNaN(size)) {
  8402. height = size;
  8403. width = size;
  8404. }
  8405. else {
  8406. Tools.Error("Invalid 'size' parameter !");
  8407. return;
  8408. }
  8409. if (!screenshotCanvas) {
  8410. screenshotCanvas = document.createElement('canvas');
  8411. }
  8412. screenshotCanvas.width = width;
  8413. screenshotCanvas.height = height;
  8414. var renderContext = screenshotCanvas.getContext("2d");
  8415. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8416. var newWidth = width;
  8417. var newHeight = newWidth / ratio;
  8418. if (newHeight > height) {
  8419. newHeight = height;
  8420. newWidth = newHeight * ratio;
  8421. }
  8422. var offsetX = Math.max(0, width - newWidth) / 2;
  8423. var offsetY = Math.max(0, height - newHeight) / 2;
  8424. var renderingCanvas = engine.getRenderingCanvas();
  8425. if (renderContext && renderingCanvas) {
  8426. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8427. }
  8428. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8429. };
  8430. /**
  8431. * Generates an image screenshot from the specified camera.
  8432. *
  8433. * @param engine The engine to use for rendering
  8434. * @param camera The camera to use for rendering
  8435. * @param size This parameter can be set to a single number or to an object with the
  8436. * following (optional) properties: precision, width, height. If a single number is passed,
  8437. * it will be used for both width and height. If an object is passed, the screenshot size
  8438. * will be derived from the parameters. The precision property is a multiplier allowing
  8439. * rendering at a higher or lower resolution.
  8440. * @param successCallback The callback receives a single parameter which contains the
  8441. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8442. * src parameter of an <img> to display it.
  8443. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8444. * Check your browser for supported MIME types.
  8445. * @param samples Texture samples (default: 1)
  8446. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8447. * @param fileName A name for for the downloaded file.
  8448. * @constructor
  8449. */
  8450. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8451. if (mimeType === void 0) { mimeType = "image/png"; }
  8452. if (samples === void 0) { samples = 1; }
  8453. if (antialiasing === void 0) { antialiasing = false; }
  8454. var width;
  8455. var height;
  8456. //If a precision value is specified
  8457. if (size.precision) {
  8458. width = Math.round(engine.getRenderWidth() * size.precision);
  8459. height = Math.round(width / engine.getAspectRatio(camera));
  8460. size = { width: width, height: height };
  8461. }
  8462. else if (size.width && size.height) {
  8463. width = size.width;
  8464. height = size.height;
  8465. }
  8466. else if (size.width && !size.height) {
  8467. width = size.width;
  8468. height = Math.round(width / engine.getAspectRatio(camera));
  8469. size = { width: width, height: height };
  8470. }
  8471. else if (size.height && !size.width) {
  8472. height = size.height;
  8473. width = Math.round(height * engine.getAspectRatio(camera));
  8474. size = { width: width, height: height };
  8475. }
  8476. else if (!isNaN(size)) {
  8477. height = size;
  8478. width = size;
  8479. }
  8480. else {
  8481. Tools.Error("Invalid 'size' parameter !");
  8482. return;
  8483. }
  8484. var scene = camera.getScene();
  8485. var previousCamera = null;
  8486. if (scene.activeCamera !== camera) {
  8487. previousCamera = scene.activeCamera;
  8488. scene.activeCamera = camera;
  8489. }
  8490. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8491. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8492. texture.renderList = null;
  8493. texture.samples = samples;
  8494. if (antialiasing) {
  8495. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8496. }
  8497. texture.onAfterRenderObservable.add(function () {
  8498. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8499. });
  8500. scene.incrementRenderId();
  8501. scene.resetCachedMaterial();
  8502. texture.render(true);
  8503. texture.dispose();
  8504. if (previousCamera) {
  8505. scene.activeCamera = previousCamera;
  8506. }
  8507. camera.getProjectionMatrix(true); // Force cache refresh;
  8508. };
  8509. // XHR response validator for local file scenario
  8510. Tools.ValidateXHRData = function (xhr, dataType) {
  8511. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8512. if (dataType === void 0) { dataType = 7; }
  8513. try {
  8514. if (dataType & 1) {
  8515. if (xhr.responseText && xhr.responseText.length > 0) {
  8516. return true;
  8517. }
  8518. else if (dataType === 1) {
  8519. return false;
  8520. }
  8521. }
  8522. if (dataType & 2) {
  8523. // Check header width and height since there is no "TGA" magic number
  8524. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8525. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8526. return true;
  8527. }
  8528. else if (dataType === 2) {
  8529. return false;
  8530. }
  8531. }
  8532. if (dataType & 4) {
  8533. // Check for the "DDS" magic number
  8534. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8535. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8536. return true;
  8537. }
  8538. else {
  8539. return false;
  8540. }
  8541. }
  8542. }
  8543. catch (e) {
  8544. // Global protection
  8545. }
  8546. return false;
  8547. };
  8548. /**
  8549. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8550. * Be aware Math.random() could cause collisions, but:
  8551. * "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"
  8552. */
  8553. Tools.RandomId = function () {
  8554. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8555. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8556. return v.toString(16);
  8557. });
  8558. };
  8559. /**
  8560. * Test if the given uri is a base64 string.
  8561. * @param uri The uri to test
  8562. * @return True if the uri is a base64 string or false otherwise.
  8563. */
  8564. Tools.IsBase64 = function (uri) {
  8565. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8566. };
  8567. /**
  8568. * Decode the given base64 uri.
  8569. * @param uri The uri to decode
  8570. * @return The decoded base64 data.
  8571. */
  8572. Tools.DecodeBase64 = function (uri) {
  8573. var decodedString = atob(uri.split(",")[1]);
  8574. var bufferLength = decodedString.length;
  8575. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8576. for (var i = 0; i < bufferLength; i++) {
  8577. bufferView[i] = decodedString.charCodeAt(i);
  8578. }
  8579. return bufferView.buffer;
  8580. };
  8581. Object.defineProperty(Tools, "NoneLogLevel", {
  8582. get: function () {
  8583. return Tools._NoneLogLevel;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(Tools, "MessageLogLevel", {
  8589. get: function () {
  8590. return Tools._MessageLogLevel;
  8591. },
  8592. enumerable: true,
  8593. configurable: true
  8594. });
  8595. Object.defineProperty(Tools, "WarningLogLevel", {
  8596. get: function () {
  8597. return Tools._WarningLogLevel;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. Object.defineProperty(Tools, "ErrorLogLevel", {
  8603. get: function () {
  8604. return Tools._ErrorLogLevel;
  8605. },
  8606. enumerable: true,
  8607. configurable: true
  8608. });
  8609. Object.defineProperty(Tools, "AllLogLevel", {
  8610. get: function () {
  8611. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. Tools._AddLogEntry = function (entry) {
  8617. Tools._LogCache = entry + Tools._LogCache;
  8618. if (Tools.OnNewCacheEntry) {
  8619. Tools.OnNewCacheEntry(entry);
  8620. }
  8621. };
  8622. Tools._FormatMessage = function (message) {
  8623. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8624. var date = new Date();
  8625. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8626. };
  8627. Tools._LogDisabled = function (message) {
  8628. // nothing to do
  8629. };
  8630. Tools._LogEnabled = function (message) {
  8631. var formattedMessage = Tools._FormatMessage(message);
  8632. console.log("BJS - " + formattedMessage);
  8633. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8634. Tools._AddLogEntry(entry);
  8635. };
  8636. Tools._WarnDisabled = function (message) {
  8637. // nothing to do
  8638. };
  8639. Tools._WarnEnabled = function (message) {
  8640. var formattedMessage = Tools._FormatMessage(message);
  8641. console.warn("BJS - " + formattedMessage);
  8642. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8643. Tools._AddLogEntry(entry);
  8644. };
  8645. Tools._ErrorDisabled = function (message) {
  8646. // nothing to do
  8647. };
  8648. Tools._ErrorEnabled = function (message) {
  8649. Tools.errorsCount++;
  8650. var formattedMessage = Tools._FormatMessage(message);
  8651. console.error("BJS - " + formattedMessage);
  8652. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8653. Tools._AddLogEntry(entry);
  8654. };
  8655. Object.defineProperty(Tools, "LogCache", {
  8656. get: function () {
  8657. return Tools._LogCache;
  8658. },
  8659. enumerable: true,
  8660. configurable: true
  8661. });
  8662. Tools.ClearLogCache = function () {
  8663. Tools._LogCache = "";
  8664. Tools.errorsCount = 0;
  8665. };
  8666. Object.defineProperty(Tools, "LogLevels", {
  8667. set: function (level) {
  8668. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8669. Tools.Log = Tools._LogEnabled;
  8670. }
  8671. else {
  8672. Tools.Log = Tools._LogDisabled;
  8673. }
  8674. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8675. Tools.Warn = Tools._WarnEnabled;
  8676. }
  8677. else {
  8678. Tools.Warn = Tools._WarnDisabled;
  8679. }
  8680. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8681. Tools.Error = Tools._ErrorEnabled;
  8682. }
  8683. else {
  8684. Tools.Error = Tools._ErrorDisabled;
  8685. }
  8686. },
  8687. enumerable: true,
  8688. configurable: true
  8689. });
  8690. Tools.IsWindowObjectExist = function () {
  8691. return (typeof window) !== "undefined";
  8692. };
  8693. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8694. get: function () {
  8695. return Tools._PerformanceNoneLogLevel;
  8696. },
  8697. enumerable: true,
  8698. configurable: true
  8699. });
  8700. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8701. get: function () {
  8702. return Tools._PerformanceUserMarkLogLevel;
  8703. },
  8704. enumerable: true,
  8705. configurable: true
  8706. });
  8707. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8708. get: function () {
  8709. return Tools._PerformanceConsoleLogLevel;
  8710. },
  8711. enumerable: true,
  8712. configurable: true
  8713. });
  8714. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8715. set: function (level) {
  8716. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8717. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8718. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8719. return;
  8720. }
  8721. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8722. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8723. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8724. return;
  8725. }
  8726. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8727. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8728. },
  8729. enumerable: true,
  8730. configurable: true
  8731. });
  8732. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8733. };
  8734. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8735. };
  8736. Tools._StartUserMark = function (counterName, condition) {
  8737. if (condition === void 0) { condition = true; }
  8738. if (!Tools._performance) {
  8739. if (!Tools.IsWindowObjectExist()) {
  8740. return;
  8741. }
  8742. Tools._performance = window.performance;
  8743. }
  8744. if (!condition || !Tools._performance.mark) {
  8745. return;
  8746. }
  8747. Tools._performance.mark(counterName + "-Begin");
  8748. };
  8749. Tools._EndUserMark = function (counterName, condition) {
  8750. if (condition === void 0) { condition = true; }
  8751. if (!condition || !Tools._performance.mark) {
  8752. return;
  8753. }
  8754. Tools._performance.mark(counterName + "-End");
  8755. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8756. };
  8757. Tools._StartPerformanceConsole = function (counterName, condition) {
  8758. if (condition === void 0) { condition = true; }
  8759. if (!condition) {
  8760. return;
  8761. }
  8762. Tools._StartUserMark(counterName, condition);
  8763. if (console.time) {
  8764. console.time(counterName);
  8765. }
  8766. };
  8767. Tools._EndPerformanceConsole = function (counterName, condition) {
  8768. if (condition === void 0) { condition = true; }
  8769. if (!condition) {
  8770. return;
  8771. }
  8772. Tools._EndUserMark(counterName, condition);
  8773. if (console.time) {
  8774. console.timeEnd(counterName);
  8775. }
  8776. };
  8777. Object.defineProperty(Tools, "Now", {
  8778. get: function () {
  8779. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8780. return window.performance.now();
  8781. }
  8782. return new Date().getTime();
  8783. },
  8784. enumerable: true,
  8785. configurable: true
  8786. });
  8787. /**
  8788. * This method will return the name of the class used to create the instance of the given object.
  8789. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8790. * @param object the object to get the class name from
  8791. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8792. */
  8793. Tools.GetClassName = function (object, isType) {
  8794. if (isType === void 0) { isType = false; }
  8795. var name = null;
  8796. if (!isType && object.getClassName) {
  8797. name = object.getClassName();
  8798. }
  8799. else {
  8800. if (object instanceof Object) {
  8801. var classObj = isType ? object : Object.getPrototypeOf(object);
  8802. name = classObj.constructor["__bjsclassName__"];
  8803. }
  8804. if (!name) {
  8805. name = typeof object;
  8806. }
  8807. }
  8808. return name;
  8809. };
  8810. Tools.First = function (array, predicate) {
  8811. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8812. var el = array_1[_i];
  8813. if (predicate(el)) {
  8814. return el;
  8815. }
  8816. }
  8817. return null;
  8818. };
  8819. /**
  8820. * This method will return the name of the full name of the class, including its owning module (if any).
  8821. * 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).
  8822. * @param object the object to get the class name from
  8823. * @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.
  8824. */
  8825. Tools.getFullClassName = function (object, isType) {
  8826. if (isType === void 0) { isType = false; }
  8827. var className = null;
  8828. var moduleName = null;
  8829. if (!isType && object.getClassName) {
  8830. className = object.getClassName();
  8831. }
  8832. else {
  8833. if (object instanceof Object) {
  8834. var classObj = isType ? object : Object.getPrototypeOf(object);
  8835. className = classObj.constructor["__bjsclassName__"];
  8836. moduleName = classObj.constructor["__bjsmoduleName__"];
  8837. }
  8838. if (!className) {
  8839. className = typeof object;
  8840. }
  8841. }
  8842. if (!className) {
  8843. return null;
  8844. }
  8845. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8846. };
  8847. /**
  8848. * 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.
  8849. * @param array
  8850. */
  8851. Tools.arrayOrStringFeeder = function (array) {
  8852. return function (index) {
  8853. if (index >= array.length) {
  8854. return null;
  8855. }
  8856. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8857. if (val && val.getHashCode) {
  8858. val = val.getHashCode();
  8859. }
  8860. if (typeof val === "string") {
  8861. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8862. }
  8863. return val;
  8864. };
  8865. };
  8866. /**
  8867. * Compute the hashCode of a stream of number
  8868. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8869. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8870. * @return the hash code computed
  8871. */
  8872. Tools.hashCodeFromStream = function (feeder) {
  8873. // Based from here: http://stackoverflow.com/a/7616484/802124
  8874. var hash = 0;
  8875. var index = 0;
  8876. var chr = feeder(index++);
  8877. while (chr != null) {
  8878. hash = ((hash << 5) - hash) + chr;
  8879. hash |= 0; // Convert to 32bit integer
  8880. chr = feeder(index++);
  8881. }
  8882. return hash;
  8883. };
  8884. Tools.BaseUrl = "";
  8885. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8886. /**
  8887. * Default behaviour for cors in the application.
  8888. * It can be a string if the expected behavior is identical in the entire app.
  8889. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8890. */
  8891. Tools.CorsBehavior = "anonymous";
  8892. Tools.UseFallbackTexture = true;
  8893. /**
  8894. * Use this object to register external classes like custom textures or material
  8895. * to allow the laoders to instantiate them
  8896. */
  8897. Tools.RegisteredExternalClasses = {};
  8898. // Used in case of a texture loading problem
  8899. 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";
  8900. Tools.PreprocessUrl = function (url) {
  8901. return url;
  8902. };
  8903. // Logs
  8904. Tools._NoneLogLevel = 0;
  8905. Tools._MessageLogLevel = 1;
  8906. Tools._WarningLogLevel = 2;
  8907. Tools._ErrorLogLevel = 4;
  8908. Tools._LogCache = "";
  8909. Tools.errorsCount = 0;
  8910. Tools.Log = Tools._LogEnabled;
  8911. Tools.Warn = Tools._WarnEnabled;
  8912. Tools.Error = Tools._ErrorEnabled;
  8913. // Performances
  8914. Tools._PerformanceNoneLogLevel = 0;
  8915. Tools._PerformanceUserMarkLogLevel = 1;
  8916. Tools._PerformanceConsoleLogLevel = 2;
  8917. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8918. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8919. return Tools;
  8920. }());
  8921. BABYLON.Tools = Tools;
  8922. /**
  8923. * This class is used to track a performance counter which is number based.
  8924. * The user has access to many properties which give statistics of different nature
  8925. *
  8926. * The implementer can track two kinds of Performance Counter: time and count
  8927. * 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.
  8928. * 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.
  8929. */
  8930. var PerfCounter = /** @class */ (function () {
  8931. function PerfCounter() {
  8932. this._startMonitoringTime = 0;
  8933. this._min = 0;
  8934. this._max = 0;
  8935. this._average = 0;
  8936. this._lastSecAverage = 0;
  8937. this._current = 0;
  8938. this._totalValueCount = 0;
  8939. this._totalAccumulated = 0;
  8940. this._lastSecAccumulated = 0;
  8941. this._lastSecTime = 0;
  8942. this._lastSecValueCount = 0;
  8943. }
  8944. Object.defineProperty(PerfCounter.prototype, "min", {
  8945. /**
  8946. * Returns the smallest value ever
  8947. */
  8948. get: function () {
  8949. return this._min;
  8950. },
  8951. enumerable: true,
  8952. configurable: true
  8953. });
  8954. Object.defineProperty(PerfCounter.prototype, "max", {
  8955. /**
  8956. * Returns the biggest value ever
  8957. */
  8958. get: function () {
  8959. return this._max;
  8960. },
  8961. enumerable: true,
  8962. configurable: true
  8963. });
  8964. Object.defineProperty(PerfCounter.prototype, "average", {
  8965. /**
  8966. * Returns the average value since the performance counter is running
  8967. */
  8968. get: function () {
  8969. return this._average;
  8970. },
  8971. enumerable: true,
  8972. configurable: true
  8973. });
  8974. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8975. /**
  8976. * Returns the average value of the last second the counter was monitored
  8977. */
  8978. get: function () {
  8979. return this._lastSecAverage;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Object.defineProperty(PerfCounter.prototype, "current", {
  8985. /**
  8986. * Returns the current value
  8987. */
  8988. get: function () {
  8989. return this._current;
  8990. },
  8991. enumerable: true,
  8992. configurable: true
  8993. });
  8994. Object.defineProperty(PerfCounter.prototype, "total", {
  8995. get: function () {
  8996. return this._totalAccumulated;
  8997. },
  8998. enumerable: true,
  8999. configurable: true
  9000. });
  9001. Object.defineProperty(PerfCounter.prototype, "count", {
  9002. get: function () {
  9003. return this._totalValueCount;
  9004. },
  9005. enumerable: true,
  9006. configurable: true
  9007. });
  9008. /**
  9009. * Call this method to start monitoring a new frame.
  9010. * 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.
  9011. */
  9012. PerfCounter.prototype.fetchNewFrame = function () {
  9013. this._totalValueCount++;
  9014. this._current = 0;
  9015. this._lastSecValueCount++;
  9016. };
  9017. /**
  9018. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9019. * @param newCount the count value to add to the monitored count
  9020. * @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.
  9021. */
  9022. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9023. if (!PerfCounter.Enabled) {
  9024. return;
  9025. }
  9026. this._current += newCount;
  9027. if (fetchResult) {
  9028. this._fetchResult();
  9029. }
  9030. };
  9031. /**
  9032. * Start monitoring this performance counter
  9033. */
  9034. PerfCounter.prototype.beginMonitoring = function () {
  9035. if (!PerfCounter.Enabled) {
  9036. return;
  9037. }
  9038. this._startMonitoringTime = Tools.Now;
  9039. };
  9040. /**
  9041. * Compute the time lapsed since the previous beginMonitoring() call.
  9042. * @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
  9043. */
  9044. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9045. if (newFrame === void 0) { newFrame = true; }
  9046. if (!PerfCounter.Enabled) {
  9047. return;
  9048. }
  9049. if (newFrame) {
  9050. this.fetchNewFrame();
  9051. }
  9052. var currentTime = Tools.Now;
  9053. this._current = currentTime - this._startMonitoringTime;
  9054. if (newFrame) {
  9055. this._fetchResult();
  9056. }
  9057. };
  9058. PerfCounter.prototype._fetchResult = function () {
  9059. this._totalAccumulated += this._current;
  9060. this._lastSecAccumulated += this._current;
  9061. // Min/Max update
  9062. this._min = Math.min(this._min, this._current);
  9063. this._max = Math.max(this._max, this._current);
  9064. this._average = this._totalAccumulated / this._totalValueCount;
  9065. // Reset last sec?
  9066. var now = Tools.Now;
  9067. if ((now - this._lastSecTime) > 1000) {
  9068. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9069. this._lastSecTime = now;
  9070. this._lastSecAccumulated = 0;
  9071. this._lastSecValueCount = 0;
  9072. }
  9073. };
  9074. PerfCounter.Enabled = true;
  9075. return PerfCounter;
  9076. }());
  9077. BABYLON.PerfCounter = PerfCounter;
  9078. /**
  9079. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9080. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9081. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9082. * @param name The name of the class, case should be preserved
  9083. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9084. */
  9085. function className(name, module) {
  9086. return function (target) {
  9087. target["__bjsclassName__"] = name;
  9088. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9089. };
  9090. }
  9091. BABYLON.className = className;
  9092. /**
  9093. * An implementation of a loop for asynchronous functions.
  9094. */
  9095. var AsyncLoop = /** @class */ (function () {
  9096. /**
  9097. * Constroctor.
  9098. * @param iterations the number of iterations.
  9099. * @param _fn the function to run each iteration
  9100. * @param _successCallback the callback that will be called upon succesful execution
  9101. * @param offset starting offset.
  9102. */
  9103. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9104. if (offset === void 0) { offset = 0; }
  9105. this.iterations = iterations;
  9106. this._fn = _fn;
  9107. this._successCallback = _successCallback;
  9108. this.index = offset - 1;
  9109. this._done = false;
  9110. }
  9111. /**
  9112. * Execute the next iteration. Must be called after the last iteration was finished.
  9113. */
  9114. AsyncLoop.prototype.executeNext = function () {
  9115. if (!this._done) {
  9116. if (this.index + 1 < this.iterations) {
  9117. ++this.index;
  9118. this._fn(this);
  9119. }
  9120. else {
  9121. this.breakLoop();
  9122. }
  9123. }
  9124. };
  9125. /**
  9126. * Break the loop and run the success callback.
  9127. */
  9128. AsyncLoop.prototype.breakLoop = function () {
  9129. this._done = true;
  9130. this._successCallback();
  9131. };
  9132. /**
  9133. * Helper function
  9134. */
  9135. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9136. if (offset === void 0) { offset = 0; }
  9137. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9138. loop.executeNext();
  9139. return loop;
  9140. };
  9141. /**
  9142. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9143. * @param iterations total number of iterations
  9144. * @param syncedIterations number of synchronous iterations in each async iteration.
  9145. * @param fn the function to call each iteration.
  9146. * @param callback a success call back that will be called when iterating stops.
  9147. * @param breakFunction a break condition (optional)
  9148. * @param timeout timeout settings for the setTimeout function. default - 0.
  9149. * @constructor
  9150. */
  9151. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9152. if (timeout === void 0) { timeout = 0; }
  9153. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9154. if (breakFunction && breakFunction())
  9155. loop.breakLoop();
  9156. else {
  9157. setTimeout(function () {
  9158. for (var i = 0; i < syncedIterations; ++i) {
  9159. var iteration = (loop.index * syncedIterations) + i;
  9160. if (iteration >= iterations)
  9161. break;
  9162. fn(iteration);
  9163. if (breakFunction && breakFunction()) {
  9164. loop.breakLoop();
  9165. break;
  9166. }
  9167. }
  9168. loop.executeNext();
  9169. }, timeout);
  9170. }
  9171. }, callback);
  9172. };
  9173. return AsyncLoop;
  9174. }());
  9175. BABYLON.AsyncLoop = AsyncLoop;
  9176. })(BABYLON || (BABYLON = {}));
  9177. //# sourceMappingURL=babylon.tools.js.map
  9178. var BABYLON;
  9179. (function (BABYLON) {
  9180. var PromiseStates;
  9181. (function (PromiseStates) {
  9182. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9183. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9184. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9185. })(PromiseStates || (PromiseStates = {}));
  9186. var FulFillmentAgregator = /** @class */ (function () {
  9187. function FulFillmentAgregator() {
  9188. this.count = 0;
  9189. this.target = 0;
  9190. this.results = [];
  9191. }
  9192. return FulFillmentAgregator;
  9193. }());
  9194. var InternalPromise = /** @class */ (function () {
  9195. function InternalPromise(resolver) {
  9196. var _this = this;
  9197. this._state = PromiseStates.Pending;
  9198. this._children = new Array();
  9199. this._rejectWasConsumed = false;
  9200. if (!resolver) {
  9201. return;
  9202. }
  9203. try {
  9204. resolver(function (value) {
  9205. _this._resolve(value);
  9206. }, function (reason) {
  9207. _this._reject(reason);
  9208. });
  9209. }
  9210. catch (e) {
  9211. this._reject(e.message);
  9212. }
  9213. }
  9214. Object.defineProperty(InternalPromise.prototype, "state", {
  9215. get: function () {
  9216. return this._state;
  9217. },
  9218. enumerable: true,
  9219. configurable: true
  9220. });
  9221. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  9222. get: function () {
  9223. return this._state === PromiseStates.Fulfilled;
  9224. },
  9225. enumerable: true,
  9226. configurable: true
  9227. });
  9228. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  9229. get: function () {
  9230. return this._state === PromiseStates.Rejected;
  9231. },
  9232. enumerable: true,
  9233. configurable: true
  9234. });
  9235. Object.defineProperty(InternalPromise.prototype, "isPending", {
  9236. get: function () {
  9237. return this._state === PromiseStates.Pending;
  9238. },
  9239. enumerable: true,
  9240. configurable: true
  9241. });
  9242. InternalPromise.prototype.value = function () {
  9243. if (!this.isFulfilled) {
  9244. throw new Error("Promise is not fulfilled");
  9245. }
  9246. return this._result;
  9247. };
  9248. InternalPromise.prototype.reason = function () {
  9249. if (!this.isRejected) {
  9250. throw new Error("Promise is not rejected");
  9251. }
  9252. return this._reason;
  9253. };
  9254. InternalPromise.prototype.catch = function (onRejected) {
  9255. return this.then(undefined, onRejected);
  9256. };
  9257. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9258. var newPromise = new InternalPromise();
  9259. newPromise._onFulfilled = onFulfilled;
  9260. newPromise._onRejected = onRejected;
  9261. // Composition
  9262. this._children.push(newPromise);
  9263. if (this._state !== PromiseStates.Pending) {
  9264. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  9265. var returnedValue = newPromise._resolve(this._result);
  9266. if (returnedValue !== undefined && returnedValue !== null) {
  9267. if (returnedValue._state !== undefined) {
  9268. var returnedPromise = returnedValue;
  9269. newPromise._children.push(returnedPromise);
  9270. newPromise = returnedPromise;
  9271. }
  9272. else {
  9273. newPromise._result = returnedValue;
  9274. }
  9275. }
  9276. }
  9277. else {
  9278. newPromise._reject(this._reason);
  9279. }
  9280. }
  9281. return newPromise;
  9282. };
  9283. InternalPromise.prototype._moveChildren = function (children) {
  9284. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9285. if (this.isFulfilled) {
  9286. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9287. var child = _b[_i];
  9288. child._resolve(this._result);
  9289. }
  9290. }
  9291. else if (this.isRejected) {
  9292. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9293. var child = _d[_c];
  9294. child._reject(this._reason);
  9295. }
  9296. }
  9297. var _a;
  9298. };
  9299. InternalPromise.prototype._resolve = function (value) {
  9300. try {
  9301. this._state = PromiseStates.Fulfilled;
  9302. this._result = value;
  9303. var returnedValue = null;
  9304. if (this._onFulfilled) {
  9305. returnedValue = this._onFulfilled(value);
  9306. }
  9307. if (returnedValue !== undefined && returnedValue !== null) {
  9308. if (returnedValue._state !== undefined) {
  9309. // Transmit children
  9310. var returnedPromise = returnedValue;
  9311. returnedPromise._moveChildren(this._children);
  9312. }
  9313. else {
  9314. value = returnedValue;
  9315. }
  9316. }
  9317. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9318. var child = _a[_i];
  9319. child._resolve(value);
  9320. }
  9321. return returnedValue;
  9322. }
  9323. catch (e) {
  9324. this._reject(e.message);
  9325. }
  9326. return null;
  9327. };
  9328. InternalPromise.prototype._reject = function (reason) {
  9329. this._state = PromiseStates.Rejected;
  9330. this._reason = reason;
  9331. if (this._onRejected) {
  9332. this._onRejected(reason);
  9333. this._rejectWasConsumed = true;
  9334. }
  9335. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9336. var child = _a[_i];
  9337. if (this._rejectWasConsumed) {
  9338. child._resolve(null);
  9339. }
  9340. else {
  9341. child._reject(reason);
  9342. }
  9343. }
  9344. };
  9345. InternalPromise.resolve = function (value) {
  9346. var newPromise = new InternalPromise();
  9347. newPromise._resolve(value);
  9348. return newPromise;
  9349. };
  9350. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9351. promise.then(function (value) {
  9352. agregator.results[index] = value;
  9353. agregator.count++;
  9354. if (agregator.count === agregator.target) {
  9355. agregator.rootPromise._resolve(agregator.results);
  9356. }
  9357. return null;
  9358. }, function (reason) {
  9359. if (!agregator.rootPromise.isRejected) {
  9360. agregator.rootPromise._reject(reason);
  9361. }
  9362. });
  9363. };
  9364. InternalPromise.all = function (promises) {
  9365. var newPromise = new InternalPromise();
  9366. var agregator = new FulFillmentAgregator();
  9367. agregator.target = promises.length;
  9368. agregator.rootPromise = newPromise;
  9369. if (promises.length) {
  9370. for (var index = 0; index < promises.length; index++) {
  9371. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9372. }
  9373. }
  9374. else {
  9375. newPromise._resolve([]);
  9376. }
  9377. return newPromise;
  9378. };
  9379. return InternalPromise;
  9380. }());
  9381. /**
  9382. * Helper class that provides a small promise polyfill
  9383. */
  9384. var PromisePolyfill = /** @class */ (function () {
  9385. function PromisePolyfill() {
  9386. }
  9387. /**
  9388. * Static function used to check if the polyfill is required
  9389. * If this is the case then the function will inject the polyfill to window.Promise
  9390. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9391. */
  9392. PromisePolyfill.Apply = function (force) {
  9393. if (force === void 0) { force = false; }
  9394. if (force || typeof Promise === 'undefined') {
  9395. var root = window;
  9396. root.Promise = InternalPromise;
  9397. }
  9398. };
  9399. return PromisePolyfill;
  9400. }());
  9401. BABYLON.PromisePolyfill = PromisePolyfill;
  9402. })(BABYLON || (BABYLON = {}));
  9403. //# sourceMappingURL=babylon.promise.js.map
  9404. var BABYLON;
  9405. (function (BABYLON) {
  9406. var _AlphaState = /** @class */ (function () {
  9407. /**
  9408. * Initializes the state.
  9409. */
  9410. function _AlphaState() {
  9411. this._isAlphaBlendDirty = false;
  9412. this._isBlendFunctionParametersDirty = false;
  9413. this._isBlendEquationParametersDirty = false;
  9414. this._isBlendConstantsDirty = false;
  9415. this._alphaBlend = false;
  9416. this._blendFunctionParameters = new Array(4);
  9417. this._blendEquationParameters = new Array(2);
  9418. this._blendConstants = new Array(4);
  9419. this.reset();
  9420. }
  9421. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9422. get: function () {
  9423. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9424. },
  9425. enumerable: true,
  9426. configurable: true
  9427. });
  9428. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9429. get: function () {
  9430. return this._alphaBlend;
  9431. },
  9432. set: function (value) {
  9433. if (this._alphaBlend === value) {
  9434. return;
  9435. }
  9436. this._alphaBlend = value;
  9437. this._isAlphaBlendDirty = true;
  9438. },
  9439. enumerable: true,
  9440. configurable: true
  9441. });
  9442. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9443. if (this._blendConstants[0] === r &&
  9444. this._blendConstants[1] === g &&
  9445. this._blendConstants[2] === b &&
  9446. this._blendConstants[3] === a) {
  9447. return;
  9448. }
  9449. this._blendConstants[0] = r;
  9450. this._blendConstants[1] = g;
  9451. this._blendConstants[2] = b;
  9452. this._blendConstants[3] = a;
  9453. this._isBlendConstantsDirty = true;
  9454. };
  9455. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9456. if (this._blendFunctionParameters[0] === value0 &&
  9457. this._blendFunctionParameters[1] === value1 &&
  9458. this._blendFunctionParameters[2] === value2 &&
  9459. this._blendFunctionParameters[3] === value3) {
  9460. return;
  9461. }
  9462. this._blendFunctionParameters[0] = value0;
  9463. this._blendFunctionParameters[1] = value1;
  9464. this._blendFunctionParameters[2] = value2;
  9465. this._blendFunctionParameters[3] = value3;
  9466. this._isBlendFunctionParametersDirty = true;
  9467. };
  9468. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9469. if (this._blendEquationParameters[0] === rgb &&
  9470. this._blendEquationParameters[1] === alpha) {
  9471. return;
  9472. }
  9473. this._blendEquationParameters[0] = rgb;
  9474. this._blendEquationParameters[1] = alpha;
  9475. this._isBlendEquationParametersDirty = true;
  9476. };
  9477. _AlphaState.prototype.reset = function () {
  9478. this._alphaBlend = false;
  9479. this._blendFunctionParameters[0] = null;
  9480. this._blendFunctionParameters[1] = null;
  9481. this._blendFunctionParameters[2] = null;
  9482. this._blendFunctionParameters[3] = null;
  9483. this._blendEquationParameters[0] = null;
  9484. this._blendEquationParameters[1] = null;
  9485. this._blendConstants[0] = null;
  9486. this._blendConstants[1] = null;
  9487. this._blendConstants[2] = null;
  9488. this._blendConstants[3] = null;
  9489. this._isAlphaBlendDirty = true;
  9490. this._isBlendFunctionParametersDirty = false;
  9491. this._isBlendEquationParametersDirty = false;
  9492. this._isBlendConstantsDirty = false;
  9493. };
  9494. _AlphaState.prototype.apply = function (gl) {
  9495. if (!this.isDirty) {
  9496. return;
  9497. }
  9498. // Alpha blend
  9499. if (this._isAlphaBlendDirty) {
  9500. if (this._alphaBlend) {
  9501. gl.enable(gl.BLEND);
  9502. }
  9503. else {
  9504. gl.disable(gl.BLEND);
  9505. }
  9506. this._isAlphaBlendDirty = false;
  9507. }
  9508. // Alpha function
  9509. if (this._isBlendFunctionParametersDirty) {
  9510. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9511. this._isBlendFunctionParametersDirty = false;
  9512. }
  9513. // Alpha equation
  9514. if (this._isBlendEquationParametersDirty) {
  9515. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9516. this._isBlendEquationParametersDirty = false;
  9517. }
  9518. // Constants
  9519. if (this._isBlendConstantsDirty) {
  9520. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9521. this._isBlendConstantsDirty = false;
  9522. }
  9523. };
  9524. return _AlphaState;
  9525. }());
  9526. BABYLON._AlphaState = _AlphaState;
  9527. })(BABYLON || (BABYLON = {}));
  9528. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9529. var BABYLON;
  9530. (function (BABYLON) {
  9531. var _DepthCullingState = /** @class */ (function () {
  9532. /**
  9533. * Initializes the state.
  9534. */
  9535. function _DepthCullingState() {
  9536. this._isDepthTestDirty = false;
  9537. this._isDepthMaskDirty = false;
  9538. this._isDepthFuncDirty = false;
  9539. this._isCullFaceDirty = false;
  9540. this._isCullDirty = false;
  9541. this._isZOffsetDirty = false;
  9542. this._isFrontFaceDirty = false;
  9543. this.reset();
  9544. }
  9545. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9546. get: function () {
  9547. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9548. },
  9549. enumerable: true,
  9550. configurable: true
  9551. });
  9552. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9553. get: function () {
  9554. return this._zOffset;
  9555. },
  9556. set: function (value) {
  9557. if (this._zOffset === value) {
  9558. return;
  9559. }
  9560. this._zOffset = value;
  9561. this._isZOffsetDirty = true;
  9562. },
  9563. enumerable: true,
  9564. configurable: true
  9565. });
  9566. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9567. get: function () {
  9568. return this._cullFace;
  9569. },
  9570. set: function (value) {
  9571. if (this._cullFace === value) {
  9572. return;
  9573. }
  9574. this._cullFace = value;
  9575. this._isCullFaceDirty = true;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9581. get: function () {
  9582. return this._cull;
  9583. },
  9584. set: function (value) {
  9585. if (this._cull === value) {
  9586. return;
  9587. }
  9588. this._cull = value;
  9589. this._isCullDirty = true;
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9595. get: function () {
  9596. return this._depthFunc;
  9597. },
  9598. set: function (value) {
  9599. if (this._depthFunc === value) {
  9600. return;
  9601. }
  9602. this._depthFunc = value;
  9603. this._isDepthFuncDirty = true;
  9604. },
  9605. enumerable: true,
  9606. configurable: true
  9607. });
  9608. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9609. get: function () {
  9610. return this._depthMask;
  9611. },
  9612. set: function (value) {
  9613. if (this._depthMask === value) {
  9614. return;
  9615. }
  9616. this._depthMask = value;
  9617. this._isDepthMaskDirty = true;
  9618. },
  9619. enumerable: true,
  9620. configurable: true
  9621. });
  9622. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9623. get: function () {
  9624. return this._depthTest;
  9625. },
  9626. set: function (value) {
  9627. if (this._depthTest === value) {
  9628. return;
  9629. }
  9630. this._depthTest = value;
  9631. this._isDepthTestDirty = true;
  9632. },
  9633. enumerable: true,
  9634. configurable: true
  9635. });
  9636. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9637. get: function () {
  9638. return this._frontFace;
  9639. },
  9640. set: function (value) {
  9641. if (this._frontFace === value) {
  9642. return;
  9643. }
  9644. this._frontFace = value;
  9645. this._isFrontFaceDirty = true;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. _DepthCullingState.prototype.reset = function () {
  9651. this._depthMask = true;
  9652. this._depthTest = true;
  9653. this._depthFunc = null;
  9654. this._cullFace = null;
  9655. this._cull = null;
  9656. this._zOffset = 0;
  9657. this._frontFace = null;
  9658. this._isDepthTestDirty = true;
  9659. this._isDepthMaskDirty = true;
  9660. this._isDepthFuncDirty = false;
  9661. this._isCullFaceDirty = false;
  9662. this._isCullDirty = false;
  9663. this._isZOffsetDirty = false;
  9664. this._isFrontFaceDirty = false;
  9665. };
  9666. _DepthCullingState.prototype.apply = function (gl) {
  9667. if (!this.isDirty) {
  9668. return;
  9669. }
  9670. // Cull
  9671. if (this._isCullDirty) {
  9672. if (this.cull) {
  9673. gl.enable(gl.CULL_FACE);
  9674. }
  9675. else {
  9676. gl.disable(gl.CULL_FACE);
  9677. }
  9678. this._isCullDirty = false;
  9679. }
  9680. // Cull face
  9681. if (this._isCullFaceDirty) {
  9682. gl.cullFace(this.cullFace);
  9683. this._isCullFaceDirty = false;
  9684. }
  9685. // Depth mask
  9686. if (this._isDepthMaskDirty) {
  9687. gl.depthMask(this.depthMask);
  9688. this._isDepthMaskDirty = false;
  9689. }
  9690. // Depth test
  9691. if (this._isDepthTestDirty) {
  9692. if (this.depthTest) {
  9693. gl.enable(gl.DEPTH_TEST);
  9694. }
  9695. else {
  9696. gl.disable(gl.DEPTH_TEST);
  9697. }
  9698. this._isDepthTestDirty = false;
  9699. }
  9700. // Depth func
  9701. if (this._isDepthFuncDirty) {
  9702. gl.depthFunc(this.depthFunc);
  9703. this._isDepthFuncDirty = false;
  9704. }
  9705. // zOffset
  9706. if (this._isZOffsetDirty) {
  9707. if (this.zOffset) {
  9708. gl.enable(gl.POLYGON_OFFSET_FILL);
  9709. gl.polygonOffset(this.zOffset, 0);
  9710. }
  9711. else {
  9712. gl.disable(gl.POLYGON_OFFSET_FILL);
  9713. }
  9714. this._isZOffsetDirty = false;
  9715. }
  9716. // Front face
  9717. if (this._isFrontFaceDirty) {
  9718. gl.frontFace(this.frontFace);
  9719. this._isFrontFaceDirty = false;
  9720. }
  9721. };
  9722. return _DepthCullingState;
  9723. }());
  9724. BABYLON._DepthCullingState = _DepthCullingState;
  9725. })(BABYLON || (BABYLON = {}));
  9726. //# sourceMappingURL=babylon.depthCullingState.js.map
  9727. var BABYLON;
  9728. (function (BABYLON) {
  9729. var _StencilState = /** @class */ (function () {
  9730. function _StencilState() {
  9731. this._isStencilTestDirty = false;
  9732. this._isStencilMaskDirty = false;
  9733. this._isStencilFuncDirty = false;
  9734. this._isStencilOpDirty = false;
  9735. this.reset();
  9736. }
  9737. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9738. get: function () {
  9739. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9740. },
  9741. enumerable: true,
  9742. configurable: true
  9743. });
  9744. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9745. get: function () {
  9746. return this._stencilFunc;
  9747. },
  9748. set: function (value) {
  9749. if (this._stencilFunc === value) {
  9750. return;
  9751. }
  9752. this._stencilFunc = value;
  9753. this._isStencilFuncDirty = true;
  9754. },
  9755. enumerable: true,
  9756. configurable: true
  9757. });
  9758. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9759. get: function () {
  9760. return this._stencilFuncRef;
  9761. },
  9762. set: function (value) {
  9763. if (this._stencilFuncRef === value) {
  9764. return;
  9765. }
  9766. this._stencilFuncRef = value;
  9767. this._isStencilFuncDirty = true;
  9768. },
  9769. enumerable: true,
  9770. configurable: true
  9771. });
  9772. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9773. get: function () {
  9774. return this._stencilFuncMask;
  9775. },
  9776. set: function (value) {
  9777. if (this._stencilFuncMask === value) {
  9778. return;
  9779. }
  9780. this._stencilFuncMask = value;
  9781. this._isStencilFuncDirty = true;
  9782. },
  9783. enumerable: true,
  9784. configurable: true
  9785. });
  9786. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9787. get: function () {
  9788. return this._stencilOpStencilFail;
  9789. },
  9790. set: function (value) {
  9791. if (this._stencilOpStencilFail === value) {
  9792. return;
  9793. }
  9794. this._stencilOpStencilFail = value;
  9795. this._isStencilOpDirty = true;
  9796. },
  9797. enumerable: true,
  9798. configurable: true
  9799. });
  9800. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9801. get: function () {
  9802. return this._stencilOpDepthFail;
  9803. },
  9804. set: function (value) {
  9805. if (this._stencilOpDepthFail === value) {
  9806. return;
  9807. }
  9808. this._stencilOpDepthFail = value;
  9809. this._isStencilOpDirty = true;
  9810. },
  9811. enumerable: true,
  9812. configurable: true
  9813. });
  9814. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9815. get: function () {
  9816. return this._stencilOpStencilDepthPass;
  9817. },
  9818. set: function (value) {
  9819. if (this._stencilOpStencilDepthPass === value) {
  9820. return;
  9821. }
  9822. this._stencilOpStencilDepthPass = value;
  9823. this._isStencilOpDirty = true;
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9829. get: function () {
  9830. return this._stencilMask;
  9831. },
  9832. set: function (value) {
  9833. if (this._stencilMask === value) {
  9834. return;
  9835. }
  9836. this._stencilMask = value;
  9837. this._isStencilMaskDirty = true;
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9843. get: function () {
  9844. return this._stencilTest;
  9845. },
  9846. set: function (value) {
  9847. if (this._stencilTest === value) {
  9848. return;
  9849. }
  9850. this._stencilTest = value;
  9851. this._isStencilTestDirty = true;
  9852. },
  9853. enumerable: true,
  9854. configurable: true
  9855. });
  9856. _StencilState.prototype.reset = function () {
  9857. this._stencilTest = false;
  9858. this._stencilMask = 0xFF;
  9859. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9860. this._stencilFuncRef = 1;
  9861. this._stencilFuncMask = 0xFF;
  9862. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9863. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9864. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9865. this._isStencilTestDirty = true;
  9866. this._isStencilMaskDirty = true;
  9867. this._isStencilFuncDirty = true;
  9868. this._isStencilOpDirty = true;
  9869. };
  9870. _StencilState.prototype.apply = function (gl) {
  9871. if (!this.isDirty) {
  9872. return;
  9873. }
  9874. // Stencil test
  9875. if (this._isStencilTestDirty) {
  9876. if (this.stencilTest) {
  9877. gl.enable(gl.STENCIL_TEST);
  9878. }
  9879. else {
  9880. gl.disable(gl.STENCIL_TEST);
  9881. }
  9882. this._isStencilTestDirty = false;
  9883. }
  9884. // Stencil mask
  9885. if (this._isStencilMaskDirty) {
  9886. gl.stencilMask(this.stencilMask);
  9887. this._isStencilMaskDirty = false;
  9888. }
  9889. // Stencil func
  9890. if (this._isStencilFuncDirty) {
  9891. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9892. this._isStencilFuncDirty = false;
  9893. }
  9894. // Stencil op
  9895. if (this._isStencilOpDirty) {
  9896. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9897. this._isStencilOpDirty = false;
  9898. }
  9899. };
  9900. return _StencilState;
  9901. }());
  9902. BABYLON._StencilState = _StencilState;
  9903. })(BABYLON || (BABYLON = {}));
  9904. //# sourceMappingURL=babylon.stencilState.js.map
  9905. var BABYLON;
  9906. (function (BABYLON) {
  9907. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9908. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9909. };
  9910. var compileRawShader = function (gl, source, type) {
  9911. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9912. gl.shaderSource(shader, source);
  9913. gl.compileShader(shader);
  9914. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9915. var log = gl.getShaderInfoLog(shader);
  9916. if (log) {
  9917. throw new Error(log);
  9918. }
  9919. }
  9920. if (!shader) {
  9921. throw new Error("Something went wrong while compile the shader.");
  9922. }
  9923. return shader;
  9924. };
  9925. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9926. var magFilter = gl.NEAREST;
  9927. var minFilter = gl.NEAREST;
  9928. switch (samplingMode) {
  9929. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9930. magFilter = gl.LINEAR;
  9931. if (generateMipMaps) {
  9932. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9933. }
  9934. else {
  9935. minFilter = gl.LINEAR;
  9936. }
  9937. break;
  9938. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9939. magFilter = gl.LINEAR;
  9940. if (generateMipMaps) {
  9941. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9942. }
  9943. else {
  9944. minFilter = gl.LINEAR;
  9945. }
  9946. break;
  9947. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9948. magFilter = gl.NEAREST;
  9949. if (generateMipMaps) {
  9950. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9951. }
  9952. else {
  9953. minFilter = gl.NEAREST;
  9954. }
  9955. break;
  9956. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9957. magFilter = gl.NEAREST;
  9958. if (generateMipMaps) {
  9959. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9960. }
  9961. else {
  9962. minFilter = gl.NEAREST;
  9963. }
  9964. break;
  9965. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9966. magFilter = gl.NEAREST;
  9967. if (generateMipMaps) {
  9968. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9969. }
  9970. else {
  9971. minFilter = gl.LINEAR;
  9972. }
  9973. break;
  9974. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9975. magFilter = gl.NEAREST;
  9976. if (generateMipMaps) {
  9977. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9978. }
  9979. else {
  9980. minFilter = gl.LINEAR;
  9981. }
  9982. break;
  9983. case BABYLON.Texture.NEAREST_LINEAR:
  9984. magFilter = gl.NEAREST;
  9985. minFilter = gl.LINEAR;
  9986. break;
  9987. case BABYLON.Texture.NEAREST_NEAREST:
  9988. magFilter = gl.NEAREST;
  9989. minFilter = gl.NEAREST;
  9990. break;
  9991. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9992. magFilter = gl.LINEAR;
  9993. if (generateMipMaps) {
  9994. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9995. }
  9996. else {
  9997. minFilter = gl.NEAREST;
  9998. }
  9999. break;
  10000. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10001. magFilter = gl.LINEAR;
  10002. if (generateMipMaps) {
  10003. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10004. }
  10005. else {
  10006. minFilter = gl.NEAREST;
  10007. }
  10008. break;
  10009. case BABYLON.Texture.LINEAR_LINEAR:
  10010. magFilter = gl.LINEAR;
  10011. minFilter = gl.LINEAR;
  10012. break;
  10013. case BABYLON.Texture.LINEAR_NEAREST:
  10014. magFilter = gl.LINEAR;
  10015. minFilter = gl.NEAREST;
  10016. break;
  10017. }
  10018. return {
  10019. min: minFilter,
  10020. mag: magFilter
  10021. };
  10022. };
  10023. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10024. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10025. var img;
  10026. var onload = function () {
  10027. loadedImages[index] = img;
  10028. loadedImages._internalCount++;
  10029. if (scene) {
  10030. scene._removePendingData(img);
  10031. }
  10032. if (loadedImages._internalCount === 6) {
  10033. onfinish(loadedImages);
  10034. }
  10035. };
  10036. var onerror = function (message, exception) {
  10037. if (scene) {
  10038. scene._removePendingData(img);
  10039. }
  10040. if (onErrorCallBack) {
  10041. onErrorCallBack(message, exception);
  10042. }
  10043. };
  10044. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10045. if (scene) {
  10046. scene._addPendingData(img);
  10047. }
  10048. };
  10049. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10050. if (onError === void 0) { onError = null; }
  10051. var loadedImages = [];
  10052. loadedImages._internalCount = 0;
  10053. for (var index = 0; index < 6; index++) {
  10054. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10055. }
  10056. };
  10057. var BufferPointer = /** @class */ (function () {
  10058. function BufferPointer() {
  10059. }
  10060. return BufferPointer;
  10061. }());
  10062. var InstancingAttributeInfo = /** @class */ (function () {
  10063. function InstancingAttributeInfo() {
  10064. }
  10065. return InstancingAttributeInfo;
  10066. }());
  10067. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10068. /**
  10069. * Define options used to create a render target texture
  10070. */
  10071. var RenderTargetCreationOptions = /** @class */ (function () {
  10072. function RenderTargetCreationOptions() {
  10073. }
  10074. return RenderTargetCreationOptions;
  10075. }());
  10076. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10077. /**
  10078. * Regroup several parameters relative to the browser in use
  10079. */
  10080. var EngineCapabilities = /** @class */ (function () {
  10081. function EngineCapabilities() {
  10082. }
  10083. return EngineCapabilities;
  10084. }());
  10085. BABYLON.EngineCapabilities = EngineCapabilities;
  10086. /**
  10087. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10088. */
  10089. var Engine = /** @class */ (function () {
  10090. /**
  10091. * @constructor
  10092. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10093. * @param antialias defines enable antialiasing (default: false)
  10094. * @param options defines further options to be sent to the getContext() function
  10095. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10096. */
  10097. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10098. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10099. var _this = this;
  10100. // Public members
  10101. this.forcePOTTextures = false;
  10102. this.isFullscreen = false;
  10103. this.isPointerLock = false;
  10104. this.cullBackFaces = true;
  10105. this.renderEvenInBackground = true;
  10106. this.preventCacheWipeBetweenFrames = false;
  10107. // To enable/disable IDB support and avoid XHR on .manifest
  10108. this.enableOfflineSupport = false;
  10109. this.scenes = new Array();
  10110. this.postProcesses = new Array();
  10111. // Observables
  10112. /**
  10113. * Observable event triggered each time the rendering canvas is resized
  10114. */
  10115. this.onResizeObservable = new BABYLON.Observable();
  10116. /**
  10117. * Observable event triggered each time the canvas loses focus
  10118. */
  10119. this.onCanvasBlurObservable = new BABYLON.Observable();
  10120. /**
  10121. * Observable event triggered each time the canvas gains focus
  10122. */
  10123. this.onCanvasFocusObservable = new BABYLON.Observable();
  10124. /**
  10125. * Observable event triggered each time the canvas receives pointerout event
  10126. */
  10127. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10128. /**
  10129. * Observable event triggered before each texture is initialized
  10130. */
  10131. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10132. //WebVR
  10133. this._vrDisplay = undefined;
  10134. this._vrSupported = false;
  10135. this._vrExclusivePointerMode = false;
  10136. // Uniform buffers list
  10137. this.disableUniformBuffers = false;
  10138. this._uniformBuffers = new Array();
  10139. // Observables
  10140. /**
  10141. * Observable raised when the engine begins a new frame
  10142. */
  10143. this.onBeginFrameObservable = new BABYLON.Observable();
  10144. /**
  10145. * Observable raised when the engine ends the current frame
  10146. */
  10147. this.onEndFrameObservable = new BABYLON.Observable();
  10148. /**
  10149. * Observable raised when the engine is about to compile a shader
  10150. */
  10151. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10152. /**
  10153. * Observable raised when the engine has jsut compiled a shader
  10154. */
  10155. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10156. this._windowIsBackground = false;
  10157. this._webGLVersion = 1.0;
  10158. this._badOS = false;
  10159. this._badDesktopOS = false;
  10160. /**
  10161. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10162. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10163. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10164. */
  10165. this.disableTextureBindingOptimization = false;
  10166. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10167. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10168. this.onVRRequestPresentStart = new BABYLON.Observable();
  10169. this._colorWrite = true;
  10170. this._drawCalls = new BABYLON.PerfCounter();
  10171. this._textureCollisions = new BABYLON.PerfCounter();
  10172. this._renderingQueueLaunched = false;
  10173. this._activeRenderLoops = new Array();
  10174. // Deterministic lockstepMaxSteps
  10175. this._deterministicLockstep = false;
  10176. this._lockstepMaxSteps = 4;
  10177. // Lost context
  10178. this.onContextLostObservable = new BABYLON.Observable();
  10179. this.onContextRestoredObservable = new BABYLON.Observable();
  10180. this._contextWasLost = false;
  10181. this._doNotHandleContextLost = false;
  10182. // FPS
  10183. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10184. this._fps = 60;
  10185. this._deltaTime = 0;
  10186. /**
  10187. * Turn this value on if you want to pause FPS computation when in background
  10188. */
  10189. this.disablePerformanceMonitorInBackground = false;
  10190. // States
  10191. this._depthCullingState = new BABYLON._DepthCullingState();
  10192. this._stencilState = new BABYLON._StencilState();
  10193. this._alphaState = new BABYLON._AlphaState();
  10194. this._alphaMode = Engine.ALPHA_DISABLE;
  10195. // Cache
  10196. this._internalTexturesCache = new Array();
  10197. this._activeChannel = 0;
  10198. this._currentTextureChannel = -1;
  10199. this._boundTexturesCache = {};
  10200. this._compiledEffects = {};
  10201. this._vertexAttribArraysEnabled = [];
  10202. this._uintIndicesCurrentlySet = false;
  10203. this._currentBoundBuffer = new Array();
  10204. this._currentBufferPointers = new Array();
  10205. this._currentInstanceLocations = new Array();
  10206. this._currentInstanceBuffers = new Array();
  10207. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10208. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10209. this._vaoRecordInProgress = false;
  10210. this._mustWipeVertexAttributes = false;
  10211. this._nextFreeTextureSlots = new Array();
  10212. this._maxSimultaneousTextures = 0;
  10213. this._activeRequests = new Array();
  10214. // Hardware supported Compressed Textures
  10215. this._texturesSupported = new Array();
  10216. this._onVRFullScreenTriggered = function () {
  10217. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10218. //get the old size before we change
  10219. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10220. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10221. //get the width and height, change the render size
  10222. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10223. _this.setHardwareScalingLevel(1);
  10224. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10225. }
  10226. else {
  10227. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10228. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10229. }
  10230. };
  10231. this._boundUniforms = {};
  10232. // Register promises
  10233. BABYLON.PromisePolyfill.Apply();
  10234. var canvas = null;
  10235. Engine.Instances.push(this);
  10236. if (!canvasOrContext) {
  10237. return;
  10238. }
  10239. options = options || {};
  10240. if (canvasOrContext.getContext) {
  10241. canvas = canvasOrContext;
  10242. this._renderingCanvas = canvas;
  10243. if (antialias != null) {
  10244. options.antialias = antialias;
  10245. }
  10246. if (options.deterministicLockstep === undefined) {
  10247. options.deterministicLockstep = false;
  10248. }
  10249. if (options.lockstepMaxSteps === undefined) {
  10250. options.lockstepMaxSteps = 4;
  10251. }
  10252. if (options.preserveDrawingBuffer === undefined) {
  10253. options.preserveDrawingBuffer = false;
  10254. }
  10255. if (options.audioEngine === undefined) {
  10256. options.audioEngine = true;
  10257. }
  10258. if (options.stencil === undefined) {
  10259. options.stencil = true;
  10260. }
  10261. this._deterministicLockstep = options.deterministicLockstep;
  10262. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10263. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10264. // Exceptions
  10265. if (navigator && navigator.userAgent) {
  10266. var ua = navigator.userAgent;
  10267. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10268. var exception = _a[_i];
  10269. var key = exception.key;
  10270. var targets = exception.targets;
  10271. if (ua.indexOf(key) > -1) {
  10272. if (exception.capture && exception.captureConstraint) {
  10273. var capture = exception.capture;
  10274. var constraint = exception.captureConstraint;
  10275. var regex = new RegExp(capture);
  10276. var matches = regex.exec(ua);
  10277. if (matches && matches.length > 0) {
  10278. var capturedValue = parseInt(matches[matches.length - 1]);
  10279. if (capturedValue >= constraint) {
  10280. continue;
  10281. }
  10282. }
  10283. }
  10284. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10285. var target = targets_1[_b];
  10286. switch (target) {
  10287. case "uniformBuffer":
  10288. this.disableUniformBuffers = true;
  10289. break;
  10290. case "textureBindingOptimization":
  10291. this.disableTextureBindingOptimization = true;
  10292. break;
  10293. }
  10294. }
  10295. break;
  10296. }
  10297. }
  10298. }
  10299. // GL
  10300. if (!options.disableWebGL2Support) {
  10301. try {
  10302. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10303. if (this._gl) {
  10304. this._webGLVersion = 2.0;
  10305. }
  10306. }
  10307. catch (e) {
  10308. // Do nothing
  10309. }
  10310. }
  10311. if (!this._gl) {
  10312. if (!canvas) {
  10313. throw new Error("The provided canvas is null or undefined.");
  10314. }
  10315. try {
  10316. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10317. }
  10318. catch (e) {
  10319. throw new Error("WebGL not supported");
  10320. }
  10321. }
  10322. if (!this._gl) {
  10323. throw new Error("WebGL not supported");
  10324. }
  10325. this._onCanvasFocus = function () {
  10326. _this.onCanvasFocusObservable.notifyObservers(_this);
  10327. };
  10328. this._onCanvasBlur = function () {
  10329. _this.onCanvasBlurObservable.notifyObservers(_this);
  10330. };
  10331. canvas.addEventListener("focus", this._onCanvasFocus);
  10332. canvas.addEventListener("blur", this._onCanvasBlur);
  10333. this._onBlur = function () {
  10334. if (_this.disablePerformanceMonitorInBackground) {
  10335. _this._performanceMonitor.disable();
  10336. }
  10337. _this._windowIsBackground = true;
  10338. };
  10339. this._onFocus = function () {
  10340. if (_this.disablePerformanceMonitorInBackground) {
  10341. _this._performanceMonitor.enable();
  10342. }
  10343. _this._windowIsBackground = false;
  10344. };
  10345. this._onCanvasPointerOut = function () {
  10346. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10347. };
  10348. window.addEventListener("blur", this._onBlur);
  10349. window.addEventListener("focus", this._onFocus);
  10350. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10351. // Context lost
  10352. if (!this._doNotHandleContextLost) {
  10353. this._onContextLost = function (evt) {
  10354. evt.preventDefault();
  10355. _this._contextWasLost = true;
  10356. BABYLON.Tools.Warn("WebGL context lost.");
  10357. _this.onContextLostObservable.notifyObservers(_this);
  10358. };
  10359. this._onContextRestored = function (evt) {
  10360. // Adding a timeout to avoid race condition at browser level
  10361. setTimeout(function () {
  10362. // Rebuild gl context
  10363. _this._initGLContext();
  10364. // Rebuild effects
  10365. _this._rebuildEffects();
  10366. // Rebuild textures
  10367. _this._rebuildInternalTextures();
  10368. // Rebuild buffers
  10369. _this._rebuildBuffers();
  10370. // Cache
  10371. _this.wipeCaches(true);
  10372. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10373. _this.onContextRestoredObservable.notifyObservers(_this);
  10374. _this._contextWasLost = false;
  10375. }, 0);
  10376. };
  10377. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10378. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10379. }
  10380. }
  10381. else {
  10382. this._gl = canvasOrContext;
  10383. this._renderingCanvas = this._gl.canvas;
  10384. if (this._gl.renderbufferStorageMultisample) {
  10385. this._webGLVersion = 2.0;
  10386. }
  10387. options.stencil = this._gl.getContextAttributes().stencil;
  10388. }
  10389. // Viewport
  10390. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10391. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10392. this.resize();
  10393. this._isStencilEnable = options.stencil ? true : false;
  10394. this._initGLContext();
  10395. if (canvas) {
  10396. // Fullscreen
  10397. this._onFullscreenChange = function () {
  10398. if (document.fullscreen !== undefined) {
  10399. _this.isFullscreen = document.fullscreen;
  10400. }
  10401. else if (document.mozFullScreen !== undefined) {
  10402. _this.isFullscreen = document.mozFullScreen;
  10403. }
  10404. else if (document.webkitIsFullScreen !== undefined) {
  10405. _this.isFullscreen = document.webkitIsFullScreen;
  10406. }
  10407. else if (document.msIsFullScreen !== undefined) {
  10408. _this.isFullscreen = document.msIsFullScreen;
  10409. }
  10410. // Pointer lock
  10411. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10412. canvas.requestPointerLock = canvas.requestPointerLock ||
  10413. canvas.msRequestPointerLock ||
  10414. canvas.mozRequestPointerLock ||
  10415. canvas.webkitRequestPointerLock;
  10416. if (canvas.requestPointerLock) {
  10417. canvas.requestPointerLock();
  10418. }
  10419. }
  10420. };
  10421. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10422. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10423. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10424. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10425. // Pointer lock
  10426. this._onPointerLockChange = function () {
  10427. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10428. document.webkitPointerLockElement === canvas ||
  10429. document.msPointerLockElement === canvas ||
  10430. document.pointerLockElement === canvas);
  10431. };
  10432. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10433. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10434. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10435. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10436. this._onVRDisplayPointerRestricted = function () {
  10437. if (canvas) {
  10438. canvas.requestPointerLock();
  10439. }
  10440. };
  10441. this._onVRDisplayPointerUnrestricted = function () {
  10442. document.exitPointerLock();
  10443. };
  10444. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10445. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10446. }
  10447. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10448. Engine.audioEngine = new BABYLON.AudioEngine();
  10449. }
  10450. // Prepare buffer pointers
  10451. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10452. this._currentBufferPointers[i] = new BufferPointer();
  10453. }
  10454. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10455. // Load WebVR Devices
  10456. if (options.autoEnableWebVR) {
  10457. this.initWebVR();
  10458. }
  10459. // Detect if we are running on a faulty buggy OS.
  10460. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10461. // Detect if we are running on a faulty buggy desktop OS.
  10462. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10463. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10464. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10465. }
  10466. Object.defineProperty(Engine, "LastCreatedEngine", {
  10467. get: function () {
  10468. if (Engine.Instances.length === 0) {
  10469. return null;
  10470. }
  10471. return Engine.Instances[Engine.Instances.length - 1];
  10472. },
  10473. enumerable: true,
  10474. configurable: true
  10475. });
  10476. Object.defineProperty(Engine, "LastCreatedScene", {
  10477. get: function () {
  10478. var lastCreatedEngine = Engine.LastCreatedEngine;
  10479. if (!lastCreatedEngine) {
  10480. return null;
  10481. }
  10482. if (lastCreatedEngine.scenes.length === 0) {
  10483. return null;
  10484. }
  10485. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10486. },
  10487. enumerable: true,
  10488. configurable: true
  10489. });
  10490. /**
  10491. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10492. */
  10493. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10494. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10495. var engine = Engine.Instances[engineIndex];
  10496. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10497. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10498. }
  10499. }
  10500. };
  10501. Object.defineProperty(Engine, "NEVER", {
  10502. get: function () {
  10503. return Engine._NEVER;
  10504. },
  10505. enumerable: true,
  10506. configurable: true
  10507. });
  10508. Object.defineProperty(Engine, "ALWAYS", {
  10509. get: function () {
  10510. return Engine._ALWAYS;
  10511. },
  10512. enumerable: true,
  10513. configurable: true
  10514. });
  10515. Object.defineProperty(Engine, "LESS", {
  10516. get: function () {
  10517. return Engine._LESS;
  10518. },
  10519. enumerable: true,
  10520. configurable: true
  10521. });
  10522. Object.defineProperty(Engine, "EQUAL", {
  10523. get: function () {
  10524. return Engine._EQUAL;
  10525. },
  10526. enumerable: true,
  10527. configurable: true
  10528. });
  10529. Object.defineProperty(Engine, "LEQUAL", {
  10530. get: function () {
  10531. return Engine._LEQUAL;
  10532. },
  10533. enumerable: true,
  10534. configurable: true
  10535. });
  10536. Object.defineProperty(Engine, "GREATER", {
  10537. get: function () {
  10538. return Engine._GREATER;
  10539. },
  10540. enumerable: true,
  10541. configurable: true
  10542. });
  10543. Object.defineProperty(Engine, "GEQUAL", {
  10544. get: function () {
  10545. return Engine._GEQUAL;
  10546. },
  10547. enumerable: true,
  10548. configurable: true
  10549. });
  10550. Object.defineProperty(Engine, "NOTEQUAL", {
  10551. get: function () {
  10552. return Engine._NOTEQUAL;
  10553. },
  10554. enumerable: true,
  10555. configurable: true
  10556. });
  10557. Object.defineProperty(Engine, "KEEP", {
  10558. get: function () {
  10559. return Engine._KEEP;
  10560. },
  10561. enumerable: true,
  10562. configurable: true
  10563. });
  10564. Object.defineProperty(Engine, "REPLACE", {
  10565. get: function () {
  10566. return Engine._REPLACE;
  10567. },
  10568. enumerable: true,
  10569. configurable: true
  10570. });
  10571. Object.defineProperty(Engine, "INCR", {
  10572. get: function () {
  10573. return Engine._INCR;
  10574. },
  10575. enumerable: true,
  10576. configurable: true
  10577. });
  10578. Object.defineProperty(Engine, "DECR", {
  10579. get: function () {
  10580. return Engine._DECR;
  10581. },
  10582. enumerable: true,
  10583. configurable: true
  10584. });
  10585. Object.defineProperty(Engine, "INVERT", {
  10586. get: function () {
  10587. return Engine._INVERT;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. Object.defineProperty(Engine, "INCR_WRAP", {
  10593. get: function () {
  10594. return Engine._INCR_WRAP;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. Object.defineProperty(Engine, "DECR_WRAP", {
  10600. get: function () {
  10601. return Engine._DECR_WRAP;
  10602. },
  10603. enumerable: true,
  10604. configurable: true
  10605. });
  10606. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10607. get: function () {
  10608. return Engine._ALPHA_DISABLE;
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10614. get: function () {
  10615. return Engine._ALPHA_ONEONE;
  10616. },
  10617. enumerable: true,
  10618. configurable: true
  10619. });
  10620. Object.defineProperty(Engine, "ALPHA_ADD", {
  10621. get: function () {
  10622. return Engine._ALPHA_ADD;
  10623. },
  10624. enumerable: true,
  10625. configurable: true
  10626. });
  10627. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10628. get: function () {
  10629. return Engine._ALPHA_COMBINE;
  10630. },
  10631. enumerable: true,
  10632. configurable: true
  10633. });
  10634. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10635. get: function () {
  10636. return Engine._ALPHA_SUBTRACT;
  10637. },
  10638. enumerable: true,
  10639. configurable: true
  10640. });
  10641. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10642. get: function () {
  10643. return Engine._ALPHA_MULTIPLY;
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10649. get: function () {
  10650. return Engine._ALPHA_MAXIMIZED;
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10656. get: function () {
  10657. return Engine._ALPHA_PREMULTIPLIED;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10663. get: function () {
  10664. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10670. get: function () {
  10671. return Engine._ALPHA_INTERPOLATE;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10677. get: function () {
  10678. return Engine._ALPHA_SCREENMODE;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10684. get: function () {
  10685. return Engine._DELAYLOADSTATE_NONE;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10691. get: function () {
  10692. return Engine._DELAYLOADSTATE_LOADED;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10698. get: function () {
  10699. return Engine._DELAYLOADSTATE_LOADING;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10705. get: function () {
  10706. return Engine._DELAYLOADSTATE_NOTLOADED;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10712. get: function () {
  10713. return Engine._TEXTUREFORMAT_ALPHA;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10719. get: function () {
  10720. return Engine._TEXTUREFORMAT_LUMINANCE;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10726. get: function () {
  10727. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10733. get: function () {
  10734. return Engine._TEXTUREFORMAT_RGB;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10740. get: function () {
  10741. return Engine._TEXTUREFORMAT_RGBA;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10747. get: function () {
  10748. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10754. get: function () {
  10755. return Engine._TEXTURETYPE_FLOAT;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10761. get: function () {
  10762. return Engine._TEXTURETYPE_HALF_FLOAT;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10768. get: function () {
  10769. return Engine._SCALEMODE_FLOOR;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10775. get: function () {
  10776. return Engine._SCALEMODE_NEAREST;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10782. get: function () {
  10783. return Engine._SCALEMODE_CEILING;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "Version", {
  10789. get: function () {
  10790. return "3.2.0-alpha7";
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10796. get: function () {
  10797. return this._vrExclusivePointerMode;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10803. get: function () {
  10804. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10810. get: function () {
  10811. return this._webGLVersion < 2 || this.forcePOTTextures;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine.prototype, "badOS", {
  10817. get: function () {
  10818. return this._badOS;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10824. get: function () {
  10825. return this._badDesktopOS;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10831. get: function () {
  10832. return this._performanceMonitor;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10838. get: function () {
  10839. return this._texturesSupported;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10845. get: function () {
  10846. return this._textureFormatInUse;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(Engine.prototype, "currentViewport", {
  10852. get: function () {
  10853. return this._cachedViewport;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10859. // Empty texture
  10860. get: function () {
  10861. if (!this._emptyTexture) {
  10862. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10863. }
  10864. return this._emptyTexture;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10870. get: function () {
  10871. if (!this._emptyTexture3D) {
  10872. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10873. }
  10874. return this._emptyTexture3D;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10880. get: function () {
  10881. if (!this._emptyCubeTexture) {
  10882. var faceData = new Uint8Array(4);
  10883. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10884. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10885. }
  10886. return this._emptyCubeTexture;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Engine.prototype._rebuildInternalTextures = function () {
  10892. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10893. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10894. var internalTexture = currentState_1[_i];
  10895. internalTexture._rebuild();
  10896. }
  10897. };
  10898. Engine.prototype._rebuildEffects = function () {
  10899. for (var key in this._compiledEffects) {
  10900. var effect = this._compiledEffects[key];
  10901. effect._prepareEffect();
  10902. }
  10903. BABYLON.Effect.ResetCache();
  10904. };
  10905. Engine.prototype._rebuildBuffers = function () {
  10906. // Index / Vertex
  10907. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10908. var scene = _a[_i];
  10909. scene.resetCachedMaterial();
  10910. scene._rebuildGeometries();
  10911. scene._rebuildTextures();
  10912. }
  10913. // Uniforms
  10914. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10915. var uniformBuffer = _c[_b];
  10916. uniformBuffer._rebuild();
  10917. }
  10918. };
  10919. Engine.prototype._initGLContext = function () {
  10920. // Caps
  10921. this._caps = new EngineCapabilities();
  10922. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10923. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10924. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10925. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10926. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10927. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10928. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10929. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10930. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10931. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10932. // Infos
  10933. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10934. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10935. if (rendererInfo != null) {
  10936. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10937. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10938. }
  10939. if (!this._glVendor) {
  10940. this._glVendor = "Unknown vendor";
  10941. }
  10942. if (!this._glRenderer) {
  10943. this._glRenderer = "Unknown renderer";
  10944. }
  10945. // Constants
  10946. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10947. if (this._gl.RGBA16F !== 0x881A) {
  10948. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10949. }
  10950. if (this._gl.RGBA32F !== 0x8814) {
  10951. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10952. }
  10953. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10954. this._gl.DEPTH24_STENCIL8 = 35056;
  10955. }
  10956. // Extensions
  10957. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10958. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10959. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10960. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10961. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10962. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10963. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10964. 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');
  10965. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10966. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10967. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10968. this._caps.highPrecisionShaderSupported = true;
  10969. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10970. if (this._caps.timerQuery) {
  10971. if (this._webGLVersion === 1) {
  10972. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10973. }
  10974. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10975. }
  10976. // Checks if some of the format renders first to allow the use of webgl inspector.
  10977. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10978. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10979. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10980. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10981. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10982. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10983. if (this._webGLVersion > 1) {
  10984. this._gl.HALF_FLOAT_OES = 0x140B;
  10985. }
  10986. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10987. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10988. // Draw buffers
  10989. if (this._webGLVersion > 1) {
  10990. this._caps.drawBuffersExtension = true;
  10991. }
  10992. else {
  10993. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10994. if (drawBuffersExtension !== null) {
  10995. this._caps.drawBuffersExtension = true;
  10996. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10997. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10998. for (var i = 0; i < 16; i++) {
  10999. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11000. }
  11001. }
  11002. else {
  11003. this._caps.drawBuffersExtension = false;
  11004. }
  11005. }
  11006. // Depth Texture
  11007. if (this._webGLVersion > 1) {
  11008. this._caps.depthTextureExtension = true;
  11009. }
  11010. else {
  11011. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11012. if (depthTextureExtension != null) {
  11013. this._caps.depthTextureExtension = true;
  11014. }
  11015. }
  11016. // Vertex array object
  11017. if (this._webGLVersion > 1) {
  11018. this._caps.vertexArrayObject = true;
  11019. }
  11020. else {
  11021. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11022. if (vertexArrayObjectExtension != null) {
  11023. this._caps.vertexArrayObject = true;
  11024. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11025. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11026. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11027. }
  11028. else {
  11029. this._caps.vertexArrayObject = false;
  11030. }
  11031. }
  11032. // Instances count
  11033. if (this._webGLVersion > 1) {
  11034. this._caps.instancedArrays = true;
  11035. }
  11036. else {
  11037. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11038. if (instanceExtension != null) {
  11039. this._caps.instancedArrays = true;
  11040. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11041. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11042. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11043. }
  11044. else {
  11045. this._caps.instancedArrays = false;
  11046. }
  11047. }
  11048. // Intelligently add supported compressed formats in order to check for.
  11049. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11050. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11051. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11052. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11053. if (this._caps.astc)
  11054. this.texturesSupported.push('-astc.ktx');
  11055. if (this._caps.s3tc)
  11056. this.texturesSupported.push('-dxt.ktx');
  11057. if (this._caps.pvrtc)
  11058. this.texturesSupported.push('-pvrtc.ktx');
  11059. if (this._caps.etc2)
  11060. this.texturesSupported.push('-etc2.ktx');
  11061. if (this._caps.etc1)
  11062. this.texturesSupported.push('-etc1.ktx');
  11063. if (this._gl.getShaderPrecisionFormat) {
  11064. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11065. if (highp) {
  11066. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11067. }
  11068. }
  11069. // Depth buffer
  11070. this.setDepthBuffer(true);
  11071. this.setDepthFunctionToLessOrEqual();
  11072. this.setDepthWrite(true);
  11073. // Texture maps
  11074. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11075. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11076. this._nextFreeTextureSlots.push(slot);
  11077. }
  11078. };
  11079. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11080. get: function () {
  11081. return this._webGLVersion;
  11082. },
  11083. enumerable: true,
  11084. configurable: true
  11085. });
  11086. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11087. /**
  11088. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11089. */
  11090. get: function () {
  11091. return this._isStencilEnable;
  11092. },
  11093. enumerable: true,
  11094. configurable: true
  11095. });
  11096. Engine.prototype._prepareWorkingCanvas = function () {
  11097. if (this._workingCanvas) {
  11098. return;
  11099. }
  11100. this._workingCanvas = document.createElement("canvas");
  11101. var context = this._workingCanvas.getContext("2d");
  11102. if (context) {
  11103. this._workingContext = context;
  11104. }
  11105. };
  11106. Engine.prototype.resetTextureCache = function () {
  11107. for (var key in this._boundTexturesCache) {
  11108. var boundTexture = this._boundTexturesCache[key];
  11109. if (boundTexture) {
  11110. this._removeDesignatedSlot(boundTexture);
  11111. }
  11112. this._boundTexturesCache[key] = null;
  11113. }
  11114. if (!this.disableTextureBindingOptimization) {
  11115. this._nextFreeTextureSlots = [];
  11116. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11117. this._nextFreeTextureSlots.push(slot);
  11118. }
  11119. }
  11120. this._currentTextureChannel = -1;
  11121. };
  11122. Engine.prototype.isDeterministicLockStep = function () {
  11123. return this._deterministicLockstep;
  11124. };
  11125. Engine.prototype.getLockstepMaxSteps = function () {
  11126. return this._lockstepMaxSteps;
  11127. };
  11128. Engine.prototype.getGlInfo = function () {
  11129. return {
  11130. vendor: this._glVendor,
  11131. renderer: this._glRenderer,
  11132. version: this._glVersion
  11133. };
  11134. };
  11135. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11136. if (useScreen === void 0) { useScreen = false; }
  11137. var viewport = camera.viewport;
  11138. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11139. };
  11140. Engine.prototype.getRenderWidth = function (useScreen) {
  11141. if (useScreen === void 0) { useScreen = false; }
  11142. if (!useScreen && this._currentRenderTarget) {
  11143. return this._currentRenderTarget.width;
  11144. }
  11145. return this._gl.drawingBufferWidth;
  11146. };
  11147. Engine.prototype.getRenderHeight = function (useScreen) {
  11148. if (useScreen === void 0) { useScreen = false; }
  11149. if (!useScreen && this._currentRenderTarget) {
  11150. return this._currentRenderTarget.height;
  11151. }
  11152. return this._gl.drawingBufferHeight;
  11153. };
  11154. Engine.prototype.getRenderingCanvas = function () {
  11155. return this._renderingCanvas;
  11156. };
  11157. Engine.prototype.getRenderingCanvasClientRect = function () {
  11158. if (!this._renderingCanvas) {
  11159. return null;
  11160. }
  11161. return this._renderingCanvas.getBoundingClientRect();
  11162. };
  11163. Engine.prototype.setHardwareScalingLevel = function (level) {
  11164. this._hardwareScalingLevel = level;
  11165. this.resize();
  11166. };
  11167. Engine.prototype.getHardwareScalingLevel = function () {
  11168. return this._hardwareScalingLevel;
  11169. };
  11170. Engine.prototype.getLoadedTexturesCache = function () {
  11171. return this._internalTexturesCache;
  11172. };
  11173. Engine.prototype.getCaps = function () {
  11174. return this._caps;
  11175. };
  11176. Object.defineProperty(Engine.prototype, "drawCalls", {
  11177. /** The number of draw calls submitted last frame */
  11178. get: function () {
  11179. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11180. return 0;
  11181. },
  11182. enumerable: true,
  11183. configurable: true
  11184. });
  11185. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11186. get: function () {
  11187. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11188. return null;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. Engine.prototype.getDepthFunction = function () {
  11194. return this._depthCullingState.depthFunc;
  11195. };
  11196. Engine.prototype.setDepthFunction = function (depthFunc) {
  11197. this._depthCullingState.depthFunc = depthFunc;
  11198. };
  11199. Engine.prototype.setDepthFunctionToGreater = function () {
  11200. this._depthCullingState.depthFunc = this._gl.GREATER;
  11201. };
  11202. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11203. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11204. };
  11205. Engine.prototype.setDepthFunctionToLess = function () {
  11206. this._depthCullingState.depthFunc = this._gl.LESS;
  11207. };
  11208. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11209. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11210. };
  11211. Engine.prototype.getStencilBuffer = function () {
  11212. return this._stencilState.stencilTest;
  11213. };
  11214. Engine.prototype.setStencilBuffer = function (enable) {
  11215. this._stencilState.stencilTest = enable;
  11216. };
  11217. Engine.prototype.getStencilMask = function () {
  11218. return this._stencilState.stencilMask;
  11219. };
  11220. Engine.prototype.setStencilMask = function (mask) {
  11221. this._stencilState.stencilMask = mask;
  11222. };
  11223. Engine.prototype.getStencilFunction = function () {
  11224. return this._stencilState.stencilFunc;
  11225. };
  11226. Engine.prototype.getStencilFunctionReference = function () {
  11227. return this._stencilState.stencilFuncRef;
  11228. };
  11229. Engine.prototype.getStencilFunctionMask = function () {
  11230. return this._stencilState.stencilFuncMask;
  11231. };
  11232. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11233. this._stencilState.stencilFunc = stencilFunc;
  11234. };
  11235. Engine.prototype.setStencilFunctionReference = function (reference) {
  11236. this._stencilState.stencilFuncRef = reference;
  11237. };
  11238. Engine.prototype.setStencilFunctionMask = function (mask) {
  11239. this._stencilState.stencilFuncMask = mask;
  11240. };
  11241. Engine.prototype.getStencilOperationFail = function () {
  11242. return this._stencilState.stencilOpStencilFail;
  11243. };
  11244. Engine.prototype.getStencilOperationDepthFail = function () {
  11245. return this._stencilState.stencilOpDepthFail;
  11246. };
  11247. Engine.prototype.getStencilOperationPass = function () {
  11248. return this._stencilState.stencilOpStencilDepthPass;
  11249. };
  11250. Engine.prototype.setStencilOperationFail = function (operation) {
  11251. this._stencilState.stencilOpStencilFail = operation;
  11252. };
  11253. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11254. this._stencilState.stencilOpDepthFail = operation;
  11255. };
  11256. Engine.prototype.setStencilOperationPass = function (operation) {
  11257. this._stencilState.stencilOpStencilDepthPass = operation;
  11258. };
  11259. Engine.prototype.setDitheringState = function (value) {
  11260. if (value) {
  11261. this._gl.enable(this._gl.DITHER);
  11262. }
  11263. else {
  11264. this._gl.disable(this._gl.DITHER);
  11265. }
  11266. };
  11267. Engine.prototype.setRasterizerState = function (value) {
  11268. if (value) {
  11269. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11270. }
  11271. else {
  11272. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11273. }
  11274. };
  11275. /**
  11276. * stop executing a render loop function and remove it from the execution array
  11277. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11278. */
  11279. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11280. if (!renderFunction) {
  11281. this._activeRenderLoops = [];
  11282. return;
  11283. }
  11284. var index = this._activeRenderLoops.indexOf(renderFunction);
  11285. if (index >= 0) {
  11286. this._activeRenderLoops.splice(index, 1);
  11287. }
  11288. };
  11289. Engine.prototype._renderLoop = function () {
  11290. if (!this._contextWasLost) {
  11291. var shouldRender = true;
  11292. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11293. shouldRender = false;
  11294. }
  11295. if (shouldRender) {
  11296. // Start new frame
  11297. this.beginFrame();
  11298. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11299. var renderFunction = this._activeRenderLoops[index];
  11300. renderFunction();
  11301. }
  11302. // Present
  11303. this.endFrame();
  11304. }
  11305. }
  11306. if (this._activeRenderLoops.length > 0) {
  11307. // Register new frame
  11308. var requester = null;
  11309. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11310. requester = this._vrDisplay;
  11311. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11312. }
  11313. else {
  11314. this._renderingQueueLaunched = false;
  11315. }
  11316. };
  11317. /**
  11318. * Register and execute a render loop. The engine can have more than one render function.
  11319. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11320. * @example
  11321. * engine.runRenderLoop(function () {
  11322. * scene.render()
  11323. * })
  11324. */
  11325. Engine.prototype.runRenderLoop = function (renderFunction) {
  11326. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11327. return;
  11328. }
  11329. this._activeRenderLoops.push(renderFunction);
  11330. if (!this._renderingQueueLaunched) {
  11331. this._renderingQueueLaunched = true;
  11332. this._bindedRenderFunction = this._renderLoop.bind(this);
  11333. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11334. }
  11335. };
  11336. /**
  11337. * Toggle full screen mode.
  11338. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11339. * @param {any} options - an options object to be sent to the requestFullscreen function
  11340. */
  11341. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11342. if (this.isFullscreen) {
  11343. BABYLON.Tools.ExitFullscreen();
  11344. }
  11345. else {
  11346. this._pointerLockRequested = requestPointerLock;
  11347. if (this._renderingCanvas) {
  11348. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11349. }
  11350. }
  11351. };
  11352. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11353. if (stencil === void 0) { stencil = false; }
  11354. this.applyStates();
  11355. var mode = 0;
  11356. if (backBuffer && color) {
  11357. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11358. mode |= this._gl.COLOR_BUFFER_BIT;
  11359. }
  11360. if (depth) {
  11361. this._gl.clearDepth(1.0);
  11362. mode |= this._gl.DEPTH_BUFFER_BIT;
  11363. }
  11364. if (stencil) {
  11365. this._gl.clearStencil(0);
  11366. mode |= this._gl.STENCIL_BUFFER_BIT;
  11367. }
  11368. this._gl.clear(mode);
  11369. };
  11370. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11371. var gl = this._gl;
  11372. // Save state
  11373. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11374. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11375. // Change state
  11376. gl.enable(gl.SCISSOR_TEST);
  11377. gl.scissor(x, y, width, height);
  11378. // Clear
  11379. this.clear(clearColor, true, true, true);
  11380. // Restore state
  11381. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11382. if (curScissor === true) {
  11383. gl.enable(gl.SCISSOR_TEST);
  11384. }
  11385. else {
  11386. gl.disable(gl.SCISSOR_TEST);
  11387. }
  11388. };
  11389. /**
  11390. * Set the WebGL's viewport
  11391. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11392. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11393. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11394. */
  11395. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11396. var width = requiredWidth || this.getRenderWidth();
  11397. var height = requiredHeight || this.getRenderHeight();
  11398. var x = viewport.x || 0;
  11399. var y = viewport.y || 0;
  11400. this._cachedViewport = viewport;
  11401. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11402. };
  11403. /**
  11404. * Directly set the WebGL Viewport
  11405. * The x, y, width & height are directly passed to the WebGL call
  11406. * @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.
  11407. */
  11408. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11409. var currentViewport = this._cachedViewport;
  11410. this._cachedViewport = null;
  11411. this._gl.viewport(x, y, width, height);
  11412. return currentViewport;
  11413. };
  11414. Engine.prototype.beginFrame = function () {
  11415. this.onBeginFrameObservable.notifyObservers(this);
  11416. this._measureFps();
  11417. };
  11418. Engine.prototype.endFrame = function () {
  11419. //force a flush in case we are using a bad OS.
  11420. if (this._badOS) {
  11421. this.flushFramebuffer();
  11422. }
  11423. //submit frame to the vr device, if enabled
  11424. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11425. // TODO: We should only submit the frame if we read frameData successfully.
  11426. this._vrDisplay.submitFrame();
  11427. }
  11428. this.onEndFrameObservable.notifyObservers(this);
  11429. };
  11430. /**
  11431. * resize the view according to the canvas' size.
  11432. * @example
  11433. * window.addEventListener("resize", function () {
  11434. * engine.resize();
  11435. * });
  11436. */
  11437. Engine.prototype.resize = function () {
  11438. // We're not resizing the size of the canvas while in VR mode & presenting
  11439. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11440. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11441. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11442. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11443. }
  11444. };
  11445. /**
  11446. * force a specific size of the canvas
  11447. * @param {number} width - the new canvas' width
  11448. * @param {number} height - the new canvas' height
  11449. */
  11450. Engine.prototype.setSize = function (width, height) {
  11451. if (!this._renderingCanvas) {
  11452. return;
  11453. }
  11454. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11455. return;
  11456. }
  11457. this._renderingCanvas.width = width;
  11458. this._renderingCanvas.height = height;
  11459. for (var index = 0; index < this.scenes.length; index++) {
  11460. var scene = this.scenes[index];
  11461. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11462. var cam = scene.cameras[camIndex];
  11463. cam._currentRenderId = 0;
  11464. }
  11465. }
  11466. if (this.onResizeObservable.hasObservers) {
  11467. this.onResizeObservable.notifyObservers(this);
  11468. }
  11469. };
  11470. // WebVR functions
  11471. Engine.prototype.isVRDevicePresent = function () {
  11472. return !!this._vrDisplay;
  11473. };
  11474. Engine.prototype.getVRDevice = function () {
  11475. return this._vrDisplay;
  11476. };
  11477. Engine.prototype.initWebVR = function () {
  11478. var _this = this;
  11479. var notifyObservers = function () {
  11480. var eventArgs = {
  11481. vrDisplay: _this._vrDisplay,
  11482. vrSupported: _this._vrSupported
  11483. };
  11484. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11485. };
  11486. if (!this._onVrDisplayConnect) {
  11487. this._onVrDisplayConnect = function (event) {
  11488. _this._vrDisplay = event.display;
  11489. notifyObservers();
  11490. };
  11491. this._onVrDisplayDisconnect = function () {
  11492. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11493. _this._vrDisplay = undefined;
  11494. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11495. notifyObservers();
  11496. };
  11497. this._onVrDisplayPresentChange = function () {
  11498. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11499. };
  11500. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11501. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11502. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11503. }
  11504. this._getVRDisplays(notifyObservers);
  11505. return this.onVRDisplayChangedObservable;
  11506. };
  11507. Engine.prototype.enableVR = function () {
  11508. var _this = this;
  11509. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11510. var onResolved = function () {
  11511. _this.onVRRequestPresentComplete.notifyObservers(true);
  11512. _this._onVRFullScreenTriggered();
  11513. };
  11514. var onRejected = function () {
  11515. _this.onVRRequestPresentComplete.notifyObservers(false);
  11516. };
  11517. this.onVRRequestPresentStart.notifyObservers(this);
  11518. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11519. }
  11520. };
  11521. Engine.prototype.disableVR = function () {
  11522. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11523. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11524. }
  11525. };
  11526. Engine.prototype._getVRDisplays = function (callback) {
  11527. var _this = this;
  11528. var getWebVRDevices = function (devices) {
  11529. _this._vrSupported = true;
  11530. // note that devices may actually be an empty array. This is fine;
  11531. // we expect this._vrDisplay to be undefined in this case.
  11532. return _this._vrDisplay = devices[0];
  11533. };
  11534. if (navigator.getVRDisplays) {
  11535. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11536. // TODO: System CANNOT support WebVR, despite API presence.
  11537. _this._vrSupported = false;
  11538. callback();
  11539. });
  11540. }
  11541. else {
  11542. // TODO: Browser does not support WebVR
  11543. this._vrDisplay = undefined;
  11544. this._vrSupported = false;
  11545. callback();
  11546. }
  11547. };
  11548. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11549. if (this._currentRenderTarget) {
  11550. this.unBindFramebuffer(this._currentRenderTarget);
  11551. }
  11552. this._currentRenderTarget = texture;
  11553. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11554. var gl = this._gl;
  11555. if (texture.isCube) {
  11556. if (faceIndex === undefined) {
  11557. faceIndex = 0;
  11558. }
  11559. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11560. }
  11561. if (this._cachedViewport && !forceFullscreenViewport) {
  11562. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11563. }
  11564. else {
  11565. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11566. }
  11567. this.wipeCaches();
  11568. };
  11569. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11570. if (this._currentFramebuffer !== framebuffer) {
  11571. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11572. this._currentFramebuffer = framebuffer;
  11573. }
  11574. };
  11575. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11576. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11577. this._currentRenderTarget = null;
  11578. // If MSAA, we need to bitblt back to main texture
  11579. var gl = this._gl;
  11580. if (texture._MSAAFramebuffer) {
  11581. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11582. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11583. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11584. }
  11585. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11586. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11587. gl.generateMipmap(gl.TEXTURE_2D);
  11588. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11589. }
  11590. if (onBeforeUnbind) {
  11591. if (texture._MSAAFramebuffer) {
  11592. // Bind the correct framebuffer
  11593. this.bindUnboundFramebuffer(texture._framebuffer);
  11594. }
  11595. onBeforeUnbind();
  11596. }
  11597. this.bindUnboundFramebuffer(null);
  11598. };
  11599. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11600. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11601. this._currentRenderTarget = null;
  11602. // If MSAA, we need to bitblt back to main texture
  11603. var gl = this._gl;
  11604. if (textures[0]._MSAAFramebuffer) {
  11605. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11606. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11607. var attachments = textures[0]._attachments;
  11608. if (!attachments) {
  11609. attachments = new Array(textures.length);
  11610. textures[0]._attachments = attachments;
  11611. }
  11612. for (var i = 0; i < textures.length; i++) {
  11613. var texture = textures[i];
  11614. for (var j = 0; j < attachments.length; j++) {
  11615. attachments[j] = gl.NONE;
  11616. }
  11617. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11618. gl.readBuffer(attachments[i]);
  11619. gl.drawBuffers(attachments);
  11620. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11621. }
  11622. for (var i = 0; i < attachments.length; i++) {
  11623. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11624. }
  11625. gl.drawBuffers(attachments);
  11626. }
  11627. for (var i = 0; i < textures.length; i++) {
  11628. var texture = textures[i];
  11629. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11630. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11631. gl.generateMipmap(gl.TEXTURE_2D);
  11632. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11633. }
  11634. }
  11635. if (onBeforeUnbind) {
  11636. if (textures[0]._MSAAFramebuffer) {
  11637. // Bind the correct framebuffer
  11638. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11639. }
  11640. onBeforeUnbind();
  11641. }
  11642. this.bindUnboundFramebuffer(null);
  11643. };
  11644. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11645. if (texture.generateMipMaps) {
  11646. var gl = this._gl;
  11647. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11648. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11649. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11650. }
  11651. };
  11652. Engine.prototype.flushFramebuffer = function () {
  11653. this._gl.flush();
  11654. };
  11655. Engine.prototype.restoreDefaultFramebuffer = function () {
  11656. if (this._currentRenderTarget) {
  11657. this.unBindFramebuffer(this._currentRenderTarget);
  11658. }
  11659. else {
  11660. this.bindUnboundFramebuffer(null);
  11661. }
  11662. if (this._cachedViewport) {
  11663. this.setViewport(this._cachedViewport);
  11664. }
  11665. this.wipeCaches();
  11666. };
  11667. // UBOs
  11668. Engine.prototype.createUniformBuffer = function (elements) {
  11669. var ubo = this._gl.createBuffer();
  11670. if (!ubo) {
  11671. throw new Error("Unable to create uniform buffer");
  11672. }
  11673. this.bindUniformBuffer(ubo);
  11674. if (elements instanceof Float32Array) {
  11675. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11676. }
  11677. else {
  11678. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11679. }
  11680. this.bindUniformBuffer(null);
  11681. ubo.references = 1;
  11682. return ubo;
  11683. };
  11684. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11685. var ubo = this._gl.createBuffer();
  11686. if (!ubo) {
  11687. throw new Error("Unable to create dynamic uniform buffer");
  11688. }
  11689. this.bindUniformBuffer(ubo);
  11690. if (elements instanceof Float32Array) {
  11691. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11692. }
  11693. else {
  11694. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11695. }
  11696. this.bindUniformBuffer(null);
  11697. ubo.references = 1;
  11698. return ubo;
  11699. };
  11700. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11701. this.bindUniformBuffer(uniformBuffer);
  11702. if (offset === undefined) {
  11703. offset = 0;
  11704. }
  11705. if (count === undefined) {
  11706. if (elements instanceof Float32Array) {
  11707. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11708. }
  11709. else {
  11710. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11711. }
  11712. }
  11713. else {
  11714. if (elements instanceof Float32Array) {
  11715. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11716. }
  11717. else {
  11718. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11719. }
  11720. }
  11721. this.bindUniformBuffer(null);
  11722. };
  11723. // VBOs
  11724. Engine.prototype._resetVertexBufferBinding = function () {
  11725. this.bindArrayBuffer(null);
  11726. this._cachedVertexBuffers = null;
  11727. };
  11728. Engine.prototype.createVertexBuffer = function (vertices) {
  11729. var vbo = this._gl.createBuffer();
  11730. if (!vbo) {
  11731. throw new Error("Unable to create vertex buffer");
  11732. }
  11733. this.bindArrayBuffer(vbo);
  11734. if (vertices instanceof Float32Array) {
  11735. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11736. }
  11737. else {
  11738. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11739. }
  11740. this._resetVertexBufferBinding();
  11741. vbo.references = 1;
  11742. return vbo;
  11743. };
  11744. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11745. var vbo = this._gl.createBuffer();
  11746. if (!vbo) {
  11747. throw new Error("Unable to create dynamic vertex buffer");
  11748. }
  11749. this.bindArrayBuffer(vbo);
  11750. if (vertices instanceof Float32Array) {
  11751. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11752. }
  11753. else {
  11754. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11755. }
  11756. this._resetVertexBufferBinding();
  11757. vbo.references = 1;
  11758. return vbo;
  11759. };
  11760. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11761. if (offset === void 0) { offset = 0; }
  11762. // Force cache update
  11763. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11764. this.bindIndexBuffer(indexBuffer);
  11765. var arrayBuffer;
  11766. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11767. arrayBuffer = indices;
  11768. }
  11769. else {
  11770. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11771. }
  11772. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11773. this._resetIndexBufferBinding();
  11774. };
  11775. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11776. this.bindArrayBuffer(vertexBuffer);
  11777. if (offset === undefined) {
  11778. offset = 0;
  11779. }
  11780. if (count === undefined) {
  11781. if (vertices instanceof Float32Array) {
  11782. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11783. }
  11784. else {
  11785. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11786. }
  11787. }
  11788. else {
  11789. if (vertices instanceof Float32Array) {
  11790. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11791. }
  11792. else {
  11793. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11794. }
  11795. }
  11796. this._resetVertexBufferBinding();
  11797. };
  11798. Engine.prototype._resetIndexBufferBinding = function () {
  11799. this.bindIndexBuffer(null);
  11800. this._cachedIndexBuffer = null;
  11801. };
  11802. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11803. var vbo = this._gl.createBuffer();
  11804. if (!vbo) {
  11805. throw new Error("Unable to create index buffer");
  11806. }
  11807. this.bindIndexBuffer(vbo);
  11808. // Check for 32 bits indices
  11809. var arrayBuffer;
  11810. var need32Bits = false;
  11811. if (indices instanceof Uint16Array) {
  11812. arrayBuffer = indices;
  11813. }
  11814. else {
  11815. //check 32 bit support
  11816. if (this._caps.uintIndices) {
  11817. if (indices instanceof Uint32Array) {
  11818. arrayBuffer = indices;
  11819. need32Bits = true;
  11820. }
  11821. else {
  11822. //number[] or Int32Array, check if 32 bit is necessary
  11823. for (var index = 0; index < indices.length; index++) {
  11824. if (indices[index] > 65535) {
  11825. need32Bits = true;
  11826. break;
  11827. }
  11828. }
  11829. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11830. }
  11831. }
  11832. else {
  11833. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11834. arrayBuffer = new Uint16Array(indices);
  11835. }
  11836. }
  11837. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11838. this._resetIndexBufferBinding();
  11839. vbo.references = 1;
  11840. vbo.is32Bits = need32Bits;
  11841. return vbo;
  11842. };
  11843. Engine.prototype.bindArrayBuffer = function (buffer) {
  11844. if (!this._vaoRecordInProgress) {
  11845. this._unbindVertexArrayObject();
  11846. }
  11847. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11848. };
  11849. Engine.prototype.bindUniformBuffer = function (buffer) {
  11850. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11851. };
  11852. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11853. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11854. };
  11855. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11856. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11857. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11858. };
  11859. ;
  11860. Engine.prototype.bindIndexBuffer = function (buffer) {
  11861. if (!this._vaoRecordInProgress) {
  11862. this._unbindVertexArrayObject();
  11863. }
  11864. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11865. };
  11866. Engine.prototype.bindBuffer = function (buffer, target) {
  11867. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11868. this._gl.bindBuffer(target, buffer);
  11869. this._currentBoundBuffer[target] = buffer;
  11870. }
  11871. };
  11872. Engine.prototype.updateArrayBuffer = function (data) {
  11873. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11874. };
  11875. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11876. var pointer = this._currentBufferPointers[indx];
  11877. var changed = false;
  11878. if (!pointer.active) {
  11879. changed = true;
  11880. pointer.active = true;
  11881. pointer.index = indx;
  11882. pointer.size = size;
  11883. pointer.type = type;
  11884. pointer.normalized = normalized;
  11885. pointer.stride = stride;
  11886. pointer.offset = offset;
  11887. pointer.buffer = buffer;
  11888. }
  11889. else {
  11890. if (pointer.buffer !== buffer) {
  11891. pointer.buffer = buffer;
  11892. changed = true;
  11893. }
  11894. if (pointer.size !== size) {
  11895. pointer.size = size;
  11896. changed = true;
  11897. }
  11898. if (pointer.type !== type) {
  11899. pointer.type = type;
  11900. changed = true;
  11901. }
  11902. if (pointer.normalized !== normalized) {
  11903. pointer.normalized = normalized;
  11904. changed = true;
  11905. }
  11906. if (pointer.stride !== stride) {
  11907. pointer.stride = stride;
  11908. changed = true;
  11909. }
  11910. if (pointer.offset !== offset) {
  11911. pointer.offset = offset;
  11912. changed = true;
  11913. }
  11914. }
  11915. if (changed || this._vaoRecordInProgress) {
  11916. this.bindArrayBuffer(buffer);
  11917. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11918. }
  11919. };
  11920. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11921. if (indexBuffer == null) {
  11922. return;
  11923. }
  11924. if (this._cachedIndexBuffer !== indexBuffer) {
  11925. this._cachedIndexBuffer = indexBuffer;
  11926. this.bindIndexBuffer(indexBuffer);
  11927. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11928. }
  11929. };
  11930. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11931. var attributes = effect.getAttributesNames();
  11932. if (!this._vaoRecordInProgress) {
  11933. this._unbindVertexArrayObject();
  11934. }
  11935. this.unbindAllAttributes();
  11936. for (var index = 0; index < attributes.length; index++) {
  11937. var order = effect.getAttributeLocation(index);
  11938. if (order >= 0) {
  11939. var vertexBuffer = vertexBuffers[attributes[index]];
  11940. if (!vertexBuffer) {
  11941. continue;
  11942. }
  11943. this._gl.enableVertexAttribArray(order);
  11944. if (!this._vaoRecordInProgress) {
  11945. this._vertexAttribArraysEnabled[order] = true;
  11946. }
  11947. var buffer = vertexBuffer.getBuffer();
  11948. if (buffer) {
  11949. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11950. if (vertexBuffer.getIsInstanced()) {
  11951. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11952. if (!this._vaoRecordInProgress) {
  11953. this._currentInstanceLocations.push(order);
  11954. this._currentInstanceBuffers.push(buffer);
  11955. }
  11956. }
  11957. }
  11958. }
  11959. }
  11960. };
  11961. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11962. var vao = this._gl.createVertexArray();
  11963. this._vaoRecordInProgress = true;
  11964. this._gl.bindVertexArray(vao);
  11965. this._mustWipeVertexAttributes = true;
  11966. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11967. this.bindIndexBuffer(indexBuffer);
  11968. this._vaoRecordInProgress = false;
  11969. this._gl.bindVertexArray(null);
  11970. return vao;
  11971. };
  11972. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11973. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11974. this._cachedVertexArrayObject = vertexArrayObject;
  11975. this._gl.bindVertexArray(vertexArrayObject);
  11976. this._cachedVertexBuffers = null;
  11977. this._cachedIndexBuffer = null;
  11978. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11979. this._mustWipeVertexAttributes = true;
  11980. }
  11981. };
  11982. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11983. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11984. this._cachedVertexBuffers = vertexBuffer;
  11985. this._cachedEffectForVertexBuffers = effect;
  11986. var attributesCount = effect.getAttributesCount();
  11987. this._unbindVertexArrayObject();
  11988. this.unbindAllAttributes();
  11989. var offset = 0;
  11990. for (var index = 0; index < attributesCount; index++) {
  11991. if (index < vertexDeclaration.length) {
  11992. var order = effect.getAttributeLocation(index);
  11993. if (order >= 0) {
  11994. this._gl.enableVertexAttribArray(order);
  11995. this._vertexAttribArraysEnabled[order] = true;
  11996. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11997. }
  11998. offset += vertexDeclaration[index] * 4;
  11999. }
  12000. }
  12001. }
  12002. this._bindIndexBufferWithCache(indexBuffer);
  12003. };
  12004. Engine.prototype._unbindVertexArrayObject = function () {
  12005. if (!this._cachedVertexArrayObject) {
  12006. return;
  12007. }
  12008. this._cachedVertexArrayObject = null;
  12009. this._gl.bindVertexArray(null);
  12010. };
  12011. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12012. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12013. this._cachedVertexBuffers = vertexBuffers;
  12014. this._cachedEffectForVertexBuffers = effect;
  12015. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12016. }
  12017. this._bindIndexBufferWithCache(indexBuffer);
  12018. };
  12019. Engine.prototype.unbindInstanceAttributes = function () {
  12020. var boundBuffer;
  12021. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12022. var instancesBuffer = this._currentInstanceBuffers[i];
  12023. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12024. boundBuffer = instancesBuffer;
  12025. this.bindArrayBuffer(instancesBuffer);
  12026. }
  12027. var offsetLocation = this._currentInstanceLocations[i];
  12028. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12029. }
  12030. this._currentInstanceBuffers.length = 0;
  12031. this._currentInstanceLocations.length = 0;
  12032. };
  12033. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12034. this._gl.deleteVertexArray(vao);
  12035. };
  12036. Engine.prototype._releaseBuffer = function (buffer) {
  12037. buffer.references--;
  12038. if (buffer.references === 0) {
  12039. this._gl.deleteBuffer(buffer);
  12040. return true;
  12041. }
  12042. return false;
  12043. };
  12044. Engine.prototype.createInstancesBuffer = function (capacity) {
  12045. var buffer = this._gl.createBuffer();
  12046. if (!buffer) {
  12047. throw new Error("Unable to create instance buffer");
  12048. }
  12049. buffer.capacity = capacity;
  12050. this.bindArrayBuffer(buffer);
  12051. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12052. return buffer;
  12053. };
  12054. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12055. this._gl.deleteBuffer(buffer);
  12056. };
  12057. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12058. this.bindArrayBuffer(instancesBuffer);
  12059. if (data) {
  12060. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12061. }
  12062. if (offsetLocations[0].index !== undefined) {
  12063. var stride = 0;
  12064. for (var i = 0; i < offsetLocations.length; i++) {
  12065. var ai = offsetLocations[i];
  12066. stride += ai.attributeSize * 4;
  12067. }
  12068. for (var i = 0; i < offsetLocations.length; i++) {
  12069. var ai = offsetLocations[i];
  12070. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12071. this._gl.enableVertexAttribArray(ai.index);
  12072. this._vertexAttribArraysEnabled[ai.index] = true;
  12073. }
  12074. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12075. this._gl.vertexAttribDivisor(ai.index, 1);
  12076. this._currentInstanceLocations.push(ai.index);
  12077. this._currentInstanceBuffers.push(instancesBuffer);
  12078. }
  12079. }
  12080. else {
  12081. for (var index = 0; index < 4; index++) {
  12082. var offsetLocation = offsetLocations[index];
  12083. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12084. this._gl.enableVertexAttribArray(offsetLocation);
  12085. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12086. }
  12087. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12088. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12089. this._currentInstanceLocations.push(offsetLocation);
  12090. this._currentInstanceBuffers.push(instancesBuffer);
  12091. }
  12092. }
  12093. };
  12094. Engine.prototype.applyStates = function () {
  12095. this._depthCullingState.apply(this._gl);
  12096. this._stencilState.apply(this._gl);
  12097. this._alphaState.apply(this._gl);
  12098. };
  12099. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12100. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12101. };
  12102. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12103. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12104. };
  12105. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12106. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12107. };
  12108. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12109. // Apply states
  12110. this.applyStates();
  12111. this._drawCalls.addCount(1, false);
  12112. // Render
  12113. var drawMode = this.DrawMode(fillMode);
  12114. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12115. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12116. if (instancesCount) {
  12117. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12118. }
  12119. else {
  12120. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12121. }
  12122. };
  12123. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12124. // Apply states
  12125. this.applyStates();
  12126. this._drawCalls.addCount(1, false);
  12127. var drawMode = this.DrawMode(fillMode);
  12128. if (instancesCount) {
  12129. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12130. }
  12131. else {
  12132. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12133. }
  12134. };
  12135. Engine.prototype.DrawMode = function (fillMode) {
  12136. switch (fillMode) {
  12137. // Triangle views
  12138. case BABYLON.Material.TriangleFillMode:
  12139. return this._gl.TRIANGLES;
  12140. case BABYLON.Material.PointFillMode:
  12141. return this._gl.POINTS;
  12142. case BABYLON.Material.WireFrameFillMode:
  12143. return this._gl.LINES;
  12144. // Draw modes
  12145. case BABYLON.Material.PointListDrawMode:
  12146. return this._gl.POINTS;
  12147. case BABYLON.Material.LineListDrawMode:
  12148. return this._gl.LINES;
  12149. case BABYLON.Material.LineLoopDrawMode:
  12150. return this._gl.LINE_LOOP;
  12151. case BABYLON.Material.LineStripDrawMode:
  12152. return this._gl.LINE_STRIP;
  12153. case BABYLON.Material.TriangleStripDrawMode:
  12154. return this._gl.TRIANGLE_STRIP;
  12155. case BABYLON.Material.TriangleFanDrawMode:
  12156. return this._gl.TRIANGLE_FAN;
  12157. default:
  12158. return this._gl.TRIANGLES;
  12159. }
  12160. };
  12161. // Shaders
  12162. Engine.prototype._releaseEffect = function (effect) {
  12163. if (this._compiledEffects[effect._key]) {
  12164. delete this._compiledEffects[effect._key];
  12165. this._deleteProgram(effect.getProgram());
  12166. }
  12167. };
  12168. Engine.prototype._deleteProgram = function (program) {
  12169. if (program) {
  12170. program.__SPECTOR_rebuildProgram = null;
  12171. if (program.transformFeedback) {
  12172. this.deleteTransformFeedback(program.transformFeedback);
  12173. program.transformFeedback = null;
  12174. }
  12175. this._gl.deleteProgram(program);
  12176. }
  12177. };
  12178. /**
  12179. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12180. * @param samplers An array of string used to represent textures
  12181. */
  12182. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12183. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12184. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12185. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12186. if (this._compiledEffects[name]) {
  12187. var compiledEffect = this._compiledEffects[name];
  12188. if (onCompiled && compiledEffect.isReady()) {
  12189. onCompiled(compiledEffect);
  12190. }
  12191. return compiledEffect;
  12192. }
  12193. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12194. effect._key = name;
  12195. this._compiledEffects[name] = effect;
  12196. return effect;
  12197. };
  12198. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12199. if (uniformsNames === void 0) { uniformsNames = []; }
  12200. if (samplers === void 0) { samplers = []; }
  12201. if (defines === void 0) { defines = ""; }
  12202. return this.createEffect({
  12203. vertex: "particles",
  12204. fragmentElement: fragmentName
  12205. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12206. };
  12207. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12208. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12209. context = context || this._gl;
  12210. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12211. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12212. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12213. };
  12214. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12215. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12216. context = context || this._gl;
  12217. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12218. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12219. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12220. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12221. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12222. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12223. return program;
  12224. };
  12225. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12226. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12227. var shaderProgram = context.createProgram();
  12228. if (!shaderProgram) {
  12229. throw new Error("Unable to create program");
  12230. }
  12231. context.attachShader(shaderProgram, vertexShader);
  12232. context.attachShader(shaderProgram, fragmentShader);
  12233. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12234. var transformFeedback = this.createTransformFeedback();
  12235. this.bindTransformFeedback(transformFeedback);
  12236. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12237. shaderProgram.transformFeedback = transformFeedback;
  12238. }
  12239. context.linkProgram(shaderProgram);
  12240. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12241. this.bindTransformFeedback(null);
  12242. }
  12243. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12244. if (!linked) {
  12245. context.validateProgram(shaderProgram);
  12246. var error = context.getProgramInfoLog(shaderProgram);
  12247. if (error) {
  12248. throw new Error(error);
  12249. }
  12250. }
  12251. context.deleteShader(vertexShader);
  12252. context.deleteShader(fragmentShader);
  12253. return shaderProgram;
  12254. };
  12255. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12256. var results = new Array();
  12257. for (var index = 0; index < uniformsNames.length; index++) {
  12258. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12259. }
  12260. return results;
  12261. };
  12262. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12263. var results = [];
  12264. for (var index = 0; index < attributesNames.length; index++) {
  12265. try {
  12266. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12267. }
  12268. catch (e) {
  12269. results.push(-1);
  12270. }
  12271. }
  12272. return results;
  12273. };
  12274. Engine.prototype.enableEffect = function (effect) {
  12275. if (!effect) {
  12276. return;
  12277. }
  12278. // Use program
  12279. this.bindSamplers(effect);
  12280. this._currentEffect = effect;
  12281. if (effect.onBind) {
  12282. effect.onBind(effect);
  12283. }
  12284. effect.onBindObservable.notifyObservers(effect);
  12285. };
  12286. Engine.prototype.setIntArray = function (uniform, array) {
  12287. if (!uniform)
  12288. return;
  12289. this._gl.uniform1iv(uniform, array);
  12290. };
  12291. Engine.prototype.setIntArray2 = function (uniform, array) {
  12292. if (!uniform || array.length % 2 !== 0)
  12293. return;
  12294. this._gl.uniform2iv(uniform, array);
  12295. };
  12296. Engine.prototype.setIntArray3 = function (uniform, array) {
  12297. if (!uniform || array.length % 3 !== 0)
  12298. return;
  12299. this._gl.uniform3iv(uniform, array);
  12300. };
  12301. Engine.prototype.setIntArray4 = function (uniform, array) {
  12302. if (!uniform || array.length % 4 !== 0)
  12303. return;
  12304. this._gl.uniform4iv(uniform, array);
  12305. };
  12306. Engine.prototype.setFloatArray = function (uniform, array) {
  12307. if (!uniform)
  12308. return;
  12309. this._gl.uniform1fv(uniform, array);
  12310. };
  12311. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12312. if (!uniform || array.length % 2 !== 0)
  12313. return;
  12314. this._gl.uniform2fv(uniform, array);
  12315. };
  12316. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12317. if (!uniform || array.length % 3 !== 0)
  12318. return;
  12319. this._gl.uniform3fv(uniform, array);
  12320. };
  12321. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12322. if (!uniform || array.length % 4 !== 0)
  12323. return;
  12324. this._gl.uniform4fv(uniform, array);
  12325. };
  12326. Engine.prototype.setArray = function (uniform, array) {
  12327. if (!uniform)
  12328. return;
  12329. this._gl.uniform1fv(uniform, array);
  12330. };
  12331. Engine.prototype.setArray2 = function (uniform, array) {
  12332. if (!uniform || array.length % 2 !== 0)
  12333. return;
  12334. this._gl.uniform2fv(uniform, array);
  12335. };
  12336. Engine.prototype.setArray3 = function (uniform, array) {
  12337. if (!uniform || array.length % 3 !== 0)
  12338. return;
  12339. this._gl.uniform3fv(uniform, array);
  12340. };
  12341. Engine.prototype.setArray4 = function (uniform, array) {
  12342. if (!uniform || array.length % 4 !== 0)
  12343. return;
  12344. this._gl.uniform4fv(uniform, array);
  12345. };
  12346. Engine.prototype.setMatrices = function (uniform, matrices) {
  12347. if (!uniform)
  12348. return;
  12349. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12350. };
  12351. Engine.prototype.setMatrix = function (uniform, matrix) {
  12352. if (!uniform)
  12353. return;
  12354. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12355. };
  12356. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12357. if (!uniform)
  12358. return;
  12359. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12360. };
  12361. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12362. if (!uniform)
  12363. return;
  12364. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12365. };
  12366. Engine.prototype.setInt = function (uniform, value) {
  12367. if (!uniform)
  12368. return;
  12369. this._gl.uniform1i(uniform, value);
  12370. };
  12371. Engine.prototype.setFloat = function (uniform, value) {
  12372. if (!uniform)
  12373. return;
  12374. this._gl.uniform1f(uniform, value);
  12375. };
  12376. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12377. if (!uniform)
  12378. return;
  12379. this._gl.uniform2f(uniform, x, y);
  12380. };
  12381. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12382. if (!uniform)
  12383. return;
  12384. this._gl.uniform3f(uniform, x, y, z);
  12385. };
  12386. Engine.prototype.setBool = function (uniform, bool) {
  12387. if (!uniform)
  12388. return;
  12389. this._gl.uniform1i(uniform, bool);
  12390. };
  12391. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12392. if (!uniform)
  12393. return;
  12394. this._gl.uniform4f(uniform, x, y, z, w);
  12395. };
  12396. Engine.prototype.setColor3 = function (uniform, color3) {
  12397. if (!uniform)
  12398. return;
  12399. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12400. };
  12401. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12402. if (!uniform)
  12403. return;
  12404. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12405. };
  12406. // States
  12407. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12408. if (zOffset === void 0) { zOffset = 0; }
  12409. if (reverseSide === void 0) { reverseSide = false; }
  12410. // Culling
  12411. if (this._depthCullingState.cull !== culling || force) {
  12412. this._depthCullingState.cull = culling;
  12413. }
  12414. // Cull face
  12415. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12416. if (this._depthCullingState.cullFace !== cullFace || force) {
  12417. this._depthCullingState.cullFace = cullFace;
  12418. }
  12419. // Z offset
  12420. this.setZOffset(zOffset);
  12421. // Front face
  12422. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12423. if (this._depthCullingState.frontFace !== frontFace || force) {
  12424. this._depthCullingState.frontFace = frontFace;
  12425. }
  12426. };
  12427. Engine.prototype.setZOffset = function (value) {
  12428. this._depthCullingState.zOffset = value;
  12429. };
  12430. Engine.prototype.getZOffset = function () {
  12431. return this._depthCullingState.zOffset;
  12432. };
  12433. Engine.prototype.setDepthBuffer = function (enable) {
  12434. this._depthCullingState.depthTest = enable;
  12435. };
  12436. Engine.prototype.getDepthWrite = function () {
  12437. return this._depthCullingState.depthMask;
  12438. };
  12439. Engine.prototype.setDepthWrite = function (enable) {
  12440. this._depthCullingState.depthMask = enable;
  12441. };
  12442. Engine.prototype.setColorWrite = function (enable) {
  12443. this._gl.colorMask(enable, enable, enable, enable);
  12444. this._colorWrite = enable;
  12445. };
  12446. Engine.prototype.getColorWrite = function () {
  12447. return this._colorWrite;
  12448. };
  12449. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12450. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12451. };
  12452. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12453. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12454. if (this._alphaMode === mode) {
  12455. return;
  12456. }
  12457. switch (mode) {
  12458. case Engine.ALPHA_DISABLE:
  12459. this._alphaState.alphaBlend = false;
  12460. break;
  12461. case Engine.ALPHA_PREMULTIPLIED:
  12462. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12463. this._alphaState.alphaBlend = true;
  12464. break;
  12465. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12466. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12467. this._alphaState.alphaBlend = true;
  12468. break;
  12469. case Engine.ALPHA_COMBINE:
  12470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12471. this._alphaState.alphaBlend = true;
  12472. break;
  12473. case Engine.ALPHA_ONEONE:
  12474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12475. this._alphaState.alphaBlend = true;
  12476. break;
  12477. case Engine.ALPHA_ADD:
  12478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12479. this._alphaState.alphaBlend = true;
  12480. break;
  12481. case Engine.ALPHA_SUBTRACT:
  12482. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12483. this._alphaState.alphaBlend = true;
  12484. break;
  12485. case Engine.ALPHA_MULTIPLY:
  12486. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12487. this._alphaState.alphaBlend = true;
  12488. break;
  12489. case Engine.ALPHA_MAXIMIZED:
  12490. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12491. this._alphaState.alphaBlend = true;
  12492. break;
  12493. case Engine.ALPHA_INTERPOLATE:
  12494. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12495. this._alphaState.alphaBlend = true;
  12496. break;
  12497. case Engine.ALPHA_SCREENMODE:
  12498. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12499. this._alphaState.alphaBlend = true;
  12500. break;
  12501. }
  12502. if (!noDepthWriteChange) {
  12503. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12504. }
  12505. this._alphaMode = mode;
  12506. };
  12507. Engine.prototype.getAlphaMode = function () {
  12508. return this._alphaMode;
  12509. };
  12510. // Textures
  12511. Engine.prototype.wipeCaches = function (bruteForce) {
  12512. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12513. return;
  12514. }
  12515. this._currentEffect = null;
  12516. // 6/8/2017: deltakosh: Should not be required anymore.
  12517. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12518. if (bruteForce) {
  12519. this.resetTextureCache();
  12520. this._currentProgram = null;
  12521. this._stencilState.reset();
  12522. this._depthCullingState.reset();
  12523. this.setDepthFunctionToLessOrEqual();
  12524. this._alphaState.reset();
  12525. }
  12526. this._resetVertexBufferBinding();
  12527. this._cachedIndexBuffer = null;
  12528. this._cachedEffectForVertexBuffers = null;
  12529. this._unbindVertexArrayObject();
  12530. this.bindIndexBuffer(null);
  12531. };
  12532. /**
  12533. * Set the compressed texture format to use, based on the formats you have, and the formats
  12534. * supported by the hardware / browser.
  12535. *
  12536. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12537. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12538. * to API arguments needed to compressed textures. This puts the burden on the container
  12539. * generator to house the arcane code for determining these for current & future formats.
  12540. *
  12541. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12542. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12543. *
  12544. * Note: The result of this call is not taken into account when a texture is base64.
  12545. *
  12546. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12547. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12548. *
  12549. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12550. * @returns The extension selected.
  12551. */
  12552. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12553. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12554. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12555. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12556. return this._textureFormatInUse = this._texturesSupported[i];
  12557. }
  12558. }
  12559. }
  12560. // actively set format to nothing, to allow this to be called more than once
  12561. // and possibly fail the 2nd time
  12562. this._textureFormatInUse = null;
  12563. return null;
  12564. };
  12565. Engine.prototype._createTexture = function () {
  12566. var texture = this._gl.createTexture();
  12567. if (!texture) {
  12568. throw new Error("Unable to create texture");
  12569. }
  12570. return texture;
  12571. };
  12572. /**
  12573. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12574. * @param {string} urlArg- This contains one of the following:
  12575. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12576. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12577. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12578. *
  12579. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12580. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12581. * @param {Scene} scene- Needed for loading to the correct scene.
  12582. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12583. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12584. * @param {callback} onError- Optional callback to be called upon failure.
  12585. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12586. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12587. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12588. *
  12589. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12590. */
  12591. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12592. var _this = this;
  12593. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12594. if (onLoad === void 0) { onLoad = null; }
  12595. if (onError === void 0) { onError = null; }
  12596. if (buffer === void 0) { buffer = null; }
  12597. if (fallBack === void 0) { fallBack = null; }
  12598. if (format === void 0) { format = null; }
  12599. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12600. var fromData = url.substr(0, 5) === "data:";
  12601. var fromBlob = url.substr(0, 5) === "blob:";
  12602. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12603. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12604. // establish the file extension, if possible
  12605. var lastDot = url.lastIndexOf('.');
  12606. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12607. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12608. var isTGA = (extension.indexOf(".tga") === 0);
  12609. // determine if a ktx file should be substituted
  12610. var isKTX = false;
  12611. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12612. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12613. isKTX = true;
  12614. }
  12615. if (scene) {
  12616. scene._addPendingData(texture);
  12617. }
  12618. texture.url = url;
  12619. texture.generateMipMaps = !noMipmap;
  12620. texture.samplingMode = samplingMode;
  12621. texture.invertY = invertY;
  12622. if (!this._doNotHandleContextLost) {
  12623. // Keep a link to the buffer only if we plan to handle context lost
  12624. texture._buffer = buffer;
  12625. }
  12626. var onLoadObserver = null;
  12627. if (onLoad && !fallBack) {
  12628. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12629. }
  12630. if (!fallBack)
  12631. this._internalTexturesCache.push(texture);
  12632. var onerror = function (message, exception) {
  12633. if (scene) {
  12634. scene._removePendingData(texture);
  12635. }
  12636. if (onLoadObserver) {
  12637. texture.onLoadedObservable.remove(onLoadObserver);
  12638. }
  12639. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12640. if (isKTX) {
  12641. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12642. }
  12643. else if (BABYLON.Tools.UseFallbackTexture) {
  12644. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12645. }
  12646. if (onError) {
  12647. onError(message || "Unknown error", exception);
  12648. }
  12649. };
  12650. var callback = null;
  12651. // processing for non-image formats
  12652. if (isKTX || isTGA || isDDS) {
  12653. if (isKTX) {
  12654. callback = function (data) {
  12655. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12656. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12657. ktx.uploadLevels(_this._gl, !noMipmap);
  12658. return false;
  12659. }, samplingMode);
  12660. };
  12661. }
  12662. else if (isTGA) {
  12663. callback = function (arrayBuffer) {
  12664. var data = new Uint8Array(arrayBuffer);
  12665. var header = BABYLON.TGATools.GetTGAHeader(data);
  12666. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12667. BABYLON.TGATools.UploadContent(_this._gl, data);
  12668. return false;
  12669. }, samplingMode);
  12670. };
  12671. }
  12672. else if (isDDS) {
  12673. callback = function (data) {
  12674. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12675. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12676. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12677. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12678. return false;
  12679. }, samplingMode);
  12680. };
  12681. }
  12682. if (!buffer) {
  12683. this._loadFile(url, function (data) {
  12684. if (callback) {
  12685. callback(data);
  12686. }
  12687. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12688. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12689. });
  12690. }
  12691. else {
  12692. if (callback) {
  12693. callback(buffer);
  12694. }
  12695. }
  12696. // image format processing
  12697. }
  12698. else {
  12699. var onload = function (img) {
  12700. if (fromBlob && !_this._doNotHandleContextLost) {
  12701. // We need to store the image if we need to rebuild the texture
  12702. // in case of a webgl context lost
  12703. texture._buffer = img;
  12704. }
  12705. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12706. var gl = _this._gl;
  12707. var isPot = (img.width === potWidth && img.height === potHeight);
  12708. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12709. if (isPot) {
  12710. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12711. return false;
  12712. }
  12713. // Using shaders to rescale because canvas.drawImage is lossy
  12714. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12715. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12716. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12717. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12718. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12719. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12720. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12721. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12722. _this._releaseTexture(source);
  12723. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12724. continuationCallback();
  12725. });
  12726. return true;
  12727. }, samplingMode);
  12728. };
  12729. if (!fromData || isBase64)
  12730. if (buffer instanceof HTMLImageElement) {
  12731. onload(buffer);
  12732. }
  12733. else {
  12734. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12735. }
  12736. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12737. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12738. else
  12739. onload(buffer);
  12740. }
  12741. return texture;
  12742. };
  12743. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12744. var _this = this;
  12745. var rtt = this.createRenderTargetTexture({
  12746. width: destination.width,
  12747. height: destination.height,
  12748. }, {
  12749. generateMipMaps: false,
  12750. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12751. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12752. generateDepthBuffer: false,
  12753. generateStencilBuffer: false
  12754. });
  12755. if (!this._rescalePostProcess) {
  12756. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12757. }
  12758. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12759. _this._rescalePostProcess.onApply = function (effect) {
  12760. effect._bindTexture("textureSampler", source);
  12761. };
  12762. var hostingScene = scene;
  12763. if (!hostingScene) {
  12764. hostingScene = _this.scenes[_this.scenes.length - 1];
  12765. }
  12766. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12767. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12768. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12769. _this.unBindFramebuffer(rtt);
  12770. _this._releaseTexture(rtt);
  12771. if (onComplete) {
  12772. onComplete();
  12773. }
  12774. });
  12775. };
  12776. Engine.prototype._getInternalFormat = function (format) {
  12777. var internalFormat = this._gl.RGBA;
  12778. switch (format) {
  12779. case Engine.TEXTUREFORMAT_ALPHA:
  12780. internalFormat = this._gl.ALPHA;
  12781. break;
  12782. case Engine.TEXTUREFORMAT_LUMINANCE:
  12783. internalFormat = this._gl.LUMINANCE;
  12784. break;
  12785. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12786. internalFormat = this._gl.LUMINANCE_ALPHA;
  12787. break;
  12788. case Engine.TEXTUREFORMAT_RGB:
  12789. internalFormat = this._gl.RGB;
  12790. break;
  12791. case Engine.TEXTUREFORMAT_RGBA:
  12792. internalFormat = this._gl.RGBA;
  12793. break;
  12794. }
  12795. return internalFormat;
  12796. };
  12797. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12798. if (compression === void 0) { compression = null; }
  12799. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12800. if (!texture) {
  12801. return;
  12802. }
  12803. var internalFormat = this._getInternalFormat(format);
  12804. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12805. var textureType = this._getWebGLTextureType(type);
  12806. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12807. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12808. if (!this._doNotHandleContextLost) {
  12809. texture._bufferView = data;
  12810. texture.format = format;
  12811. texture.type = type;
  12812. texture.invertY = invertY;
  12813. texture._compression = compression;
  12814. }
  12815. if (texture.width % 4 !== 0) {
  12816. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12817. }
  12818. if (compression && data) {
  12819. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12820. }
  12821. else {
  12822. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12823. }
  12824. if (texture.generateMipMaps) {
  12825. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12826. }
  12827. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12828. // this.resetTextureCache();
  12829. texture.isReady = true;
  12830. };
  12831. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12832. if (compression === void 0) { compression = null; }
  12833. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12834. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12835. texture.baseWidth = width;
  12836. texture.baseHeight = height;
  12837. texture.width = width;
  12838. texture.height = height;
  12839. texture.format = format;
  12840. texture.generateMipMaps = generateMipMaps;
  12841. texture.samplingMode = samplingMode;
  12842. texture.invertY = invertY;
  12843. texture._compression = compression;
  12844. texture.type = type;
  12845. if (!this._doNotHandleContextLost) {
  12846. texture._bufferView = data;
  12847. }
  12848. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12849. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12850. // Filters
  12851. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12852. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12853. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12854. if (generateMipMaps) {
  12855. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12856. }
  12857. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12858. this._internalTexturesCache.push(texture);
  12859. return texture;
  12860. };
  12861. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12862. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12863. texture.baseWidth = width;
  12864. texture.baseHeight = height;
  12865. if (generateMipMaps) {
  12866. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12867. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12868. }
  12869. // this.resetTextureCache();
  12870. texture.width = width;
  12871. texture.height = height;
  12872. texture.isReady = false;
  12873. texture.generateMipMaps = generateMipMaps;
  12874. texture.samplingMode = samplingMode;
  12875. this.updateTextureSamplingMode(samplingMode, texture);
  12876. this._internalTexturesCache.push(texture);
  12877. return texture;
  12878. };
  12879. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12880. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12881. if (texture.isCube) {
  12882. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12883. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12884. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12885. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12886. }
  12887. else if (texture.is3D) {
  12888. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12889. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12890. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12891. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12892. }
  12893. else {
  12894. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12895. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12897. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12898. }
  12899. texture.samplingMode = samplingMode;
  12900. };
  12901. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12902. if (premulAlpha === void 0) { premulAlpha = false; }
  12903. if (!texture) {
  12904. return;
  12905. }
  12906. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12907. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12908. if (premulAlpha) {
  12909. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12910. }
  12911. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12912. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12913. if (texture.generateMipMaps) {
  12914. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12915. }
  12916. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12917. if (premulAlpha) {
  12918. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12919. }
  12920. texture.isReady = true;
  12921. };
  12922. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12923. if (!texture || texture._isDisabled) {
  12924. return;
  12925. }
  12926. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12927. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12928. try {
  12929. // Testing video texture support
  12930. if (this._videoTextureSupported === undefined) {
  12931. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12932. if (this._gl.getError() !== 0) {
  12933. this._videoTextureSupported = false;
  12934. }
  12935. else {
  12936. this._videoTextureSupported = true;
  12937. }
  12938. }
  12939. // Copy video through the current working canvas if video texture is not supported
  12940. if (!this._videoTextureSupported) {
  12941. if (!texture._workingCanvas) {
  12942. texture._workingCanvas = document.createElement("canvas");
  12943. var context = texture._workingCanvas.getContext("2d");
  12944. if (!context) {
  12945. throw new Error("Unable to get 2d context");
  12946. }
  12947. texture._workingContext = context;
  12948. texture._workingCanvas.width = texture.width;
  12949. texture._workingCanvas.height = texture.height;
  12950. }
  12951. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12952. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12953. }
  12954. else {
  12955. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12956. }
  12957. if (texture.generateMipMaps) {
  12958. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12959. }
  12960. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12961. // this.resetTextureCache();
  12962. texture.isReady = true;
  12963. }
  12964. catch (ex) {
  12965. // Something unexpected
  12966. // Let's disable the texture
  12967. texture._isDisabled = true;
  12968. }
  12969. };
  12970. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12971. var fullOptions = new RenderTargetCreationOptions();
  12972. if (options !== undefined && typeof options === "object") {
  12973. fullOptions.generateMipMaps = options.generateMipMaps;
  12974. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12975. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12976. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12977. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12978. }
  12979. else {
  12980. fullOptions.generateMipMaps = options;
  12981. fullOptions.generateDepthBuffer = true;
  12982. fullOptions.generateStencilBuffer = false;
  12983. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12984. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12985. }
  12986. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12987. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12988. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12989. }
  12990. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12991. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12992. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12993. }
  12994. var gl = this._gl;
  12995. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12996. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12997. var width = size.width || size;
  12998. var height = size.height || size;
  12999. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13000. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13001. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13002. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13003. }
  13004. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13005. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13008. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13009. // Create the framebuffer
  13010. var framebuffer = gl.createFramebuffer();
  13011. this.bindUnboundFramebuffer(framebuffer);
  13012. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13013. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13014. if (fullOptions.generateMipMaps) {
  13015. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13016. }
  13017. // Unbind
  13018. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13019. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13020. this.bindUnboundFramebuffer(null);
  13021. texture._framebuffer = framebuffer;
  13022. texture.baseWidth = width;
  13023. texture.baseHeight = height;
  13024. texture.width = width;
  13025. texture.height = height;
  13026. texture.isReady = true;
  13027. texture.samples = 1;
  13028. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13029. texture.samplingMode = fullOptions.samplingMode;
  13030. texture.type = fullOptions.type;
  13031. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13032. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13033. // this.resetTextureCache();
  13034. this._internalTexturesCache.push(texture);
  13035. return texture;
  13036. };
  13037. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13038. var generateMipMaps = false;
  13039. var generateDepthBuffer = true;
  13040. var generateStencilBuffer = false;
  13041. var generateDepthTexture = false;
  13042. var textureCount = 1;
  13043. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13044. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13045. var types = [], samplingModes = [];
  13046. if (options !== undefined) {
  13047. generateMipMaps = options.generateMipMaps;
  13048. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13049. generateStencilBuffer = options.generateStencilBuffer;
  13050. generateDepthTexture = options.generateDepthTexture;
  13051. textureCount = options.textureCount || 1;
  13052. if (options.types) {
  13053. types = options.types;
  13054. }
  13055. if (options.samplingModes) {
  13056. samplingModes = options.samplingModes;
  13057. }
  13058. }
  13059. var gl = this._gl;
  13060. // Create the framebuffer
  13061. var framebuffer = gl.createFramebuffer();
  13062. this.bindUnboundFramebuffer(framebuffer);
  13063. var width = size.width || size;
  13064. var height = size.height || size;
  13065. var textures = [];
  13066. var attachments = [];
  13067. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13068. for (var i = 0; i < textureCount; i++) {
  13069. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13070. var type = types[i] || defaultType;
  13071. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13072. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13073. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13074. }
  13075. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13076. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13077. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13078. }
  13079. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13080. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13081. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13082. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13083. }
  13084. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13085. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13086. textures.push(texture);
  13087. attachments.push(attachment);
  13088. gl.activeTexture(gl["TEXTURE" + i]);
  13089. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13094. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13095. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13096. if (generateMipMaps) {
  13097. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13098. }
  13099. // Unbind
  13100. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13101. texture._framebuffer = framebuffer;
  13102. texture._depthStencilBuffer = depthStencilBuffer;
  13103. texture.baseWidth = width;
  13104. texture.baseHeight = height;
  13105. texture.width = width;
  13106. texture.height = height;
  13107. texture.isReady = true;
  13108. texture.samples = 1;
  13109. texture.generateMipMaps = generateMipMaps;
  13110. texture.samplingMode = samplingMode;
  13111. texture.type = type;
  13112. texture._generateDepthBuffer = generateDepthBuffer;
  13113. texture._generateStencilBuffer = generateStencilBuffer;
  13114. texture._attachments = attachments;
  13115. this._internalTexturesCache.push(texture);
  13116. }
  13117. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13118. // Depth texture
  13119. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13120. gl.activeTexture(gl.TEXTURE0);
  13121. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13126. 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);
  13127. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13128. depthTexture._framebuffer = framebuffer;
  13129. depthTexture.baseWidth = width;
  13130. depthTexture.baseHeight = height;
  13131. depthTexture.width = width;
  13132. depthTexture.height = height;
  13133. depthTexture.isReady = true;
  13134. depthTexture.samples = 1;
  13135. depthTexture.generateMipMaps = generateMipMaps;
  13136. depthTexture.samplingMode = gl.NEAREST;
  13137. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13138. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13139. textures.push(depthTexture);
  13140. this._internalTexturesCache.push(depthTexture);
  13141. }
  13142. gl.drawBuffers(attachments);
  13143. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13144. this.bindUnboundFramebuffer(null);
  13145. this.resetTextureCache();
  13146. return textures;
  13147. };
  13148. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13149. if (samples === void 0) { samples = 1; }
  13150. var depthStencilBuffer = null;
  13151. var gl = this._gl;
  13152. // Create the depth/stencil buffer
  13153. if (generateStencilBuffer) {
  13154. depthStencilBuffer = gl.createRenderbuffer();
  13155. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13156. if (samples > 1) {
  13157. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13158. }
  13159. else {
  13160. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13161. }
  13162. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13163. }
  13164. else if (generateDepthBuffer) {
  13165. depthStencilBuffer = gl.createRenderbuffer();
  13166. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13167. if (samples > 1) {
  13168. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13169. }
  13170. else {
  13171. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13172. }
  13173. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13174. }
  13175. return depthStencilBuffer;
  13176. };
  13177. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13178. if (this.webGLVersion < 2 || !texture) {
  13179. return 1;
  13180. }
  13181. if (texture.samples === samples) {
  13182. return samples;
  13183. }
  13184. var gl = this._gl;
  13185. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13186. // Dispose previous render buffers
  13187. if (texture._depthStencilBuffer) {
  13188. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13189. texture._depthStencilBuffer = null;
  13190. }
  13191. if (texture._MSAAFramebuffer) {
  13192. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13193. texture._MSAAFramebuffer = null;
  13194. }
  13195. if (texture._MSAARenderBuffer) {
  13196. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13197. texture._MSAARenderBuffer = null;
  13198. }
  13199. if (samples > 1) {
  13200. var framebuffer = gl.createFramebuffer();
  13201. if (!framebuffer) {
  13202. throw new Error("Unable to create multi sampled framebuffer");
  13203. }
  13204. texture._MSAAFramebuffer = framebuffer;
  13205. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13206. var colorRenderbuffer = gl.createRenderbuffer();
  13207. if (!colorRenderbuffer) {
  13208. throw new Error("Unable to create multi sampled framebuffer");
  13209. }
  13210. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13211. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13212. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13213. texture._MSAARenderBuffer = colorRenderbuffer;
  13214. }
  13215. else {
  13216. this.bindUnboundFramebuffer(texture._framebuffer);
  13217. }
  13218. texture.samples = samples;
  13219. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13220. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13221. this.bindUnboundFramebuffer(null);
  13222. return samples;
  13223. };
  13224. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13225. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13226. return 1;
  13227. }
  13228. if (textures[0].samples === samples) {
  13229. return samples;
  13230. }
  13231. var gl = this._gl;
  13232. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13233. // Dispose previous render buffers
  13234. if (textures[0]._depthStencilBuffer) {
  13235. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13236. textures[0]._depthStencilBuffer = null;
  13237. }
  13238. if (textures[0]._MSAAFramebuffer) {
  13239. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13240. textures[0]._MSAAFramebuffer = null;
  13241. }
  13242. for (var i = 0; i < textures.length; i++) {
  13243. if (textures[i]._MSAARenderBuffer) {
  13244. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13245. textures[i]._MSAARenderBuffer = null;
  13246. }
  13247. }
  13248. if (samples > 1) {
  13249. var framebuffer = gl.createFramebuffer();
  13250. if (!framebuffer) {
  13251. throw new Error("Unable to create multi sampled framebuffer");
  13252. }
  13253. this.bindUnboundFramebuffer(framebuffer);
  13254. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13255. var attachments = [];
  13256. for (var i = 0; i < textures.length; i++) {
  13257. var texture = textures[i];
  13258. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13259. var colorRenderbuffer = gl.createRenderbuffer();
  13260. if (!colorRenderbuffer) {
  13261. throw new Error("Unable to create multi sampled framebuffer");
  13262. }
  13263. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13264. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13265. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13266. texture._MSAAFramebuffer = framebuffer;
  13267. texture._MSAARenderBuffer = colorRenderbuffer;
  13268. texture.samples = samples;
  13269. texture._depthStencilBuffer = depthStencilBuffer;
  13270. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13271. attachments.push(attachment);
  13272. }
  13273. gl.drawBuffers(attachments);
  13274. }
  13275. else {
  13276. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13277. }
  13278. this.bindUnboundFramebuffer(null);
  13279. return samples;
  13280. };
  13281. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13282. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13283. };
  13284. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13285. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13286. };
  13287. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13288. var gl = this._gl;
  13289. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13290. var generateMipMaps = true;
  13291. var generateDepthBuffer = true;
  13292. var generateStencilBuffer = false;
  13293. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13294. if (options !== undefined) {
  13295. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13296. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13297. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13298. if (options.samplingMode !== undefined) {
  13299. samplingMode = options.samplingMode;
  13300. }
  13301. }
  13302. texture.isCube = true;
  13303. texture.generateMipMaps = generateMipMaps;
  13304. texture.samples = 1;
  13305. texture.samplingMode = samplingMode;
  13306. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13307. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13308. for (var face = 0; face < 6; face++) {
  13309. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13310. }
  13311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13315. // Create the framebuffer
  13316. var framebuffer = gl.createFramebuffer();
  13317. this.bindUnboundFramebuffer(framebuffer);
  13318. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13319. // Mipmaps
  13320. if (texture.generateMipMaps) {
  13321. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13322. }
  13323. // Unbind
  13324. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13325. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13326. this.bindUnboundFramebuffer(null);
  13327. texture._framebuffer = framebuffer;
  13328. texture.width = size;
  13329. texture.height = size;
  13330. texture.isReady = true;
  13331. //this.resetTextureCache();
  13332. this._internalTexturesCache.push(texture);
  13333. return texture;
  13334. };
  13335. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13336. var _this = this;
  13337. if (onLoad === void 0) { onLoad = null; }
  13338. if (onError === void 0) { onError = null; }
  13339. if (forcedExtension === void 0) { forcedExtension = null; }
  13340. var callback = function (loadData) {
  13341. if (!loadData) {
  13342. if (onLoad) {
  13343. onLoad(null);
  13344. }
  13345. return;
  13346. }
  13347. var texture = loadData.texture;
  13348. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13349. texture._lodGenerationScale = scale;
  13350. texture._lodGenerationOffset = offset;
  13351. if (_this._caps.textureLOD) {
  13352. // Do not add extra process if texture lod is supported.
  13353. if (onLoad) {
  13354. onLoad(texture);
  13355. }
  13356. return;
  13357. }
  13358. var mipSlices = 3;
  13359. var gl = _this._gl;
  13360. var width = loadData.width;
  13361. if (!width) {
  13362. return;
  13363. }
  13364. var textures = [];
  13365. for (var i = 0; i < mipSlices; i++) {
  13366. //compute LOD from even spacing in smoothness (matching shader calculation)
  13367. var smoothness = i / (mipSlices - 1);
  13368. var roughness = 1 - smoothness;
  13369. var minLODIndex = offset; // roughness = 0
  13370. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13371. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13372. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13373. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13374. glTextureFromLod.isCube = true;
  13375. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13376. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13378. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13380. if (loadData.isDDS) {
  13381. var info = loadData.info;
  13382. var data = loadData.data;
  13383. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13384. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13385. }
  13386. else {
  13387. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13388. }
  13389. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13390. // Wrap in a base texture for easy binding.
  13391. var lodTexture = new BABYLON.BaseTexture(scene);
  13392. lodTexture.isCube = true;
  13393. lodTexture._texture = glTextureFromLod;
  13394. glTextureFromLod.isReady = true;
  13395. textures.push(lodTexture);
  13396. }
  13397. texture._lodTextureHigh = textures[2];
  13398. texture._lodTextureMid = textures[1];
  13399. texture._lodTextureLow = textures[0];
  13400. if (onLoad) {
  13401. onLoad(texture);
  13402. }
  13403. };
  13404. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13405. };
  13406. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13407. var _this = this;
  13408. if (onLoad === void 0) { onLoad = null; }
  13409. if (onError === void 0) { onError = null; }
  13410. if (forcedExtension === void 0) { forcedExtension = null; }
  13411. var gl = this._gl;
  13412. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13413. texture.isCube = true;
  13414. texture.url = rootUrl;
  13415. texture.generateMipMaps = !noMipmap;
  13416. if (!this._doNotHandleContextLost) {
  13417. texture._extension = forcedExtension;
  13418. texture._files = files;
  13419. }
  13420. var isKTX = false;
  13421. var isDDS = false;
  13422. var lastDot = rootUrl.lastIndexOf('.');
  13423. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13424. if (this._textureFormatInUse) {
  13425. extension = this._textureFormatInUse;
  13426. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13427. isKTX = true;
  13428. }
  13429. else {
  13430. isDDS = (extension === ".dds");
  13431. }
  13432. var onerror = function (request, exception) {
  13433. if (onError && request) {
  13434. onError(request.status + " " + request.statusText, exception);
  13435. }
  13436. };
  13437. if (isKTX) {
  13438. this._loadFile(rootUrl, function (data) {
  13439. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13440. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13441. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13442. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13443. ktx.uploadLevels(_this._gl, !noMipmap);
  13444. _this.setCubeMapTextureParams(gl, loadMipmap);
  13445. texture.width = ktx.pixelWidth;
  13446. texture.height = ktx.pixelHeight;
  13447. texture.isReady = true;
  13448. }, undefined, undefined, true, onerror);
  13449. }
  13450. else if (isDDS) {
  13451. if (files && files.length === 6) {
  13452. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13453. var info;
  13454. var loadMipmap = false;
  13455. var width = 0;
  13456. for (var index = 0; index < imgs.length; index++) {
  13457. var data = imgs[index];
  13458. info = BABYLON.DDSTools.GetDDSInfo(data);
  13459. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13460. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13461. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13462. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13463. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13464. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13465. }
  13466. texture.width = info.width;
  13467. texture.height = info.height;
  13468. texture.type = info.textureType;
  13469. width = info.width;
  13470. }
  13471. _this.setCubeMapTextureParams(gl, loadMipmap);
  13472. texture.isReady = true;
  13473. if (onLoad) {
  13474. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13475. }
  13476. }, files, onError);
  13477. }
  13478. else {
  13479. this._loadFile(rootUrl, function (data) {
  13480. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13481. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13482. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13483. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13484. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13485. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13486. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13487. }
  13488. _this.setCubeMapTextureParams(gl, loadMipmap);
  13489. texture.width = info.width;
  13490. texture.height = info.height;
  13491. texture.isReady = true;
  13492. texture.type = info.textureType;
  13493. if (onLoad) {
  13494. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13495. }
  13496. }, undefined, undefined, true, onerror);
  13497. }
  13498. }
  13499. else {
  13500. if (!files) {
  13501. throw new Error("Cannot load cubemap because files were not defined");
  13502. }
  13503. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13504. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13505. var height = width;
  13506. _this._prepareWorkingCanvas();
  13507. if (!_this._workingCanvas || !_this._workingContext) {
  13508. return;
  13509. }
  13510. _this._workingCanvas.width = width;
  13511. _this._workingCanvas.height = height;
  13512. var faces = [
  13513. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13514. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13515. ];
  13516. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13517. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13518. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13519. for (var index = 0; index < faces.length; index++) {
  13520. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13521. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13522. }
  13523. if (!noMipmap) {
  13524. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13525. }
  13526. _this.setCubeMapTextureParams(gl, !noMipmap);
  13527. texture.width = width;
  13528. texture.height = height;
  13529. texture.isReady = true;
  13530. if (format) {
  13531. texture.format = format;
  13532. }
  13533. texture.onLoadedObservable.notifyObservers(texture);
  13534. texture.onLoadedObservable.clear();
  13535. if (onLoad) {
  13536. onLoad();
  13537. }
  13538. }, files, onError);
  13539. }
  13540. this._internalTexturesCache.push(texture);
  13541. return texture;
  13542. };
  13543. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13548. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13549. // this.resetTextureCache();
  13550. };
  13551. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13552. if (compression === void 0) { compression = null; }
  13553. if (level === void 0) { level = 0; }
  13554. texture._bufferViewArray = data;
  13555. texture.format = format;
  13556. texture.type = type;
  13557. texture.invertY = invertY;
  13558. texture._compression = compression;
  13559. var gl = this._gl;
  13560. var textureType = this._getWebGLTextureType(type);
  13561. var internalFormat = this._getInternalFormat(format);
  13562. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13563. var needConversion = false;
  13564. if (internalFormat === gl.RGB) {
  13565. internalFormat = gl.RGBA;
  13566. needConversion = true;
  13567. }
  13568. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13569. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13570. if (texture.width % 4 !== 0) {
  13571. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13572. }
  13573. // Data are known to be in +X +Y +Z -X -Y -Z
  13574. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13575. var faceData = data[faceIndex];
  13576. if (compression) {
  13577. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13578. }
  13579. else {
  13580. if (needConversion) {
  13581. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13582. }
  13583. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13584. }
  13585. }
  13586. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13587. if (isPot && texture.generateMipMaps && level === 0) {
  13588. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13589. }
  13590. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13591. // this.resetTextureCache();
  13592. texture.isReady = true;
  13593. };
  13594. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13595. if (compression === void 0) { compression = null; }
  13596. var gl = this._gl;
  13597. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13598. texture.isCube = true;
  13599. texture.generateMipMaps = generateMipMaps;
  13600. texture.format = format;
  13601. texture.type = type;
  13602. if (!this._doNotHandleContextLost) {
  13603. texture._bufferViewArray = data;
  13604. }
  13605. var textureType = this._getWebGLTextureType(type);
  13606. var internalFormat = this._getInternalFormat(format);
  13607. if (internalFormat === gl.RGB) {
  13608. internalFormat = gl.RGBA;
  13609. }
  13610. var width = size;
  13611. var height = width;
  13612. texture.width = width;
  13613. texture.height = height;
  13614. // Double check on POT to generate Mips.
  13615. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13616. if (!isPot) {
  13617. generateMipMaps = false;
  13618. }
  13619. // Upload data if needed. The texture won't be ready until then.
  13620. if (data) {
  13621. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13622. }
  13623. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13624. // Filters
  13625. if (data && generateMipMaps) {
  13626. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13627. }
  13628. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13630. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13631. }
  13632. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13634. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13635. }
  13636. else {
  13637. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13640. }
  13641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13643. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13644. return texture;
  13645. };
  13646. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13647. var _this = this;
  13648. if (onLoad === void 0) { onLoad = null; }
  13649. if (onError === void 0) { onError = null; }
  13650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13651. if (invertY === void 0) { invertY = false; }
  13652. var gl = this._gl;
  13653. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13654. scene._addPendingData(texture);
  13655. texture.url = url;
  13656. this._internalTexturesCache.push(texture);
  13657. var onerror = function (request, exception) {
  13658. scene._removePendingData(texture);
  13659. if (onError && request) {
  13660. onError(request.status + " " + request.statusText, exception);
  13661. }
  13662. };
  13663. var internalCallback = function (data) {
  13664. var width = texture.width;
  13665. var faceDataArrays = callback(data);
  13666. if (!faceDataArrays) {
  13667. return;
  13668. }
  13669. if (mipmmapGenerator) {
  13670. var textureType = _this._getWebGLTextureType(type);
  13671. var internalFormat = _this._getInternalFormat(format);
  13672. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13673. var needConversion = false;
  13674. if (internalFormat === gl.RGB) {
  13675. internalFormat = gl.RGBA;
  13676. needConversion = true;
  13677. }
  13678. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13679. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13680. var mipData = mipmmapGenerator(faceDataArrays);
  13681. for (var level = 0; level < mipData.length; level++) {
  13682. var mipSize = width >> level;
  13683. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13684. var mipFaceData = mipData[level][faceIndex];
  13685. if (needConversion) {
  13686. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13687. }
  13688. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13689. }
  13690. }
  13691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13692. }
  13693. else {
  13694. texture.generateMipMaps = !noMipmap;
  13695. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13696. }
  13697. texture.isReady = true;
  13698. // this.resetTextureCache();
  13699. scene._removePendingData(texture);
  13700. if (onLoad) {
  13701. onLoad();
  13702. }
  13703. };
  13704. this._loadFile(url, function (data) {
  13705. internalCallback(data);
  13706. }, undefined, scene.database, true, onerror);
  13707. return texture;
  13708. };
  13709. ;
  13710. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13711. if (compression === void 0) { compression = null; }
  13712. var internalFormat = this._getInternalFormat(format);
  13713. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13714. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13715. if (!this._doNotHandleContextLost) {
  13716. texture._bufferView = data;
  13717. texture.format = format;
  13718. texture.invertY = invertY;
  13719. texture._compression = compression;
  13720. }
  13721. if (texture.width % 4 !== 0) {
  13722. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13723. }
  13724. if (compression && data) {
  13725. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13726. }
  13727. else {
  13728. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13729. }
  13730. if (texture.generateMipMaps) {
  13731. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13732. }
  13733. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13734. // this.resetTextureCache();
  13735. texture.isReady = true;
  13736. };
  13737. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13738. if (compression === void 0) { compression = null; }
  13739. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13740. texture.baseWidth = width;
  13741. texture.baseHeight = height;
  13742. texture.baseDepth = depth;
  13743. texture.width = width;
  13744. texture.height = height;
  13745. texture.depth = depth;
  13746. texture.format = format;
  13747. texture.generateMipMaps = generateMipMaps;
  13748. texture.samplingMode = samplingMode;
  13749. texture.is3D = true;
  13750. if (!this._doNotHandleContextLost) {
  13751. texture._bufferView = data;
  13752. }
  13753. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13754. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13755. // Filters
  13756. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13757. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13758. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13759. if (generateMipMaps) {
  13760. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13761. }
  13762. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13763. this._internalTexturesCache.push(texture);
  13764. return texture;
  13765. };
  13766. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13767. var gl = this._gl;
  13768. if (!gl) {
  13769. return;
  13770. }
  13771. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13774. if (!noMipmap && !isCompressed) {
  13775. gl.generateMipmap(gl.TEXTURE_2D);
  13776. }
  13777. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13778. // this.resetTextureCache();
  13779. if (scene) {
  13780. scene._removePendingData(texture);
  13781. }
  13782. texture.onLoadedObservable.notifyObservers(texture);
  13783. texture.onLoadedObservable.clear();
  13784. };
  13785. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13786. var _this = this;
  13787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13788. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13789. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13790. var gl = this._gl;
  13791. if (!gl) {
  13792. return;
  13793. }
  13794. if (!texture._webGLTexture) {
  13795. // this.resetTextureCache();
  13796. if (scene) {
  13797. scene._removePendingData(texture);
  13798. }
  13799. return;
  13800. }
  13801. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13802. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13803. texture.baseWidth = width;
  13804. texture.baseHeight = height;
  13805. texture.width = potWidth;
  13806. texture.height = potHeight;
  13807. texture.isReady = true;
  13808. if (processFunction(potWidth, potHeight, function () {
  13809. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13810. })) {
  13811. // Returning as texture needs extra async steps
  13812. return;
  13813. }
  13814. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13815. };
  13816. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13817. // Create new RGBA data container.
  13818. var rgbaData;
  13819. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13820. rgbaData = new Float32Array(width * height * 4);
  13821. }
  13822. else {
  13823. rgbaData = new Uint32Array(width * height * 4);
  13824. }
  13825. // Convert each pixel.
  13826. for (var x = 0; x < width; x++) {
  13827. for (var y = 0; y < height; y++) {
  13828. var index = (y * width + x) * 3;
  13829. var newIndex = (y * width + x) * 4;
  13830. // Map Old Value to new value.
  13831. rgbaData[newIndex + 0] = rgbData[index + 0];
  13832. rgbaData[newIndex + 1] = rgbData[index + 1];
  13833. rgbaData[newIndex + 2] = rgbData[index + 2];
  13834. // Add fully opaque alpha channel.
  13835. rgbaData[newIndex + 3] = 1;
  13836. }
  13837. }
  13838. return rgbaData;
  13839. };
  13840. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13841. var gl = this._gl;
  13842. if (texture._framebuffer) {
  13843. gl.deleteFramebuffer(texture._framebuffer);
  13844. texture._framebuffer = null;
  13845. }
  13846. if (texture._depthStencilBuffer) {
  13847. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13848. texture._depthStencilBuffer = null;
  13849. }
  13850. if (texture._MSAAFramebuffer) {
  13851. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13852. texture._MSAAFramebuffer = null;
  13853. }
  13854. if (texture._MSAARenderBuffer) {
  13855. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13856. texture._MSAARenderBuffer = null;
  13857. }
  13858. };
  13859. Engine.prototype._releaseTexture = function (texture) {
  13860. var gl = this._gl;
  13861. this._releaseFramebufferObjects(texture);
  13862. gl.deleteTexture(texture._webGLTexture);
  13863. // Unbind channels
  13864. this.unbindAllTextures();
  13865. var index = this._internalTexturesCache.indexOf(texture);
  13866. if (index !== -1) {
  13867. this._internalTexturesCache.splice(index, 1);
  13868. }
  13869. // Integrated fixed lod samplers.
  13870. if (texture._lodTextureHigh) {
  13871. texture._lodTextureHigh.dispose();
  13872. }
  13873. if (texture._lodTextureMid) {
  13874. texture._lodTextureMid.dispose();
  13875. }
  13876. if (texture._lodTextureLow) {
  13877. texture._lodTextureLow.dispose();
  13878. }
  13879. };
  13880. Engine.prototype.setProgram = function (program) {
  13881. if (this._currentProgram !== program) {
  13882. this._gl.useProgram(program);
  13883. this._currentProgram = program;
  13884. }
  13885. };
  13886. Engine.prototype.bindSamplers = function (effect) {
  13887. this.setProgram(effect.getProgram());
  13888. var samplers = effect.getSamplers();
  13889. for (var index = 0; index < samplers.length; index++) {
  13890. var uniform = effect.getUniform(samplers[index]);
  13891. if (uniform) {
  13892. this._boundUniforms[index] = uniform;
  13893. }
  13894. }
  13895. this._currentEffect = null;
  13896. };
  13897. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13898. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13899. return;
  13900. }
  13901. // Remove
  13902. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13903. // Bind last to it
  13904. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13905. // Bind to dummy
  13906. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13907. };
  13908. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13909. if (!internalTexture) {
  13910. return -1;
  13911. }
  13912. internalTexture._initialSlot = channel;
  13913. if (this.disableTextureBindingOptimization) {
  13914. if (channel !== internalTexture._designatedSlot) {
  13915. this._textureCollisions.addCount(1, false);
  13916. }
  13917. }
  13918. else {
  13919. if (channel !== internalTexture._designatedSlot) {
  13920. if (internalTexture._designatedSlot > -1) {
  13921. return internalTexture._designatedSlot;
  13922. }
  13923. else {
  13924. // No slot for this texture, let's pick a new one (if we find a free slot)
  13925. if (this._nextFreeTextureSlots.length) {
  13926. return this._nextFreeTextureSlots[0];
  13927. }
  13928. // We need to recycle the oldest bound texture, sorry.
  13929. this._textureCollisions.addCount(1, false);
  13930. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13931. }
  13932. }
  13933. }
  13934. return channel;
  13935. };
  13936. Engine.prototype._linkTrackers = function (previous, next) {
  13937. previous.next = next;
  13938. next.previous = previous;
  13939. };
  13940. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13941. var currentSlot = internalTexture._designatedSlot;
  13942. if (currentSlot === -1) {
  13943. return -1;
  13944. }
  13945. internalTexture._designatedSlot = -1;
  13946. if (this.disableTextureBindingOptimization) {
  13947. return -1;
  13948. }
  13949. // Remove from bound list
  13950. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13951. // Free the slot
  13952. this._boundTexturesCache[currentSlot] = null;
  13953. this._nextFreeTextureSlots.push(currentSlot);
  13954. return currentSlot;
  13955. };
  13956. Engine.prototype._activateCurrentTexture = function () {
  13957. if (this._currentTextureChannel !== this._activeChannel) {
  13958. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13959. this._currentTextureChannel = this._activeChannel;
  13960. }
  13961. };
  13962. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13963. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13964. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13965. this._activeChannel = texture._designatedSlot;
  13966. }
  13967. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13968. var isTextureForRendering = texture && texture._initialSlot > -1;
  13969. if (currentTextureBound !== texture) {
  13970. if (currentTextureBound) {
  13971. this._removeDesignatedSlot(currentTextureBound);
  13972. }
  13973. this._activateCurrentTexture();
  13974. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13975. this._boundTexturesCache[this._activeChannel] = texture;
  13976. if (texture) {
  13977. if (!this.disableTextureBindingOptimization) {
  13978. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13979. if (slotIndex > -1) {
  13980. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13981. }
  13982. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13983. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13984. }
  13985. texture._designatedSlot = this._activeChannel;
  13986. }
  13987. }
  13988. else if (forTextureDataUpdate) {
  13989. this._activateCurrentTexture();
  13990. }
  13991. if (isTextureForRendering && !forTextureDataUpdate) {
  13992. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13993. }
  13994. };
  13995. Engine.prototype._bindTexture = function (channel, texture) {
  13996. if (channel < 0) {
  13997. return;
  13998. }
  13999. if (texture) {
  14000. channel = this._getCorrectTextureChannel(channel, texture);
  14001. }
  14002. this._activeChannel = channel;
  14003. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14004. };
  14005. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14006. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14007. };
  14008. Engine.prototype.unbindAllTextures = function () {
  14009. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14010. this._activeChannel = channel;
  14011. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14012. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14013. if (this.webGLVersion > 1) {
  14014. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14015. }
  14016. }
  14017. };
  14018. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14019. if (channel < 0) {
  14020. return;
  14021. }
  14022. if (uniform) {
  14023. this._boundUniforms[channel] = uniform;
  14024. }
  14025. this._setTexture(channel, texture);
  14026. };
  14027. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14028. var uniform = this._boundUniforms[sourceSlot];
  14029. if (uniform._currentState === destination) {
  14030. return;
  14031. }
  14032. this._gl.uniform1i(uniform, destination);
  14033. uniform._currentState = destination;
  14034. };
  14035. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14036. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14037. // Not ready?
  14038. if (!texture) {
  14039. if (this._boundTexturesCache[channel] != null) {
  14040. this._activeChannel = channel;
  14041. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14042. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14043. if (this.webGLVersion > 1) {
  14044. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14045. }
  14046. }
  14047. return false;
  14048. }
  14049. // Video
  14050. if (texture.video) {
  14051. this._activeChannel = channel;
  14052. texture.update();
  14053. }
  14054. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14055. texture.delayLoad();
  14056. return false;
  14057. }
  14058. var internalTexture;
  14059. if (texture.isReady()) {
  14060. internalTexture = texture.getInternalTexture();
  14061. }
  14062. else if (texture.isCube) {
  14063. internalTexture = this.emptyCubeTexture;
  14064. }
  14065. else if (texture.is3D) {
  14066. internalTexture = this.emptyTexture3D;
  14067. }
  14068. else {
  14069. internalTexture = this.emptyTexture;
  14070. }
  14071. if (!isPartOfTextureArray) {
  14072. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14073. }
  14074. if (this._boundTexturesCache[channel] === internalTexture) {
  14075. this._moveBoundTextureOnTop(internalTexture);
  14076. if (!isPartOfTextureArray) {
  14077. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14078. }
  14079. return false;
  14080. }
  14081. this._activeChannel = channel;
  14082. if (internalTexture && internalTexture.is3D) {
  14083. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14084. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14085. internalTexture._cachedWrapU = texture.wrapU;
  14086. switch (texture.wrapU) {
  14087. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14088. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14089. break;
  14090. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14091. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14092. break;
  14093. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14094. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14095. break;
  14096. }
  14097. }
  14098. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14099. internalTexture._cachedWrapV = texture.wrapV;
  14100. switch (texture.wrapV) {
  14101. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14102. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14103. break;
  14104. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14105. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14106. break;
  14107. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14108. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14109. break;
  14110. }
  14111. }
  14112. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14113. internalTexture._cachedWrapR = texture.wrapR;
  14114. switch (texture.wrapV) {
  14115. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14116. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14117. break;
  14118. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14119. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14120. break;
  14121. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14122. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14123. break;
  14124. }
  14125. }
  14126. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14127. }
  14128. else if (internalTexture && internalTexture.isCube) {
  14129. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14130. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14131. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14132. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14133. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14134. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14135. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14136. }
  14137. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14138. }
  14139. else {
  14140. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14141. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14142. internalTexture._cachedWrapU = texture.wrapU;
  14143. switch (texture.wrapU) {
  14144. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14145. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14146. break;
  14147. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14148. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14149. break;
  14150. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14151. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14152. break;
  14153. }
  14154. }
  14155. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14156. internalTexture._cachedWrapV = texture.wrapV;
  14157. switch (texture.wrapV) {
  14158. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14159. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14160. break;
  14161. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14162. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14163. break;
  14164. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14165. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14166. break;
  14167. }
  14168. }
  14169. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14170. }
  14171. return true;
  14172. };
  14173. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14174. if (channel < 0 || !uniform) {
  14175. return;
  14176. }
  14177. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14178. this._textureUnits = new Int32Array(textures.length);
  14179. }
  14180. for (var i = 0; i < textures.length; i++) {
  14181. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14182. }
  14183. this._gl.uniform1iv(uniform, this._textureUnits);
  14184. for (var index = 0; index < textures.length; index++) {
  14185. this._setTexture(this._textureUnits[index], textures[index], true);
  14186. }
  14187. };
  14188. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14189. var internalTexture = texture.getInternalTexture();
  14190. if (!internalTexture) {
  14191. return;
  14192. }
  14193. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14194. var value = texture.anisotropicFilteringLevel;
  14195. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14196. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14197. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14198. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14199. }
  14200. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14201. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14202. internalTexture._cachedAnisotropicFilteringLevel = value;
  14203. }
  14204. };
  14205. Engine.prototype.readPixels = function (x, y, width, height) {
  14206. var data = new Uint8Array(height * width * 4);
  14207. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14208. return data;
  14209. };
  14210. /**
  14211. * Add an externaly attached data from its key.
  14212. * This method call will fail and return false, if such key already exists.
  14213. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14214. * @param key the unique key that identifies the data
  14215. * @param data the data object to associate to the key for this Engine instance
  14216. * @return true if no such key were already present and the data was added successfully, false otherwise
  14217. */
  14218. Engine.prototype.addExternalData = function (key, data) {
  14219. if (!this._externalData) {
  14220. this._externalData = new BABYLON.StringDictionary();
  14221. }
  14222. return this._externalData.add(key, data);
  14223. };
  14224. /**
  14225. * Get an externaly attached data from its key
  14226. * @param key the unique key that identifies the data
  14227. * @return the associated data, if present (can be null), or undefined if not present
  14228. */
  14229. Engine.prototype.getExternalData = function (key) {
  14230. if (!this._externalData) {
  14231. this._externalData = new BABYLON.StringDictionary();
  14232. }
  14233. return this._externalData.get(key);
  14234. };
  14235. /**
  14236. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14237. * @param key the unique key that identifies the data
  14238. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14239. * @return the associated data, can be null if the factory returned null.
  14240. */
  14241. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14242. if (!this._externalData) {
  14243. this._externalData = new BABYLON.StringDictionary();
  14244. }
  14245. return this._externalData.getOrAddWithFactory(key, factory);
  14246. };
  14247. /**
  14248. * Remove an externaly attached data from the Engine instance
  14249. * @param key the unique key that identifies the data
  14250. * @return true if the data was successfully removed, false if it doesn't exist
  14251. */
  14252. Engine.prototype.removeExternalData = function (key) {
  14253. if (!this._externalData) {
  14254. this._externalData = new BABYLON.StringDictionary();
  14255. }
  14256. return this._externalData.remove(key);
  14257. };
  14258. Engine.prototype.unbindAllAttributes = function () {
  14259. if (this._mustWipeVertexAttributes) {
  14260. this._mustWipeVertexAttributes = false;
  14261. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14262. this._gl.disableVertexAttribArray(i);
  14263. this._vertexAttribArraysEnabled[i] = false;
  14264. this._currentBufferPointers[i].active = false;
  14265. }
  14266. return;
  14267. }
  14268. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14269. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14270. continue;
  14271. }
  14272. this._gl.disableVertexAttribArray(i);
  14273. this._vertexAttribArraysEnabled[i] = false;
  14274. this._currentBufferPointers[i].active = false;
  14275. }
  14276. };
  14277. Engine.prototype.releaseEffects = function () {
  14278. for (var name in this._compiledEffects) {
  14279. this._deleteProgram(this._compiledEffects[name]._program);
  14280. }
  14281. this._compiledEffects = {};
  14282. };
  14283. // Dispose
  14284. Engine.prototype.dispose = function () {
  14285. this.hideLoadingUI();
  14286. this.stopRenderLoop();
  14287. // Release postProcesses
  14288. while (this.postProcesses.length) {
  14289. this.postProcesses[0].dispose();
  14290. }
  14291. // Empty texture
  14292. if (this._emptyTexture) {
  14293. this._releaseTexture(this._emptyTexture);
  14294. this._emptyTexture = null;
  14295. }
  14296. if (this._emptyCubeTexture) {
  14297. this._releaseTexture(this._emptyCubeTexture);
  14298. this._emptyCubeTexture = null;
  14299. }
  14300. // Rescale PP
  14301. if (this._rescalePostProcess) {
  14302. this._rescalePostProcess.dispose();
  14303. }
  14304. // Release scenes
  14305. while (this.scenes.length) {
  14306. this.scenes[0].dispose();
  14307. }
  14308. // Release audio engine
  14309. if (Engine.audioEngine) {
  14310. Engine.audioEngine.dispose();
  14311. }
  14312. // Release effects
  14313. this.releaseEffects();
  14314. // Unbind
  14315. this.unbindAllAttributes();
  14316. if (this._dummyFramebuffer) {
  14317. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14318. }
  14319. //WebVR
  14320. this.disableVR();
  14321. // Events
  14322. if (BABYLON.Tools.IsWindowObjectExist()) {
  14323. window.removeEventListener("blur", this._onBlur);
  14324. window.removeEventListener("focus", this._onFocus);
  14325. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14326. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14327. if (this._renderingCanvas) {
  14328. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14329. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14330. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14331. if (!this._doNotHandleContextLost) {
  14332. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14333. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14334. }
  14335. }
  14336. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14337. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14338. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14339. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14340. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14341. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14342. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14343. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14344. if (this._onVrDisplayConnect) {
  14345. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14346. if (this._onVrDisplayDisconnect) {
  14347. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14348. }
  14349. if (this._onVrDisplayPresentChange) {
  14350. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14351. }
  14352. this._onVrDisplayConnect = null;
  14353. this._onVrDisplayDisconnect = null;
  14354. }
  14355. }
  14356. // Remove from Instances
  14357. var index = Engine.Instances.indexOf(this);
  14358. if (index >= 0) {
  14359. Engine.Instances.splice(index, 1);
  14360. }
  14361. this._workingCanvas = null;
  14362. this._workingContext = null;
  14363. this._currentBufferPointers = [];
  14364. this._renderingCanvas = null;
  14365. this._currentProgram = null;
  14366. this.onResizeObservable.clear();
  14367. this.onCanvasBlurObservable.clear();
  14368. this.onCanvasFocusObservable.clear();
  14369. this.onCanvasPointerOutObservable.clear();
  14370. this.onBeginFrameObservable.clear();
  14371. this.onEndFrameObservable.clear();
  14372. BABYLON.Effect.ResetCache();
  14373. // Abort active requests
  14374. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14375. var request = _a[_i];
  14376. request.abort();
  14377. }
  14378. };
  14379. // Loading screen
  14380. Engine.prototype.displayLoadingUI = function () {
  14381. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14382. return;
  14383. }
  14384. var loadingScreen = this.loadingScreen;
  14385. if (loadingScreen) {
  14386. loadingScreen.displayLoadingUI();
  14387. }
  14388. };
  14389. Engine.prototype.hideLoadingUI = function () {
  14390. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14391. return;
  14392. }
  14393. var loadingScreen = this.loadingScreen;
  14394. if (loadingScreen) {
  14395. loadingScreen.hideLoadingUI();
  14396. }
  14397. };
  14398. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14399. get: function () {
  14400. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14401. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14402. return this._loadingScreen;
  14403. },
  14404. set: function (loadingScreen) {
  14405. this._loadingScreen = loadingScreen;
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14411. set: function (text) {
  14412. this.loadingScreen.loadingUIText = text;
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14418. set: function (color) {
  14419. this.loadingScreen.loadingUIBackgroundColor = color;
  14420. },
  14421. enumerable: true,
  14422. configurable: true
  14423. });
  14424. Engine.prototype.attachContextLostEvent = function (callback) {
  14425. if (this._renderingCanvas) {
  14426. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14427. }
  14428. };
  14429. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14430. if (this._renderingCanvas) {
  14431. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14432. }
  14433. };
  14434. Engine.prototype.getVertexShaderSource = function (program) {
  14435. var shaders = this._gl.getAttachedShaders(program);
  14436. if (!shaders) {
  14437. return null;
  14438. }
  14439. return this._gl.getShaderSource(shaders[0]);
  14440. };
  14441. Engine.prototype.getFragmentShaderSource = function (program) {
  14442. var shaders = this._gl.getAttachedShaders(program);
  14443. if (!shaders) {
  14444. return null;
  14445. }
  14446. return this._gl.getShaderSource(shaders[1]);
  14447. };
  14448. Engine.prototype.getError = function () {
  14449. return this._gl.getError();
  14450. };
  14451. // FPS
  14452. Engine.prototype.getFps = function () {
  14453. return this._fps;
  14454. };
  14455. Engine.prototype.getDeltaTime = function () {
  14456. return this._deltaTime;
  14457. };
  14458. Engine.prototype._measureFps = function () {
  14459. this._performanceMonitor.sampleFrame();
  14460. this._fps = this._performanceMonitor.averageFPS;
  14461. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14462. };
  14463. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14464. if (faceIndex === void 0) { faceIndex = -1; }
  14465. var gl = this._gl;
  14466. if (!this._dummyFramebuffer) {
  14467. var dummy = gl.createFramebuffer();
  14468. if (!dummy) {
  14469. throw new Error("Unable to create dummy framebuffer");
  14470. }
  14471. this._dummyFramebuffer = dummy;
  14472. }
  14473. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14474. if (faceIndex > -1) {
  14475. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14476. }
  14477. else {
  14478. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14479. }
  14480. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14481. var buffer;
  14482. switch (readType) {
  14483. case gl.UNSIGNED_BYTE:
  14484. buffer = new Uint8Array(4 * width * height);
  14485. readType = gl.UNSIGNED_BYTE;
  14486. break;
  14487. default:
  14488. buffer = new Float32Array(4 * width * height);
  14489. readType = gl.FLOAT;
  14490. break;
  14491. }
  14492. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14493. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14494. return buffer;
  14495. };
  14496. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14497. if (this._webGLVersion > 1) {
  14498. return this._caps.colorBufferFloat;
  14499. }
  14500. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14501. };
  14502. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14503. if (this._webGLVersion > 1) {
  14504. return this._caps.colorBufferFloat;
  14505. }
  14506. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14507. };
  14508. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14509. Engine.prototype._canRenderToFramebuffer = function (type) {
  14510. var gl = this._gl;
  14511. //clear existing errors
  14512. while (gl.getError() !== gl.NO_ERROR) { }
  14513. var successful = true;
  14514. var texture = gl.createTexture();
  14515. gl.bindTexture(gl.TEXTURE_2D, texture);
  14516. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14517. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14518. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14519. var fb = gl.createFramebuffer();
  14520. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14521. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14522. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14523. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14524. successful = successful && (gl.getError() === gl.NO_ERROR);
  14525. //try render by clearing frame buffer's color buffer
  14526. if (successful) {
  14527. gl.clear(gl.COLOR_BUFFER_BIT);
  14528. successful = successful && (gl.getError() === gl.NO_ERROR);
  14529. }
  14530. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14531. if (successful) {
  14532. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14533. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14534. var readFormat = gl.RGBA;
  14535. var readType = gl.UNSIGNED_BYTE;
  14536. var buffer = new Uint8Array(4);
  14537. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14538. successful = successful && (gl.getError() === gl.NO_ERROR);
  14539. }
  14540. //clean up
  14541. gl.deleteTexture(texture);
  14542. gl.deleteFramebuffer(fb);
  14543. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14544. //clear accumulated errors
  14545. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14546. return successful;
  14547. };
  14548. Engine.prototype._getWebGLTextureType = function (type) {
  14549. if (type === Engine.TEXTURETYPE_FLOAT) {
  14550. return this._gl.FLOAT;
  14551. }
  14552. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14553. // Add Half Float Constant.
  14554. return this._gl.HALF_FLOAT_OES;
  14555. }
  14556. return this._gl.UNSIGNED_BYTE;
  14557. };
  14558. ;
  14559. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14560. if (this._webGLVersion === 1) {
  14561. return this._gl.RGBA;
  14562. }
  14563. if (type === Engine.TEXTURETYPE_FLOAT) {
  14564. return this._gl.RGBA32F;
  14565. }
  14566. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14567. return this._gl.RGBA16F;
  14568. }
  14569. return this._gl.RGBA;
  14570. };
  14571. ;
  14572. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14573. if (type === Engine.TEXTURETYPE_FLOAT) {
  14574. return this._gl.RGBA32F;
  14575. }
  14576. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14577. return this._gl.RGBA16F;
  14578. }
  14579. return this._gl.RGBA8;
  14580. };
  14581. ;
  14582. Engine.prototype.createQuery = function () {
  14583. return this._gl.createQuery();
  14584. };
  14585. Engine.prototype.deleteQuery = function (query) {
  14586. this._gl.deleteQuery(query);
  14587. return this;
  14588. };
  14589. Engine.prototype.isQueryResultAvailable = function (query) {
  14590. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14591. };
  14592. Engine.prototype.getQueryResult = function (query) {
  14593. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14594. };
  14595. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14596. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14597. this._gl.beginQuery(glAlgorithm, query);
  14598. return this;
  14599. };
  14600. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14601. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14602. this._gl.endQuery(glAlgorithm);
  14603. return this;
  14604. };
  14605. /* Time queries */
  14606. Engine.prototype._createTimeQuery = function () {
  14607. var timerQuery = this._caps.timerQuery;
  14608. if (timerQuery.createQueryEXT) {
  14609. return timerQuery.createQueryEXT();
  14610. }
  14611. return this.createQuery();
  14612. };
  14613. Engine.prototype._deleteTimeQuery = function (query) {
  14614. var timerQuery = this._caps.timerQuery;
  14615. if (timerQuery.deleteQueryEXT) {
  14616. timerQuery.deleteQueryEXT(query);
  14617. return;
  14618. }
  14619. this.deleteQuery(query);
  14620. };
  14621. Engine.prototype._getTimeQueryResult = function (query) {
  14622. var timerQuery = this._caps.timerQuery;
  14623. if (timerQuery.getQueryObjectEXT) {
  14624. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14625. }
  14626. return this.getQueryResult(query);
  14627. };
  14628. Engine.prototype._getTimeQueryAvailability = function (query) {
  14629. var timerQuery = this._caps.timerQuery;
  14630. if (timerQuery.getQueryObjectEXT) {
  14631. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14632. }
  14633. return this.isQueryResultAvailable(query);
  14634. };
  14635. Engine.prototype.startTimeQuery = function () {
  14636. var timerQuery = this._caps.timerQuery;
  14637. if (!timerQuery) {
  14638. return null;
  14639. }
  14640. var token = new BABYLON._TimeToken();
  14641. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14642. if (this._caps.canUseTimestampForTimerQuery) {
  14643. token._startTimeQuery = this._createTimeQuery();
  14644. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14645. }
  14646. else {
  14647. if (this._currentNonTimestampToken) {
  14648. return this._currentNonTimestampToken;
  14649. }
  14650. token._timeElapsedQuery = this._createTimeQuery();
  14651. if (timerQuery.beginQueryEXT) {
  14652. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14653. }
  14654. else {
  14655. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14656. }
  14657. this._currentNonTimestampToken = token;
  14658. }
  14659. return token;
  14660. };
  14661. Engine.prototype.endTimeQuery = function (token) {
  14662. var timerQuery = this._caps.timerQuery;
  14663. if (!timerQuery || !token) {
  14664. return -1;
  14665. }
  14666. if (this._caps.canUseTimestampForTimerQuery) {
  14667. if (!token._startTimeQuery) {
  14668. return -1;
  14669. }
  14670. if (!token._endTimeQuery) {
  14671. token._endTimeQuery = this._createTimeQuery();
  14672. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14673. }
  14674. }
  14675. else if (!token._timeElapsedQueryEnded) {
  14676. if (!token._timeElapsedQuery) {
  14677. return -1;
  14678. }
  14679. if (timerQuery.endQueryEXT) {
  14680. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14681. }
  14682. else {
  14683. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14684. }
  14685. token._timeElapsedQueryEnded = true;
  14686. }
  14687. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14688. var available = false;
  14689. if (token._endTimeQuery) {
  14690. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14691. }
  14692. else if (token._timeElapsedQuery) {
  14693. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14694. }
  14695. if (available && !disjoint) {
  14696. var result = 0;
  14697. if (this._caps.canUseTimestampForTimerQuery) {
  14698. if (!token._startTimeQuery || !token._endTimeQuery) {
  14699. return -1;
  14700. }
  14701. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14702. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14703. result = timeEnd - timeStart;
  14704. this._deleteTimeQuery(token._startTimeQuery);
  14705. this._deleteTimeQuery(token._endTimeQuery);
  14706. token._startTimeQuery = null;
  14707. token._endTimeQuery = null;
  14708. }
  14709. else {
  14710. if (!token._timeElapsedQuery) {
  14711. return -1;
  14712. }
  14713. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14714. this._deleteTimeQuery(token._timeElapsedQuery);
  14715. token._timeElapsedQuery = null;
  14716. token._timeElapsedQueryEnded = false;
  14717. this._currentNonTimestampToken = null;
  14718. }
  14719. return result;
  14720. }
  14721. return -1;
  14722. };
  14723. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14724. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14725. };
  14726. // Transform feedback
  14727. Engine.prototype.createTransformFeedback = function () {
  14728. return this._gl.createTransformFeedback();
  14729. };
  14730. Engine.prototype.deleteTransformFeedback = function (value) {
  14731. this._gl.deleteTransformFeedback(value);
  14732. };
  14733. Engine.prototype.bindTransformFeedback = function (value) {
  14734. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14735. };
  14736. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14737. if (usePoints === void 0) { usePoints = true; }
  14738. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14739. };
  14740. Engine.prototype.endTransformFeedback = function () {
  14741. this._gl.endTransformFeedback();
  14742. };
  14743. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14744. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14745. };
  14746. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14747. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14748. };
  14749. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14750. var _this = this;
  14751. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14752. this._activeRequests.push(request);
  14753. request.onCompleteObservable.add(function (request) {
  14754. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14755. });
  14756. return request;
  14757. };
  14758. /** @ignore */
  14759. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14760. var _this = this;
  14761. return new Promise(function (resolve, reject) {
  14762. _this._loadFile(url, function (data) {
  14763. resolve(data);
  14764. }, undefined, database, useArrayBuffer, function (request, exception) {
  14765. reject(exception);
  14766. });
  14767. });
  14768. };
  14769. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14770. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14771. var onload = function (data) {
  14772. loadedFiles[index] = data;
  14773. loadedFiles._internalCount++;
  14774. if (loadedFiles._internalCount === 6) {
  14775. onfinish(loadedFiles);
  14776. }
  14777. };
  14778. var onerror = function (request, exception) {
  14779. if (onErrorCallBack && request) {
  14780. onErrorCallBack(request.status + " " + request.statusText, exception);
  14781. }
  14782. };
  14783. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14784. };
  14785. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14786. if (onError === void 0) { onError = null; }
  14787. var loadedFiles = [];
  14788. loadedFiles._internalCount = 0;
  14789. for (var index = 0; index < 6; index++) {
  14790. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14791. }
  14792. };
  14793. // Statics
  14794. Engine.isSupported = function () {
  14795. try {
  14796. var tempcanvas = document.createElement("canvas");
  14797. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14798. return gl != null && !!window.WebGLRenderingContext;
  14799. }
  14800. catch (e) {
  14801. return false;
  14802. }
  14803. };
  14804. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14805. Engine.ExceptionList = [
  14806. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14807. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14808. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14809. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14810. ];
  14811. Engine.Instances = new Array();
  14812. // Const statics
  14813. Engine._ALPHA_DISABLE = 0;
  14814. Engine._ALPHA_ADD = 1;
  14815. Engine._ALPHA_COMBINE = 2;
  14816. Engine._ALPHA_SUBTRACT = 3;
  14817. Engine._ALPHA_MULTIPLY = 4;
  14818. Engine._ALPHA_MAXIMIZED = 5;
  14819. Engine._ALPHA_ONEONE = 6;
  14820. Engine._ALPHA_PREMULTIPLIED = 7;
  14821. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14822. Engine._ALPHA_INTERPOLATE = 9;
  14823. Engine._ALPHA_SCREENMODE = 10;
  14824. Engine._DELAYLOADSTATE_NONE = 0;
  14825. Engine._DELAYLOADSTATE_LOADED = 1;
  14826. Engine._DELAYLOADSTATE_LOADING = 2;
  14827. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14828. Engine._TEXTUREFORMAT_ALPHA = 0;
  14829. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14830. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14831. Engine._TEXTUREFORMAT_RGB = 4;
  14832. Engine._TEXTUREFORMAT_RGBA = 5;
  14833. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14834. Engine._TEXTURETYPE_FLOAT = 1;
  14835. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14836. // Depht or Stencil test Constants.
  14837. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14838. 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.
  14839. 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.
  14840. 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.
  14841. 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.
  14842. 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.
  14843. 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.
  14844. 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.
  14845. // Stencil Actions Constants.
  14846. Engine._KEEP = 0x1E00;
  14847. Engine._REPLACE = 0x1E01;
  14848. Engine._INCR = 0x1E02;
  14849. Engine._DECR = 0x1E03;
  14850. Engine._INVERT = 0x150A;
  14851. Engine._INCR_WRAP = 0x8507;
  14852. Engine._DECR_WRAP = 0x8508;
  14853. // Texture rescaling mode
  14854. Engine._SCALEMODE_FLOOR = 1;
  14855. Engine._SCALEMODE_NEAREST = 2;
  14856. Engine._SCALEMODE_CEILING = 3;
  14857. // Updatable statics so stick with vars here
  14858. Engine.CollisionsEpsilon = 0.001;
  14859. Engine.CodeRepository = "src/";
  14860. Engine.ShadersRepository = "src/Shaders/";
  14861. return Engine;
  14862. }());
  14863. BABYLON.Engine = Engine;
  14864. })(BABYLON || (BABYLON = {}));
  14865. //# sourceMappingURL=babylon.engine.js.map
  14866. var BABYLON;
  14867. (function (BABYLON) {
  14868. /**
  14869. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14870. */
  14871. var Node = /** @class */ (function () {
  14872. /**
  14873. * @constructor
  14874. * @param {string} name - the name and id to be given to this node
  14875. * @param {BABYLON.Scene} the scene this node will be added to
  14876. */
  14877. function Node(name, scene) {
  14878. if (scene === void 0) { scene = null; }
  14879. this.state = "";
  14880. this.metadata = null;
  14881. this.doNotSerialize = false;
  14882. this.animations = new Array();
  14883. this._ranges = {};
  14884. this._isEnabled = true;
  14885. this._isReady = true;
  14886. this._currentRenderId = -1;
  14887. this._parentRenderId = -1;
  14888. /**
  14889. * An event triggered when the mesh is disposed.
  14890. * @type {BABYLON.Observable}
  14891. */
  14892. this.onDisposeObservable = new BABYLON.Observable();
  14893. // Behaviors
  14894. this._behaviors = new Array();
  14895. this.name = name;
  14896. this.id = name;
  14897. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14898. this.uniqueId = this._scene.getUniqueId();
  14899. this._initCache();
  14900. }
  14901. Object.defineProperty(Node.prototype, "parent", {
  14902. get: function () {
  14903. return this._parentNode;
  14904. },
  14905. set: function (parent) {
  14906. if (this._parentNode === parent) {
  14907. return;
  14908. }
  14909. // Remove self from list of children of parent
  14910. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14911. var index = this._parentNode._children.indexOf(this);
  14912. if (index !== -1) {
  14913. this._parentNode._children.splice(index, 1);
  14914. }
  14915. }
  14916. // Store new parent
  14917. this._parentNode = parent;
  14918. // Add as child to new parent
  14919. if (this._parentNode) {
  14920. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14921. this._parentNode._children = new Array();
  14922. }
  14923. this._parentNode._children.push(this);
  14924. }
  14925. },
  14926. enumerable: true,
  14927. configurable: true
  14928. });
  14929. Node.prototype.getClassName = function () {
  14930. return "Node";
  14931. };
  14932. Object.defineProperty(Node.prototype, "onDispose", {
  14933. set: function (callback) {
  14934. if (this._onDisposeObserver) {
  14935. this.onDisposeObservable.remove(this._onDisposeObserver);
  14936. }
  14937. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14938. },
  14939. enumerable: true,
  14940. configurable: true
  14941. });
  14942. Node.prototype.getScene = function () {
  14943. return this._scene;
  14944. };
  14945. Node.prototype.getEngine = function () {
  14946. return this._scene.getEngine();
  14947. };
  14948. Node.prototype.addBehavior = function (behavior) {
  14949. var _this = this;
  14950. var index = this._behaviors.indexOf(behavior);
  14951. if (index !== -1) {
  14952. return this;
  14953. }
  14954. behavior.init();
  14955. if (this._scene.isLoading) {
  14956. // We defer the attach when the scene will be loaded
  14957. var observer = this._scene.onDataLoadedObservable.add(function () {
  14958. behavior.attach(_this);
  14959. setTimeout(function () {
  14960. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14961. _this._scene.onDataLoadedObservable.remove(observer);
  14962. }, 0);
  14963. });
  14964. }
  14965. else {
  14966. behavior.attach(this);
  14967. }
  14968. this._behaviors.push(behavior);
  14969. return this;
  14970. };
  14971. Node.prototype.removeBehavior = function (behavior) {
  14972. var index = this._behaviors.indexOf(behavior);
  14973. if (index === -1) {
  14974. return this;
  14975. }
  14976. this._behaviors[index].detach();
  14977. this._behaviors.splice(index, 1);
  14978. return this;
  14979. };
  14980. Object.defineProperty(Node.prototype, "behaviors", {
  14981. get: function () {
  14982. return this._behaviors;
  14983. },
  14984. enumerable: true,
  14985. configurable: true
  14986. });
  14987. Node.prototype.getBehaviorByName = function (name) {
  14988. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14989. var behavior = _a[_i];
  14990. if (behavior.name === name) {
  14991. return behavior;
  14992. }
  14993. }
  14994. return null;
  14995. };
  14996. // override it in derived class
  14997. Node.prototype.getWorldMatrix = function () {
  14998. return BABYLON.Matrix.Identity();
  14999. };
  15000. // override it in derived class if you add new variables to the cache
  15001. // and call the parent class method
  15002. Node.prototype._initCache = function () {
  15003. this._cache = {};
  15004. this._cache.parent = undefined;
  15005. };
  15006. Node.prototype.updateCache = function (force) {
  15007. if (!force && this.isSynchronized())
  15008. return;
  15009. this._cache.parent = this.parent;
  15010. this._updateCache();
  15011. };
  15012. // override it in derived class if you add new variables to the cache
  15013. // and call the parent class method if !ignoreParentClass
  15014. Node.prototype._updateCache = function (ignoreParentClass) {
  15015. };
  15016. // override it in derived class if you add new variables to the cache
  15017. Node.prototype._isSynchronized = function () {
  15018. return true;
  15019. };
  15020. Node.prototype._markSyncedWithParent = function () {
  15021. if (this.parent) {
  15022. this._parentRenderId = this.parent._currentRenderId;
  15023. }
  15024. };
  15025. Node.prototype.isSynchronizedWithParent = function () {
  15026. if (!this.parent) {
  15027. return true;
  15028. }
  15029. if (this._parentRenderId !== this.parent._currentRenderId) {
  15030. return false;
  15031. }
  15032. return this.parent.isSynchronized();
  15033. };
  15034. Node.prototype.isSynchronized = function (updateCache) {
  15035. var check = this.hasNewParent();
  15036. check = check || !this.isSynchronizedWithParent();
  15037. check = check || !this._isSynchronized();
  15038. if (updateCache)
  15039. this.updateCache(true);
  15040. return !check;
  15041. };
  15042. Node.prototype.hasNewParent = function (update) {
  15043. if (this._cache.parent === this.parent)
  15044. return false;
  15045. if (update)
  15046. this._cache.parent = this.parent;
  15047. return true;
  15048. };
  15049. /**
  15050. * Is this node ready to be used/rendered
  15051. * @return {boolean} is it ready
  15052. */
  15053. Node.prototype.isReady = function () {
  15054. return this._isReady;
  15055. };
  15056. /**
  15057. * Is this node enabled.
  15058. * 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.
  15059. * @param {boolean} [checkAncestors=true] - 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.
  15060. * @return {boolean} whether this node (and its parent) is enabled.
  15061. * @see setEnabled
  15062. */
  15063. Node.prototype.isEnabled = function (checkAncestors) {
  15064. if (checkAncestors === void 0) { checkAncestors = true; }
  15065. if (checkAncestors === false) {
  15066. return this._isEnabled;
  15067. }
  15068. if (this._isEnabled === false) {
  15069. return false;
  15070. }
  15071. if (this.parent !== undefined && this.parent !== null) {
  15072. return this.parent.isEnabled(checkAncestors);
  15073. }
  15074. return true;
  15075. };
  15076. /**
  15077. * Set the enabled state of this node.
  15078. * @param {boolean} value - the new enabled state
  15079. * @see isEnabled
  15080. */
  15081. Node.prototype.setEnabled = function (value) {
  15082. this._isEnabled = value;
  15083. };
  15084. /**
  15085. * Is this node a descendant of the given node.
  15086. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  15087. * @param {BABYLON.Node} ancestor - The parent node to inspect
  15088. * @see parent
  15089. */
  15090. Node.prototype.isDescendantOf = function (ancestor) {
  15091. if (this.parent) {
  15092. if (this.parent === ancestor) {
  15093. return true;
  15094. }
  15095. return this.parent.isDescendantOf(ancestor);
  15096. }
  15097. return false;
  15098. };
  15099. /**
  15100. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  15101. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  15102. * @param {boolean} directDescendantsOnly 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.
  15103. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  15104. */
  15105. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15106. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15107. if (!this._children) {
  15108. return;
  15109. }
  15110. for (var index = 0; index < this._children.length; index++) {
  15111. var item = this._children[index];
  15112. if (!predicate || predicate(item)) {
  15113. results.push(item);
  15114. }
  15115. if (!directDescendantsOnly) {
  15116. item._getDescendants(results, false, predicate);
  15117. }
  15118. }
  15119. };
  15120. /**
  15121. * Will return all nodes that have this node as ascendant.
  15122. * @param {boolean} directDescendantsOnly 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.
  15123. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  15124. * @return {BABYLON.Node[]} all children nodes of all types.
  15125. */
  15126. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15127. var results = new Array();
  15128. this._getDescendants(results, directDescendantsOnly, predicate);
  15129. return results;
  15130. };
  15131. /**
  15132. * Get all child-meshes of this node.
  15133. */
  15134. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15135. var results = [];
  15136. this._getDescendants(results, directDescendantsOnly, function (node) {
  15137. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15138. });
  15139. return results;
  15140. };
  15141. /**
  15142. * Get all child-transformNodes of this node.
  15143. */
  15144. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15145. var results = [];
  15146. this._getDescendants(results, directDescendantsOnly, function (node) {
  15147. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15148. });
  15149. return results;
  15150. };
  15151. /**
  15152. * Get all direct children of this node.
  15153. */
  15154. Node.prototype.getChildren = function (predicate) {
  15155. return this.getDescendants(true, predicate);
  15156. };
  15157. Node.prototype._setReady = function (state) {
  15158. if (state === this._isReady) {
  15159. return;
  15160. }
  15161. if (!state) {
  15162. this._isReady = false;
  15163. return;
  15164. }
  15165. this._isReady = true;
  15166. if (this.onReady) {
  15167. this.onReady(this);
  15168. }
  15169. };
  15170. Node.prototype.getAnimationByName = function (name) {
  15171. for (var i = 0; i < this.animations.length; i++) {
  15172. var animation = this.animations[i];
  15173. if (animation.name === name) {
  15174. return animation;
  15175. }
  15176. }
  15177. return null;
  15178. };
  15179. Node.prototype.createAnimationRange = function (name, from, to) {
  15180. // check name not already in use
  15181. if (!this._ranges[name]) {
  15182. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15183. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15184. if (this.animations[i]) {
  15185. this.animations[i].createRange(name, from, to);
  15186. }
  15187. }
  15188. }
  15189. };
  15190. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15191. if (deleteFrames === void 0) { deleteFrames = true; }
  15192. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15193. if (this.animations[i]) {
  15194. this.animations[i].deleteRange(name, deleteFrames);
  15195. }
  15196. }
  15197. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15198. };
  15199. Node.prototype.getAnimationRange = function (name) {
  15200. return this._ranges[name];
  15201. };
  15202. /**
  15203. * Will start the animation sequence
  15204. * @param name defines the range frames for animation sequence
  15205. * @param loop defines if the animation should loop (false by default)
  15206. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15207. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15208. * @returns the {BABYLON.Animatable} object created for this animation. If range does not exist, it will return null
  15209. */
  15210. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15211. var range = this.getAnimationRange(name);
  15212. if (!range) {
  15213. return null;
  15214. }
  15215. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15216. };
  15217. Node.prototype.serializeAnimationRanges = function () {
  15218. var serializationRanges = [];
  15219. for (var name in this._ranges) {
  15220. var localRange = this._ranges[name];
  15221. if (!localRange) {
  15222. continue;
  15223. }
  15224. var range = {};
  15225. range.name = name;
  15226. range.from = localRange.from;
  15227. range.to = localRange.to;
  15228. serializationRanges.push(range);
  15229. }
  15230. return serializationRanges;
  15231. };
  15232. // override it in derived class
  15233. Node.prototype.computeWorldMatrix = function (force) {
  15234. return BABYLON.Matrix.Identity();
  15235. };
  15236. Node.prototype.dispose = function () {
  15237. this.parent = null;
  15238. // Callback
  15239. this.onDisposeObservable.notifyObservers(this);
  15240. this.onDisposeObservable.clear();
  15241. // Behaviors
  15242. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15243. var behavior = _a[_i];
  15244. behavior.detach();
  15245. }
  15246. this._behaviors = [];
  15247. };
  15248. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15249. if (parsedNode.ranges) {
  15250. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15251. var data = parsedNode.ranges[index];
  15252. node.createAnimationRange(data.name, data.from, data.to);
  15253. }
  15254. }
  15255. };
  15256. __decorate([
  15257. BABYLON.serialize()
  15258. ], Node.prototype, "name", void 0);
  15259. __decorate([
  15260. BABYLON.serialize()
  15261. ], Node.prototype, "id", void 0);
  15262. __decorate([
  15263. BABYLON.serialize()
  15264. ], Node.prototype, "uniqueId", void 0);
  15265. __decorate([
  15266. BABYLON.serialize()
  15267. ], Node.prototype, "state", void 0);
  15268. __decorate([
  15269. BABYLON.serialize()
  15270. ], Node.prototype, "metadata", void 0);
  15271. return Node;
  15272. }());
  15273. BABYLON.Node = Node;
  15274. })(BABYLON || (BABYLON = {}));
  15275. //# sourceMappingURL=babylon.node.js.map
  15276. var BABYLON;
  15277. (function (BABYLON) {
  15278. var BoundingSphere = /** @class */ (function () {
  15279. function BoundingSphere(minimum, maximum) {
  15280. this.minimum = minimum;
  15281. this.maximum = maximum;
  15282. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15283. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15284. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15285. this.radius = distance * 0.5;
  15286. this.centerWorld = BABYLON.Vector3.Zero();
  15287. this._update(BABYLON.Matrix.Identity());
  15288. }
  15289. // Methods
  15290. BoundingSphere.prototype._update = function (world) {
  15291. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15292. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15293. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15294. };
  15295. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15296. for (var i = 0; i < 6; i++) {
  15297. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15298. return false;
  15299. }
  15300. return true;
  15301. };
  15302. BoundingSphere.prototype.intersectsPoint = function (point) {
  15303. var x = this.centerWorld.x - point.x;
  15304. var y = this.centerWorld.y - point.y;
  15305. var z = this.centerWorld.z - point.z;
  15306. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15307. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15308. return false;
  15309. return true;
  15310. };
  15311. // Statics
  15312. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15313. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15314. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15315. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15316. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15317. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15318. return false;
  15319. return true;
  15320. };
  15321. return BoundingSphere;
  15322. }());
  15323. BABYLON.BoundingSphere = BoundingSphere;
  15324. })(BABYLON || (BABYLON = {}));
  15325. //# sourceMappingURL=babylon.boundingSphere.js.map
  15326. var BABYLON;
  15327. (function (BABYLON) {
  15328. var BoundingBox = /** @class */ (function () {
  15329. function BoundingBox(minimum, maximum) {
  15330. this.minimum = minimum;
  15331. this.maximum = maximum;
  15332. this.vectors = new Array();
  15333. this.vectorsWorld = new Array();
  15334. // Bounding vectors
  15335. this.vectors.push(this.minimum.clone());
  15336. this.vectors.push(this.maximum.clone());
  15337. this.vectors.push(this.minimum.clone());
  15338. this.vectors[2].x = this.maximum.x;
  15339. this.vectors.push(this.minimum.clone());
  15340. this.vectors[3].y = this.maximum.y;
  15341. this.vectors.push(this.minimum.clone());
  15342. this.vectors[4].z = this.maximum.z;
  15343. this.vectors.push(this.maximum.clone());
  15344. this.vectors[5].z = this.minimum.z;
  15345. this.vectors.push(this.maximum.clone());
  15346. this.vectors[6].x = this.minimum.x;
  15347. this.vectors.push(this.maximum.clone());
  15348. this.vectors[7].y = this.minimum.y;
  15349. // OBB
  15350. this.center = this.maximum.add(this.minimum).scale(0.5);
  15351. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15352. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15353. // World
  15354. for (var index = 0; index < this.vectors.length; index++) {
  15355. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15356. }
  15357. this.minimumWorld = BABYLON.Vector3.Zero();
  15358. this.maximumWorld = BABYLON.Vector3.Zero();
  15359. this.centerWorld = BABYLON.Vector3.Zero();
  15360. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15361. this._update(BABYLON.Matrix.Identity());
  15362. }
  15363. // Methods
  15364. BoundingBox.prototype.getWorldMatrix = function () {
  15365. return this._worldMatrix;
  15366. };
  15367. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15368. this._worldMatrix.copyFrom(matrix);
  15369. return this;
  15370. };
  15371. BoundingBox.prototype._update = function (world) {
  15372. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15373. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15374. for (var index = 0; index < this.vectors.length; index++) {
  15375. var v = this.vectorsWorld[index];
  15376. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15377. if (v.x < this.minimumWorld.x)
  15378. this.minimumWorld.x = v.x;
  15379. if (v.y < this.minimumWorld.y)
  15380. this.minimumWorld.y = v.y;
  15381. if (v.z < this.minimumWorld.z)
  15382. this.minimumWorld.z = v.z;
  15383. if (v.x > this.maximumWorld.x)
  15384. this.maximumWorld.x = v.x;
  15385. if (v.y > this.maximumWorld.y)
  15386. this.maximumWorld.y = v.y;
  15387. if (v.z > this.maximumWorld.z)
  15388. this.maximumWorld.z = v.z;
  15389. }
  15390. // Extend
  15391. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15392. this.extendSizeWorld.scaleInPlace(0.5);
  15393. // OBB
  15394. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15395. this.centerWorld.scaleInPlace(0.5);
  15396. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15397. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15398. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15399. this._worldMatrix = world;
  15400. };
  15401. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15402. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15403. };
  15404. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15405. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15406. };
  15407. BoundingBox.prototype.intersectsPoint = function (point) {
  15408. var delta = -BABYLON.Epsilon;
  15409. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15410. return false;
  15411. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15412. return false;
  15413. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15414. return false;
  15415. return true;
  15416. };
  15417. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15418. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15419. };
  15420. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15421. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15422. return false;
  15423. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15424. return false;
  15425. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15426. return false;
  15427. return true;
  15428. };
  15429. // Statics
  15430. BoundingBox.Intersects = function (box0, box1) {
  15431. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15432. return false;
  15433. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15434. return false;
  15435. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15436. return false;
  15437. return true;
  15438. };
  15439. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15440. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15441. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15442. return (num <= (sphereRadius * sphereRadius));
  15443. };
  15444. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15445. for (var p = 0; p < 6; p++) {
  15446. for (var i = 0; i < 8; i++) {
  15447. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15448. return false;
  15449. }
  15450. }
  15451. }
  15452. return true;
  15453. };
  15454. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15455. for (var p = 0; p < 6; p++) {
  15456. var inCount = 8;
  15457. for (var i = 0; i < 8; i++) {
  15458. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15459. --inCount;
  15460. }
  15461. else {
  15462. break;
  15463. }
  15464. }
  15465. if (inCount === 0)
  15466. return false;
  15467. }
  15468. return true;
  15469. };
  15470. return BoundingBox;
  15471. }());
  15472. BABYLON.BoundingBox = BoundingBox;
  15473. })(BABYLON || (BABYLON = {}));
  15474. //# sourceMappingURL=babylon.boundingBox.js.map
  15475. var BABYLON;
  15476. (function (BABYLON) {
  15477. var computeBoxExtents = function (axis, box) {
  15478. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15479. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15480. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15481. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15482. var r = r0 + r1 + r2;
  15483. return {
  15484. min: p - r,
  15485. max: p + r
  15486. };
  15487. };
  15488. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15489. var axisOverlap = function (axis, box0, box1) {
  15490. var result0 = computeBoxExtents(axis, box0);
  15491. var result1 = computeBoxExtents(axis, box1);
  15492. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15493. };
  15494. var BoundingInfo = /** @class */ (function () {
  15495. function BoundingInfo(minimum, maximum) {
  15496. this.minimum = minimum;
  15497. this.maximum = maximum;
  15498. this._isLocked = false;
  15499. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15500. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15501. }
  15502. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15503. get: function () {
  15504. return this._isLocked;
  15505. },
  15506. set: function (value) {
  15507. this._isLocked = value;
  15508. },
  15509. enumerable: true,
  15510. configurable: true
  15511. });
  15512. // Methods
  15513. BoundingInfo.prototype.update = function (world) {
  15514. if (this._isLocked) {
  15515. return;
  15516. }
  15517. this.boundingBox._update(world);
  15518. this.boundingSphere._update(world);
  15519. };
  15520. /**
  15521. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15522. * @param center New center of the bounding info
  15523. * @param extend New extend of the bounding info
  15524. */
  15525. BoundingInfo.prototype.centerOn = function (center, extend) {
  15526. this.minimum = center.subtract(extend);
  15527. this.maximum = center.add(extend);
  15528. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15529. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15530. return this;
  15531. };
  15532. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15533. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15534. return false;
  15535. return this.boundingBox.isInFrustum(frustumPlanes);
  15536. };
  15537. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15538. /**
  15539. * Gets the world distance between the min and max points of the bounding box
  15540. */
  15541. get: function () {
  15542. var boundingBox = this.boundingBox;
  15543. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15544. return size.length();
  15545. },
  15546. enumerable: true,
  15547. configurable: true
  15548. });
  15549. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15550. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15551. };
  15552. BoundingInfo.prototype._checkCollision = function (collider) {
  15553. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15554. };
  15555. BoundingInfo.prototype.intersectsPoint = function (point) {
  15556. if (!this.boundingSphere.centerWorld) {
  15557. return false;
  15558. }
  15559. if (!this.boundingSphere.intersectsPoint(point)) {
  15560. return false;
  15561. }
  15562. if (!this.boundingBox.intersectsPoint(point)) {
  15563. return false;
  15564. }
  15565. return true;
  15566. };
  15567. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15568. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15569. return false;
  15570. }
  15571. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15572. return false;
  15573. }
  15574. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15575. return false;
  15576. }
  15577. if (!precise) {
  15578. return true;
  15579. }
  15580. var box0 = this.boundingBox;
  15581. var box1 = boundingInfo.boundingBox;
  15582. if (!axisOverlap(box0.directions[0], box0, box1))
  15583. return false;
  15584. if (!axisOverlap(box0.directions[1], box0, box1))
  15585. return false;
  15586. if (!axisOverlap(box0.directions[2], box0, box1))
  15587. return false;
  15588. if (!axisOverlap(box1.directions[0], box0, box1))
  15589. return false;
  15590. if (!axisOverlap(box1.directions[1], box0, box1))
  15591. return false;
  15592. if (!axisOverlap(box1.directions[2], box0, box1))
  15593. return false;
  15594. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15595. return false;
  15596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15597. return false;
  15598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15599. return false;
  15600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15601. return false;
  15602. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15603. return false;
  15604. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15605. return false;
  15606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15607. return false;
  15608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15609. return false;
  15610. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15611. return false;
  15612. return true;
  15613. };
  15614. return BoundingInfo;
  15615. }());
  15616. BABYLON.BoundingInfo = BoundingInfo;
  15617. })(BABYLON || (BABYLON = {}));
  15618. //# sourceMappingURL=babylon.boundingInfo.js.map
  15619. var BABYLON;
  15620. (function (BABYLON) {
  15621. var TransformNode = /** @class */ (function (_super) {
  15622. __extends(TransformNode, _super);
  15623. function TransformNode(name, scene, isPure) {
  15624. if (scene === void 0) { scene = null; }
  15625. if (isPure === void 0) { isPure = true; }
  15626. var _this = _super.call(this, name, scene) || this;
  15627. // Properties
  15628. _this._rotation = BABYLON.Vector3.Zero();
  15629. _this._scaling = BABYLON.Vector3.One();
  15630. _this._isDirty = false;
  15631. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15632. _this.scalingDeterminant = 1;
  15633. _this.infiniteDistance = false;
  15634. _this.position = BABYLON.Vector3.Zero();
  15635. _this._localWorld = BABYLON.Matrix.Zero();
  15636. _this._worldMatrix = BABYLON.Matrix.Zero();
  15637. _this._worldMatrixDeterminant = 0;
  15638. _this._absolutePosition = BABYLON.Vector3.Zero();
  15639. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15640. _this._postMultiplyPivotMatrix = false;
  15641. _this._isWorldMatrixFrozen = false;
  15642. /**
  15643. * An event triggered after the world matrix is updated
  15644. * @type {BABYLON.Observable}
  15645. */
  15646. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15647. _this._nonUniformScaling = false;
  15648. if (isPure) {
  15649. _this.getScene().addTransformNode(_this);
  15650. }
  15651. return _this;
  15652. }
  15653. Object.defineProperty(TransformNode.prototype, "rotation", {
  15654. /**
  15655. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15656. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15657. * Default : (0.0, 0.0, 0.0)
  15658. */
  15659. get: function () {
  15660. return this._rotation;
  15661. },
  15662. set: function (newRotation) {
  15663. this._rotation = newRotation;
  15664. },
  15665. enumerable: true,
  15666. configurable: true
  15667. });
  15668. Object.defineProperty(TransformNode.prototype, "scaling", {
  15669. /**
  15670. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15671. * Default : (1.0, 1.0, 1.0)
  15672. */
  15673. get: function () {
  15674. return this._scaling;
  15675. },
  15676. /**
  15677. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15678. * Default : (1.0, 1.0, 1.0)
  15679. */
  15680. set: function (newScaling) {
  15681. this._scaling = newScaling;
  15682. },
  15683. enumerable: true,
  15684. configurable: true
  15685. });
  15686. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15687. /**
  15688. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15689. * It's null by default.
  15690. * 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)
  15691. */
  15692. get: function () {
  15693. return this._rotationQuaternion;
  15694. },
  15695. set: function (quaternion) {
  15696. this._rotationQuaternion = quaternion;
  15697. //reset the rotation vector.
  15698. if (quaternion && this.rotation.length()) {
  15699. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15700. }
  15701. },
  15702. enumerable: true,
  15703. configurable: true
  15704. });
  15705. /**
  15706. * Returns the latest update of the World matrix
  15707. * Returns a Matrix.
  15708. */
  15709. TransformNode.prototype.getWorldMatrix = function () {
  15710. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15711. this.computeWorldMatrix();
  15712. }
  15713. return this._worldMatrix;
  15714. };
  15715. /**
  15716. * Returns the latest update of the World matrix determinant.
  15717. */
  15718. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15719. return this._worldMatrixDeterminant;
  15720. };
  15721. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15722. /**
  15723. * Returns directly the latest state of the mesh World matrix.
  15724. * A Matrix is returned.
  15725. */
  15726. get: function () {
  15727. return this._worldMatrix;
  15728. },
  15729. enumerable: true,
  15730. configurable: true
  15731. });
  15732. /**
  15733. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15734. * Returns the AbstractMesh.
  15735. */
  15736. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15737. this._poseMatrix.copyFrom(matrix);
  15738. return this;
  15739. };
  15740. /**
  15741. * Returns the mesh Pose matrix.
  15742. * Returned object : Matrix
  15743. */
  15744. TransformNode.prototype.getPoseMatrix = function () {
  15745. return this._poseMatrix;
  15746. };
  15747. TransformNode.prototype._isSynchronized = function () {
  15748. if (this._isDirty) {
  15749. return false;
  15750. }
  15751. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15752. return false;
  15753. if (this._cache.pivotMatrixUpdated) {
  15754. return false;
  15755. }
  15756. if (this.infiniteDistance) {
  15757. return false;
  15758. }
  15759. if (!this._cache.position.equals(this.position))
  15760. return false;
  15761. if (this.rotationQuaternion) {
  15762. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15763. return false;
  15764. }
  15765. if (!this._cache.rotation.equals(this.rotation))
  15766. return false;
  15767. if (!this._cache.scaling.equals(this.scaling))
  15768. return false;
  15769. return true;
  15770. };
  15771. TransformNode.prototype._initCache = function () {
  15772. _super.prototype._initCache.call(this);
  15773. this._cache.localMatrixUpdated = false;
  15774. this._cache.position = BABYLON.Vector3.Zero();
  15775. this._cache.scaling = BABYLON.Vector3.Zero();
  15776. this._cache.rotation = BABYLON.Vector3.Zero();
  15777. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15778. this._cache.billboardMode = -1;
  15779. };
  15780. TransformNode.prototype.markAsDirty = function (property) {
  15781. if (property === "rotation") {
  15782. this.rotationQuaternion = null;
  15783. }
  15784. this._currentRenderId = Number.MAX_VALUE;
  15785. this._isDirty = true;
  15786. return this;
  15787. };
  15788. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15789. /**
  15790. * Returns the current mesh absolute position.
  15791. * Retuns a Vector3.
  15792. */
  15793. get: function () {
  15794. return this._absolutePosition;
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. /**
  15800. * Sets a new matrix to apply before all other transformation
  15801. * @param matrix defines the transform matrix
  15802. * @returns the current TransformNode
  15803. */
  15804. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15805. return this.setPivotMatrix(matrix, false);
  15806. };
  15807. /**
  15808. * Sets a new pivot matrix to the current node
  15809. * @param matrix defines the new pivot matrix to use
  15810. * @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
  15811. * @returns the current TransformNode
  15812. */
  15813. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15814. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15815. this._pivotMatrix = matrix.clone();
  15816. this._cache.pivotMatrixUpdated = true;
  15817. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15818. if (this._postMultiplyPivotMatrix) {
  15819. if (!this._pivotMatrixInverse) {
  15820. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15821. }
  15822. else {
  15823. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15824. }
  15825. }
  15826. return this;
  15827. };
  15828. /**
  15829. * Returns the mesh pivot matrix.
  15830. * Default : Identity.
  15831. * A Matrix is returned.
  15832. */
  15833. TransformNode.prototype.getPivotMatrix = function () {
  15834. return this._pivotMatrix;
  15835. };
  15836. /**
  15837. * Prevents the World matrix to be computed any longer.
  15838. * Returns the AbstractMesh.
  15839. */
  15840. TransformNode.prototype.freezeWorldMatrix = function () {
  15841. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15842. this.computeWorldMatrix(true);
  15843. this._isWorldMatrixFrozen = true;
  15844. return this;
  15845. };
  15846. /**
  15847. * Allows back the World matrix computation.
  15848. * Returns the AbstractMesh.
  15849. */
  15850. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15851. this._isWorldMatrixFrozen = false;
  15852. this.computeWorldMatrix(true);
  15853. return this;
  15854. };
  15855. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15856. /**
  15857. * True if the World matrix has been frozen.
  15858. * Returns a boolean.
  15859. */
  15860. get: function () {
  15861. return this._isWorldMatrixFrozen;
  15862. },
  15863. enumerable: true,
  15864. configurable: true
  15865. });
  15866. /**
  15867. * Retuns the mesh absolute position in the World.
  15868. * Returns a Vector3.
  15869. */
  15870. TransformNode.prototype.getAbsolutePosition = function () {
  15871. this.computeWorldMatrix();
  15872. return this._absolutePosition;
  15873. };
  15874. /**
  15875. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15876. * Returns the AbstractMesh.
  15877. */
  15878. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15879. if (!absolutePosition) {
  15880. return this;
  15881. }
  15882. var absolutePositionX;
  15883. var absolutePositionY;
  15884. var absolutePositionZ;
  15885. if (absolutePosition.x === undefined) {
  15886. if (arguments.length < 3) {
  15887. return this;
  15888. }
  15889. absolutePositionX = arguments[0];
  15890. absolutePositionY = arguments[1];
  15891. absolutePositionZ = arguments[2];
  15892. }
  15893. else {
  15894. absolutePositionX = absolutePosition.x;
  15895. absolutePositionY = absolutePosition.y;
  15896. absolutePositionZ = absolutePosition.z;
  15897. }
  15898. if (this.parent) {
  15899. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15900. invertParentWorldMatrix.invert();
  15901. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15902. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15903. }
  15904. else {
  15905. this.position.x = absolutePositionX;
  15906. this.position.y = absolutePositionY;
  15907. this.position.z = absolutePositionZ;
  15908. }
  15909. return this;
  15910. };
  15911. /**
  15912. * Sets the mesh position in its local space.
  15913. * Returns the AbstractMesh.
  15914. */
  15915. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15916. this.computeWorldMatrix();
  15917. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15918. return this;
  15919. };
  15920. /**
  15921. * Returns the mesh position in the local space from the current World matrix values.
  15922. * Returns a new Vector3.
  15923. */
  15924. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15925. this.computeWorldMatrix();
  15926. var invLocalWorldMatrix = this._localWorld.clone();
  15927. invLocalWorldMatrix.invert();
  15928. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15929. };
  15930. /**
  15931. * Translates the mesh along the passed Vector3 in its local space.
  15932. * Returns the AbstractMesh.
  15933. */
  15934. TransformNode.prototype.locallyTranslate = function (vector3) {
  15935. this.computeWorldMatrix(true);
  15936. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15937. return this;
  15938. };
  15939. /**
  15940. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15941. * @param targetPoint the position (must be in same space as current mesh) to look at
  15942. * @param yawCor optional yaw (y-axis) correction in radians
  15943. * @param pitchCor optional pitch (x-axis) correction in radians
  15944. * @param rollCor optional roll (z-axis) correction in radians
  15945. * @param space the choosen space of the target
  15946. * @returns the TransformNode.
  15947. */
  15948. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15949. if (yawCor === void 0) { yawCor = 0; }
  15950. if (pitchCor === void 0) { pitchCor = 0; }
  15951. if (rollCor === void 0) { rollCor = 0; }
  15952. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15953. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15954. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15955. targetPoint.subtractToRef(pos, dv);
  15956. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15957. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15958. var pitch = Math.atan2(dv.y, len);
  15959. if (this.rotationQuaternion) {
  15960. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15961. }
  15962. else {
  15963. this.rotation.x = pitch + pitchCor;
  15964. this.rotation.y = yaw + yawCor;
  15965. this.rotation.z = rollCor;
  15966. }
  15967. return this;
  15968. };
  15969. /**
  15970. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15971. * This Vector3 is expressed in the World space.
  15972. */
  15973. TransformNode.prototype.getDirection = function (localAxis) {
  15974. var result = BABYLON.Vector3.Zero();
  15975. this.getDirectionToRef(localAxis, result);
  15976. return result;
  15977. };
  15978. /**
  15979. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15980. * localAxis is expressed in the mesh local space.
  15981. * result is computed in the Wordl space from the mesh World matrix.
  15982. * Returns the AbstractMesh.
  15983. */
  15984. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15985. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15986. return this;
  15987. };
  15988. /**
  15989. * Sets a new pivot point to the current node
  15990. * @param point defines the new pivot point to use
  15991. * @param space defines if the point is in world or local space (local by default)
  15992. * @returns the current TransformNode
  15993. */
  15994. TransformNode.prototype.setPivotPoint = function (point, space) {
  15995. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15996. if (this.getScene().getRenderId() == 0) {
  15997. this.computeWorldMatrix(true);
  15998. }
  15999. var wm = this.getWorldMatrix();
  16000. if (space == BABYLON.Space.WORLD) {
  16001. var tmat = BABYLON.Tmp.Matrix[0];
  16002. wm.invertToRef(tmat);
  16003. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16004. }
  16005. return this.setPivotMatrix(BABYLON.Matrix.Translation(point.x, point.y, point.z), true);
  16006. };
  16007. /**
  16008. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16009. */
  16010. TransformNode.prototype.getPivotPoint = function () {
  16011. var point = BABYLON.Vector3.Zero();
  16012. this.getPivotPointToRef(point);
  16013. return point;
  16014. };
  16015. /**
  16016. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16017. * Returns the AbstractMesh.
  16018. */
  16019. TransformNode.prototype.getPivotPointToRef = function (result) {
  16020. result.x = -this._pivotMatrix.m[12];
  16021. result.y = -this._pivotMatrix.m[13];
  16022. result.z = -this._pivotMatrix.m[14];
  16023. return this;
  16024. };
  16025. /**
  16026. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16027. */
  16028. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16029. var point = BABYLON.Vector3.Zero();
  16030. this.getAbsolutePivotPointToRef(point);
  16031. return point;
  16032. };
  16033. /**
  16034. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16035. * Returns the AbstractMesh.
  16036. */
  16037. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16038. result.x = this._pivotMatrix.m[12];
  16039. result.y = this._pivotMatrix.m[13];
  16040. result.z = this._pivotMatrix.m[14];
  16041. this.getPivotPointToRef(result);
  16042. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16043. return this;
  16044. };
  16045. /**
  16046. * Defines the passed node as the parent of the current node.
  16047. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16048. * Returns the TransformNode.
  16049. */
  16050. TransformNode.prototype.setParent = function (node) {
  16051. if (node === null) {
  16052. var rotation = BABYLON.Tmp.Quaternion[0];
  16053. var position = BABYLON.Tmp.Vector3[0];
  16054. var scale = BABYLON.Tmp.Vector3[1];
  16055. if (this.parent && this.parent.computeWorldMatrix) {
  16056. this.parent.computeWorldMatrix(true);
  16057. }
  16058. this.computeWorldMatrix(true);
  16059. this.getWorldMatrix().decompose(scale, rotation, position);
  16060. if (this.rotationQuaternion) {
  16061. this.rotationQuaternion.copyFrom(rotation);
  16062. }
  16063. else {
  16064. rotation.toEulerAnglesToRef(this.rotation);
  16065. }
  16066. this.scaling.x = scale.x;
  16067. this.scaling.y = scale.y;
  16068. this.scaling.z = scale.z;
  16069. this.position.x = position.x;
  16070. this.position.y = position.y;
  16071. this.position.z = position.z;
  16072. }
  16073. else {
  16074. var rotation = BABYLON.Tmp.Quaternion[0];
  16075. var position = BABYLON.Tmp.Vector3[0];
  16076. var scale = BABYLON.Tmp.Vector3[1];
  16077. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16078. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16079. this.computeWorldMatrix(true);
  16080. node.computeWorldMatrix(true);
  16081. node.getWorldMatrix().invertToRef(invParentMatrix);
  16082. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16083. diffMatrix.decompose(scale, rotation, position);
  16084. if (this.rotationQuaternion) {
  16085. this.rotationQuaternion.copyFrom(rotation);
  16086. }
  16087. else {
  16088. rotation.toEulerAnglesToRef(this.rotation);
  16089. }
  16090. this.position.x = position.x;
  16091. this.position.y = position.y;
  16092. this.position.z = position.z;
  16093. this.scaling.x = scale.x;
  16094. this.scaling.y = scale.y;
  16095. this.scaling.z = scale.z;
  16096. }
  16097. this.parent = node;
  16098. return this;
  16099. };
  16100. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16101. get: function () {
  16102. return this._nonUniformScaling;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16108. if (this._nonUniformScaling === value) {
  16109. return false;
  16110. }
  16111. this._nonUniformScaling = true;
  16112. return true;
  16113. };
  16114. /**
  16115. * Attach the current TransformNode to another TransformNode associated with a bone
  16116. * @param bone Bone affecting the TransformNode
  16117. * @param affectedTransformNode TransformNode associated with the bone
  16118. */
  16119. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16120. this._transformToBoneReferal = affectedTransformNode;
  16121. this.parent = bone;
  16122. if (bone.getWorldMatrix().determinant() < 0) {
  16123. this.scalingDeterminant *= -1;
  16124. }
  16125. return this;
  16126. };
  16127. TransformNode.prototype.detachFromBone = function () {
  16128. if (!this.parent) {
  16129. return this;
  16130. }
  16131. if (this.parent.getWorldMatrix().determinant() < 0) {
  16132. this.scalingDeterminant *= -1;
  16133. }
  16134. this._transformToBoneReferal = null;
  16135. this.parent = null;
  16136. return this;
  16137. };
  16138. /**
  16139. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16140. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16141. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16142. * The passed axis is also normalized.
  16143. * Returns the AbstractMesh.
  16144. */
  16145. TransformNode.prototype.rotate = function (axis, amount, space) {
  16146. axis.normalize();
  16147. if (!this.rotationQuaternion) {
  16148. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16149. this.rotation = BABYLON.Vector3.Zero();
  16150. }
  16151. var rotationQuaternion;
  16152. if (!space || space === BABYLON.Space.LOCAL) {
  16153. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16154. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16155. }
  16156. else {
  16157. if (this.parent) {
  16158. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16159. invertParentWorldMatrix.invert();
  16160. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16161. }
  16162. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16163. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16164. }
  16165. return this;
  16166. };
  16167. /**
  16168. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16169. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16170. * The passed axis is also normalized.
  16171. * Returns the AbstractMesh.
  16172. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16173. */
  16174. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16175. axis.normalize();
  16176. if (!this.rotationQuaternion) {
  16177. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16178. this.rotation.copyFromFloats(0, 0, 0);
  16179. }
  16180. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16181. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16182. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16183. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16184. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16185. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16186. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16187. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16188. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16189. return this;
  16190. };
  16191. /**
  16192. * Translates the mesh along the axis vector for the passed distance in the given space.
  16193. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16194. * Returns the AbstractMesh.
  16195. */
  16196. TransformNode.prototype.translate = function (axis, distance, space) {
  16197. var displacementVector = axis.scale(distance);
  16198. if (!space || space === BABYLON.Space.LOCAL) {
  16199. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16200. this.setPositionWithLocalVector(tempV3);
  16201. }
  16202. else {
  16203. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16204. }
  16205. return this;
  16206. };
  16207. /**
  16208. * Adds a rotation step to the mesh current rotation.
  16209. * x, y, z are Euler angles expressed in radians.
  16210. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16211. * This means this rotation is made in the mesh local space only.
  16212. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16213. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16214. * ```javascript
  16215. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16216. * ```
  16217. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16218. * 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.
  16219. * Returns the AbstractMesh.
  16220. */
  16221. TransformNode.prototype.addRotation = function (x, y, z) {
  16222. var rotationQuaternion;
  16223. if (this.rotationQuaternion) {
  16224. rotationQuaternion = this.rotationQuaternion;
  16225. }
  16226. else {
  16227. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16228. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16229. }
  16230. var accumulation = BABYLON.Tmp.Quaternion[0];
  16231. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16232. rotationQuaternion.multiplyInPlace(accumulation);
  16233. if (!this.rotationQuaternion) {
  16234. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16235. }
  16236. return this;
  16237. };
  16238. /**
  16239. * Computes the mesh World matrix and returns it.
  16240. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16241. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16242. * If the parameter `force`is set to `true`, the actual computation is done.
  16243. * Returns the mesh World Matrix.
  16244. */
  16245. TransformNode.prototype.computeWorldMatrix = function (force) {
  16246. if (this._isWorldMatrixFrozen) {
  16247. return this._worldMatrix;
  16248. }
  16249. if (!force && this.isSynchronized(true)) {
  16250. return this._worldMatrix;
  16251. }
  16252. this._cache.position.copyFrom(this.position);
  16253. this._cache.scaling.copyFrom(this.scaling);
  16254. this._cache.pivotMatrixUpdated = false;
  16255. this._cache.billboardMode = this.billboardMode;
  16256. this._currentRenderId = this.getScene().getRenderId();
  16257. this._isDirty = false;
  16258. // Scaling
  16259. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16260. // Rotation
  16261. //rotate, if quaternion is set and rotation was used
  16262. if (this.rotationQuaternion) {
  16263. var len = this.rotation.length();
  16264. if (len) {
  16265. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16266. this.rotation.copyFromFloats(0, 0, 0);
  16267. }
  16268. }
  16269. if (this.rotationQuaternion) {
  16270. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16271. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16272. }
  16273. else {
  16274. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16275. this._cache.rotation.copyFrom(this.rotation);
  16276. }
  16277. // Translation
  16278. var camera = this.getScene().activeCamera;
  16279. if (this.infiniteDistance && !this.parent && camera) {
  16280. var cameraWorldMatrix = camera.getWorldMatrix();
  16281. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16282. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16283. }
  16284. else {
  16285. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16286. }
  16287. // Composing transformations
  16288. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16289. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16290. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16291. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16292. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16293. // Need to decompose each rotation here
  16294. var currentPosition = BABYLON.Tmp.Vector3[3];
  16295. if (this.parent && this.parent.getWorldMatrix) {
  16296. if (this._transformToBoneReferal) {
  16297. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16298. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16299. }
  16300. else {
  16301. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16302. }
  16303. }
  16304. else {
  16305. currentPosition.copyFrom(this.position);
  16306. }
  16307. currentPosition.subtractInPlace(camera.globalPosition);
  16308. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16309. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16310. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16311. }
  16312. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16313. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16314. }
  16315. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16316. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16317. }
  16318. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16319. }
  16320. else {
  16321. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16322. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16323. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16324. }
  16325. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16326. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16327. }
  16328. // Local world
  16329. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16330. // Parent
  16331. if (this.parent && this.parent.getWorldMatrix) {
  16332. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16333. if (this._transformToBoneReferal) {
  16334. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16335. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16336. }
  16337. else {
  16338. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16339. }
  16340. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16341. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16342. this._worldMatrix.copyFrom(this._localWorld);
  16343. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16344. }
  16345. else {
  16346. if (this._transformToBoneReferal) {
  16347. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16348. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16349. }
  16350. else {
  16351. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16352. }
  16353. }
  16354. this._markSyncedWithParent();
  16355. }
  16356. else {
  16357. this._worldMatrix.copyFrom(this._localWorld);
  16358. }
  16359. // Post multiply inverse of pivotMatrix
  16360. if (this._postMultiplyPivotMatrix) {
  16361. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16362. }
  16363. // Normal matrix
  16364. if (this.scaling.isNonUniform) {
  16365. this._updateNonUniformScalingState(true);
  16366. }
  16367. else if (this.parent && this.parent._nonUniformScaling) {
  16368. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16369. }
  16370. else {
  16371. this._updateNonUniformScalingState(false);
  16372. }
  16373. this._afterComputeWorldMatrix();
  16374. // Absolute position
  16375. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16376. // Callbacks
  16377. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16378. if (!this._poseMatrix) {
  16379. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16380. }
  16381. // Cache the determinant
  16382. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16383. return this._worldMatrix;
  16384. };
  16385. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16386. };
  16387. /**
  16388. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16389. * @param func: callback function to add
  16390. *
  16391. * Returns the TransformNode.
  16392. */
  16393. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16394. this.onAfterWorldMatrixUpdateObservable.add(func);
  16395. return this;
  16396. };
  16397. /**
  16398. * Removes a registered callback function.
  16399. * Returns the TransformNode.
  16400. */
  16401. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16402. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16403. return this;
  16404. };
  16405. /**
  16406. * Clone the current transform node
  16407. * Returns the new transform node
  16408. * @param name Name of the new clone
  16409. * @param newParent New parent for the clone
  16410. * @param doNotCloneChildren Do not clone children hierarchy
  16411. */
  16412. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16413. var _this = this;
  16414. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16415. result.name = name;
  16416. result.id = name;
  16417. if (newParent) {
  16418. result.parent = newParent;
  16419. }
  16420. if (!doNotCloneChildren) {
  16421. // Children
  16422. var directDescendants = this.getDescendants(true);
  16423. for (var index = 0; index < directDescendants.length; index++) {
  16424. var child = directDescendants[index];
  16425. if (child.clone) {
  16426. child.clone(name + "." + child.name, result);
  16427. }
  16428. }
  16429. }
  16430. return result;
  16431. };
  16432. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16433. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16434. serializationObject.type = this.getClassName();
  16435. // Parent
  16436. if (this.parent) {
  16437. serializationObject.parentId = this.parent.id;
  16438. }
  16439. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16440. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16441. }
  16442. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16443. serializationObject.isEnabled = this.isEnabled();
  16444. // Parent
  16445. if (this.parent) {
  16446. serializationObject.parentId = this.parent.id;
  16447. }
  16448. return serializationObject;
  16449. };
  16450. // Statics
  16451. /**
  16452. * Returns a new TransformNode object parsed from the source provided.
  16453. * The parameter `parsedMesh` is the source.
  16454. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16455. */
  16456. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16457. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16458. if (BABYLON.Tags) {
  16459. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16460. }
  16461. if (parsedTransformNode.localMatrix) {
  16462. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16463. }
  16464. else if (parsedTransformNode.pivotMatrix) {
  16465. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16466. }
  16467. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16468. // Parent
  16469. if (parsedTransformNode.parentId) {
  16470. transformNode._waitingParentId = parsedTransformNode.parentId;
  16471. }
  16472. return transformNode;
  16473. };
  16474. /**
  16475. * Disposes the TransformNode.
  16476. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16477. * Returns nothing.
  16478. */
  16479. TransformNode.prototype.dispose = function (doNotRecurse) {
  16480. // Animations
  16481. this.getScene().stopAnimation(this);
  16482. // Remove from scene
  16483. this.getScene().removeTransformNode(this);
  16484. if (!doNotRecurse) {
  16485. // Children
  16486. var objects = this.getDescendants(true);
  16487. for (var index = 0; index < objects.length; index++) {
  16488. objects[index].dispose();
  16489. }
  16490. }
  16491. else {
  16492. var childMeshes = this.getChildMeshes(true);
  16493. for (index = 0; index < childMeshes.length; index++) {
  16494. var child = childMeshes[index];
  16495. child.parent = null;
  16496. child.computeWorldMatrix(true);
  16497. }
  16498. }
  16499. this.onAfterWorldMatrixUpdateObservable.clear();
  16500. _super.prototype.dispose.call(this);
  16501. };
  16502. // Statics
  16503. TransformNode.BILLBOARDMODE_NONE = 0;
  16504. TransformNode.BILLBOARDMODE_X = 1;
  16505. TransformNode.BILLBOARDMODE_Y = 2;
  16506. TransformNode.BILLBOARDMODE_Z = 4;
  16507. TransformNode.BILLBOARDMODE_ALL = 7;
  16508. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16509. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16510. __decorate([
  16511. BABYLON.serializeAsVector3()
  16512. ], TransformNode.prototype, "_rotation", void 0);
  16513. __decorate([
  16514. BABYLON.serializeAsQuaternion()
  16515. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16516. __decorate([
  16517. BABYLON.serializeAsVector3()
  16518. ], TransformNode.prototype, "_scaling", void 0);
  16519. __decorate([
  16520. BABYLON.serialize()
  16521. ], TransformNode.prototype, "billboardMode", void 0);
  16522. __decorate([
  16523. BABYLON.serialize()
  16524. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16525. __decorate([
  16526. BABYLON.serialize()
  16527. ], TransformNode.prototype, "infiniteDistance", void 0);
  16528. __decorate([
  16529. BABYLON.serializeAsVector3()
  16530. ], TransformNode.prototype, "position", void 0);
  16531. return TransformNode;
  16532. }(BABYLON.Node));
  16533. BABYLON.TransformNode = TransformNode;
  16534. })(BABYLON || (BABYLON = {}));
  16535. //# sourceMappingURL=babylon.transformNode.js.map
  16536. var BABYLON;
  16537. (function (BABYLON) {
  16538. var AbstractMesh = /** @class */ (function (_super) {
  16539. __extends(AbstractMesh, _super);
  16540. // Constructor
  16541. function AbstractMesh(name, scene) {
  16542. if (scene === void 0) { scene = null; }
  16543. var _this = _super.call(this, name, scene, false) || this;
  16544. _this._facetNb = 0; // facet number
  16545. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16546. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16547. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16548. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16549. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16550. _this._subDiv = {
  16551. max: 1,
  16552. X: 1,
  16553. Y: 1,
  16554. Z: 1
  16555. };
  16556. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16557. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16558. // Events
  16559. /**
  16560. * An event triggered when this mesh collides with another one
  16561. * @type {BABYLON.Observable}
  16562. */
  16563. _this.onCollideObservable = new BABYLON.Observable();
  16564. /**
  16565. * An event triggered when the collision's position changes
  16566. * @type {BABYLON.Observable}
  16567. */
  16568. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16569. /**
  16570. * An event triggered when material is changed
  16571. * @type {BABYLON.Observable}
  16572. */
  16573. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16574. // Properties
  16575. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16576. /**
  16577. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16578. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16579. * or
  16580. * 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.
  16581. * for more info check WebGl documentations
  16582. */
  16583. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16584. /**
  16585. * 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:
  16586. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16587. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16588. * 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.
  16589. */
  16590. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16591. /**
  16592. * 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.
  16593. * The default value is -1 which means don't break the query and wait till the result.
  16594. */
  16595. _this.occlusionRetryCount = -1;
  16596. _this._occlusionInternalRetryCounter = 0;
  16597. _this._isOccluded = false;
  16598. _this._isOcclusionQueryInProgress = false;
  16599. _this._visibility = 1.0;
  16600. _this.alphaIndex = Number.MAX_VALUE;
  16601. _this.isVisible = true;
  16602. _this.isPickable = true;
  16603. _this.showBoundingBox = false;
  16604. _this.showSubMeshesBoundingBox = false;
  16605. _this.isBlocker = false;
  16606. _this.enablePointerMoveEvents = false;
  16607. _this.renderingGroupId = 0;
  16608. _this._receiveShadows = false;
  16609. _this.renderOutline = false;
  16610. _this.outlineColor = BABYLON.Color3.Red();
  16611. _this.outlineWidth = 0.02;
  16612. _this.renderOverlay = false;
  16613. _this.overlayColor = BABYLON.Color3.Red();
  16614. _this.overlayAlpha = 0.5;
  16615. _this._hasVertexAlpha = false;
  16616. _this._useVertexColors = true;
  16617. _this._computeBonesUsingShaders = true;
  16618. _this._numBoneInfluencers = 4;
  16619. _this._applyFog = true;
  16620. _this.useOctreeForRenderingSelection = true;
  16621. _this.useOctreeForPicking = true;
  16622. _this.useOctreeForCollisions = true;
  16623. _this._layerMask = 0x0FFFFFFF;
  16624. /**
  16625. * True if the mesh must be rendered in any case.
  16626. */
  16627. _this.alwaysSelectAsActiveMesh = false;
  16628. /**
  16629. * This scene's action manager
  16630. * @type {BABYLON.ActionManager}
  16631. */
  16632. _this.actionManager = null;
  16633. // Physics
  16634. _this.physicsImpostor = null;
  16635. // Collisions
  16636. _this._checkCollisions = false;
  16637. _this._collisionMask = -1;
  16638. _this._collisionGroup = -1;
  16639. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16640. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16641. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16642. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16643. // Edges
  16644. _this.edgesWidth = 1;
  16645. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16646. // Cache
  16647. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16648. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16649. _this._isDisposed = false;
  16650. _this._renderId = 0;
  16651. _this._intersectionsInProgress = new Array();
  16652. _this._unIndexed = false;
  16653. _this._lightSources = new Array();
  16654. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16655. if (collidedMesh === void 0) { collidedMesh = null; }
  16656. //TODO move this to the collision coordinator!
  16657. if (_this.getScene().workerCollisions)
  16658. newPosition.multiplyInPlace(_this._collider._radius);
  16659. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16660. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16661. _this.position.addInPlace(_this._diffPositionForCollisions);
  16662. }
  16663. if (collidedMesh) {
  16664. _this.onCollideObservable.notifyObservers(collidedMesh);
  16665. }
  16666. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16667. };
  16668. _this.getScene().addMesh(_this);
  16669. _this._resyncLightSources();
  16670. return _this;
  16671. }
  16672. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16673. get: function () {
  16674. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16675. },
  16676. enumerable: true,
  16677. configurable: true
  16678. });
  16679. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16680. get: function () {
  16681. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16682. },
  16683. enumerable: true,
  16684. configurable: true
  16685. });
  16686. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16687. get: function () {
  16688. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16689. },
  16690. enumerable: true,
  16691. configurable: true
  16692. });
  16693. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16694. get: function () {
  16695. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16696. },
  16697. enumerable: true,
  16698. configurable: true
  16699. });
  16700. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16701. get: function () {
  16702. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16708. /**
  16709. * Read-only : the number of facets in the mesh
  16710. */
  16711. get: function () {
  16712. return this._facetNb;
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16718. /**
  16719. * The number (integer) of subdivisions per axis in the partioning space
  16720. */
  16721. get: function () {
  16722. return this._partitioningSubdivisions;
  16723. },
  16724. set: function (nb) {
  16725. this._partitioningSubdivisions = nb;
  16726. },
  16727. enumerable: true,
  16728. configurable: true
  16729. });
  16730. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16731. /**
  16732. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16733. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16734. */
  16735. get: function () {
  16736. return this._partitioningBBoxRatio;
  16737. },
  16738. set: function (ratio) {
  16739. this._partitioningBBoxRatio = ratio;
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16745. /**
  16746. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16747. * Works only for updatable meshes.
  16748. * Doesn't work with multi-materials.
  16749. */
  16750. get: function () {
  16751. return this._facetDepthSort;
  16752. },
  16753. set: function (sort) {
  16754. this._facetDepthSort = sort;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16760. /**
  16761. * The location (Vector3) where the facet depth sort must be computed from.
  16762. * By default, the active camera position.
  16763. * Used only when facet depth sort is enabled.
  16764. */
  16765. get: function () {
  16766. return this._facetDepthSortFrom;
  16767. },
  16768. set: function (location) {
  16769. this._facetDepthSortFrom = location;
  16770. },
  16771. enumerable: true,
  16772. configurable: true
  16773. });
  16774. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16775. /**
  16776. * Read-only boolean : is the feature facetData enabled ?
  16777. */
  16778. get: function () {
  16779. return this._facetDataEnabled;
  16780. },
  16781. enumerable: true,
  16782. configurable: true
  16783. });
  16784. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16785. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16786. return false;
  16787. }
  16788. this._markSubMeshesAsMiscDirty();
  16789. return true;
  16790. };
  16791. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16792. set: function (callback) {
  16793. if (this._onCollideObserver) {
  16794. this.onCollideObservable.remove(this._onCollideObserver);
  16795. }
  16796. this._onCollideObserver = this.onCollideObservable.add(callback);
  16797. },
  16798. enumerable: true,
  16799. configurable: true
  16800. });
  16801. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16802. set: function (callback) {
  16803. if (this._onCollisionPositionChangeObserver) {
  16804. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16805. }
  16806. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16807. },
  16808. enumerable: true,
  16809. configurable: true
  16810. });
  16811. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16812. /**
  16813. * 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.
  16814. */
  16815. get: function () {
  16816. return this._isOccluded;
  16817. },
  16818. set: function (value) {
  16819. this._isOccluded = value;
  16820. },
  16821. enumerable: true,
  16822. configurable: true
  16823. });
  16824. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16825. /**
  16826. * Flag to check the progress status of the query
  16827. */
  16828. get: function () {
  16829. return this._isOcclusionQueryInProgress;
  16830. },
  16831. enumerable: true,
  16832. configurable: true
  16833. });
  16834. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16835. /**
  16836. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16837. */
  16838. get: function () {
  16839. return this._visibility;
  16840. },
  16841. /**
  16842. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16843. */
  16844. set: function (value) {
  16845. if (this._visibility === value) {
  16846. return;
  16847. }
  16848. this._visibility = value;
  16849. this._markSubMeshesAsMiscDirty();
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(AbstractMesh.prototype, "material", {
  16855. get: function () {
  16856. return this._material;
  16857. },
  16858. set: function (value) {
  16859. if (this._material === value) {
  16860. return;
  16861. }
  16862. this._material = value;
  16863. if (this.onMaterialChangedObservable.hasObservers) {
  16864. this.onMaterialChangedObservable.notifyObservers(this);
  16865. }
  16866. if (!this.subMeshes) {
  16867. return;
  16868. }
  16869. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16870. var subMesh = _a[_i];
  16871. subMesh.setEffect(null);
  16872. }
  16873. },
  16874. enumerable: true,
  16875. configurable: true
  16876. });
  16877. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16878. get: function () {
  16879. return this._receiveShadows;
  16880. },
  16881. set: function (value) {
  16882. if (this._receiveShadows === value) {
  16883. return;
  16884. }
  16885. this._receiveShadows = value;
  16886. this._markSubMeshesAsLightDirty();
  16887. },
  16888. enumerable: true,
  16889. configurable: true
  16890. });
  16891. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16892. get: function () {
  16893. return this._hasVertexAlpha;
  16894. },
  16895. set: function (value) {
  16896. if (this._hasVertexAlpha === value) {
  16897. return;
  16898. }
  16899. this._hasVertexAlpha = value;
  16900. this._markSubMeshesAsAttributesDirty();
  16901. this._markSubMeshesAsMiscDirty();
  16902. },
  16903. enumerable: true,
  16904. configurable: true
  16905. });
  16906. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16907. get: function () {
  16908. return this._useVertexColors;
  16909. },
  16910. set: function (value) {
  16911. if (this._useVertexColors === value) {
  16912. return;
  16913. }
  16914. this._useVertexColors = value;
  16915. this._markSubMeshesAsAttributesDirty();
  16916. },
  16917. enumerable: true,
  16918. configurable: true
  16919. });
  16920. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16921. get: function () {
  16922. return this._computeBonesUsingShaders;
  16923. },
  16924. set: function (value) {
  16925. if (this._computeBonesUsingShaders === value) {
  16926. return;
  16927. }
  16928. this._computeBonesUsingShaders = value;
  16929. this._markSubMeshesAsAttributesDirty();
  16930. },
  16931. enumerable: true,
  16932. configurable: true
  16933. });
  16934. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16935. get: function () {
  16936. return this._numBoneInfluencers;
  16937. },
  16938. set: function (value) {
  16939. if (this._numBoneInfluencers === value) {
  16940. return;
  16941. }
  16942. this._numBoneInfluencers = value;
  16943. this._markSubMeshesAsAttributesDirty();
  16944. },
  16945. enumerable: true,
  16946. configurable: true
  16947. });
  16948. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16949. get: function () {
  16950. return this._applyFog;
  16951. },
  16952. set: function (value) {
  16953. if (this._applyFog === value) {
  16954. return;
  16955. }
  16956. this._applyFog = value;
  16957. this._markSubMeshesAsMiscDirty();
  16958. },
  16959. enumerable: true,
  16960. configurable: true
  16961. });
  16962. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16963. get: function () {
  16964. return this._layerMask;
  16965. },
  16966. set: function (value) {
  16967. if (value === this._layerMask) {
  16968. return;
  16969. }
  16970. this._layerMask = value;
  16971. this._resyncLightSources();
  16972. },
  16973. enumerable: true,
  16974. configurable: true
  16975. });
  16976. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16977. get: function () {
  16978. return this._collisionMask;
  16979. },
  16980. set: function (mask) {
  16981. this._collisionMask = !isNaN(mask) ? mask : -1;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16987. get: function () {
  16988. return this._collisionGroup;
  16989. },
  16990. set: function (mask) {
  16991. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16992. },
  16993. enumerable: true,
  16994. configurable: true
  16995. });
  16996. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16997. get: function () {
  16998. return null;
  16999. },
  17000. enumerable: true,
  17001. configurable: true
  17002. });
  17003. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17004. get: function () {
  17005. return this._skeleton;
  17006. },
  17007. set: function (value) {
  17008. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17009. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17010. }
  17011. if (value && value.needInitialSkinMatrix) {
  17012. value._registerMeshWithPoseMatrix(this);
  17013. }
  17014. this._skeleton = value;
  17015. if (!this._skeleton) {
  17016. this._bonesTransformMatrices = null;
  17017. }
  17018. this._markSubMeshesAsAttributesDirty();
  17019. },
  17020. enumerable: true,
  17021. configurable: true
  17022. });
  17023. /**
  17024. * Boolean : true if the mesh has been disposed.
  17025. */
  17026. AbstractMesh.prototype.isDisposed = function () {
  17027. return this._isDisposed;
  17028. };
  17029. /**
  17030. * Returns the string "AbstractMesh"
  17031. */
  17032. AbstractMesh.prototype.getClassName = function () {
  17033. return "AbstractMesh";
  17034. };
  17035. /**
  17036. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17037. */
  17038. AbstractMesh.prototype.toString = function (fullDetails) {
  17039. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17040. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17041. if (this._skeleton) {
  17042. ret += ", skeleton: " + this._skeleton.name;
  17043. }
  17044. if (fullDetails) {
  17045. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17046. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17047. }
  17048. return ret;
  17049. };
  17050. AbstractMesh.prototype._rebuild = function () {
  17051. if (this._occlusionQuery) {
  17052. this._occlusionQuery = null;
  17053. }
  17054. if (this._edgesRenderer) {
  17055. this._edgesRenderer._rebuild();
  17056. }
  17057. if (!this.subMeshes) {
  17058. return;
  17059. }
  17060. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17061. var subMesh = _a[_i];
  17062. subMesh._rebuild();
  17063. }
  17064. };
  17065. AbstractMesh.prototype._resyncLightSources = function () {
  17066. this._lightSources.length = 0;
  17067. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17068. var light = _a[_i];
  17069. if (!light.isEnabled()) {
  17070. continue;
  17071. }
  17072. if (light.canAffectMesh(this)) {
  17073. this._lightSources.push(light);
  17074. }
  17075. }
  17076. this._markSubMeshesAsLightDirty();
  17077. };
  17078. AbstractMesh.prototype._resyncLighSource = function (light) {
  17079. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17080. var index = this._lightSources.indexOf(light);
  17081. if (index === -1) {
  17082. if (!isIn) {
  17083. return;
  17084. }
  17085. this._lightSources.push(light);
  17086. }
  17087. else {
  17088. if (isIn) {
  17089. return;
  17090. }
  17091. this._lightSources.splice(index, 1);
  17092. }
  17093. this._markSubMeshesAsLightDirty();
  17094. };
  17095. AbstractMesh.prototype._removeLightSource = function (light) {
  17096. var index = this._lightSources.indexOf(light);
  17097. if (index === -1) {
  17098. return;
  17099. }
  17100. this._lightSources.splice(index, 1);
  17101. this._markSubMeshesAsLightDirty();
  17102. };
  17103. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17104. if (!this.subMeshes) {
  17105. return;
  17106. }
  17107. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17108. var subMesh = _a[_i];
  17109. if (subMesh._materialDefines) {
  17110. func(subMesh._materialDefines);
  17111. }
  17112. }
  17113. };
  17114. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17115. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17116. };
  17117. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17118. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17119. };
  17120. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17121. if (!this.subMeshes) {
  17122. return;
  17123. }
  17124. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17125. var subMesh = _a[_i];
  17126. var material = subMesh.getMaterial();
  17127. if (material) {
  17128. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17129. }
  17130. }
  17131. };
  17132. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17133. /**
  17134. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17135. * Default : (1.0, 1.0, 1.0)
  17136. */
  17137. get: function () {
  17138. return this._scaling;
  17139. },
  17140. /**
  17141. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17142. * Default : (1.0, 1.0, 1.0)
  17143. */
  17144. set: function (newScaling) {
  17145. this._scaling = newScaling;
  17146. if (this.physicsImpostor) {
  17147. this.physicsImpostor.forceUpdate();
  17148. }
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. // Methods
  17154. /**
  17155. * Disables the mesh edger rendering mode.
  17156. * Returns the AbstractMesh.
  17157. */
  17158. AbstractMesh.prototype.disableEdgesRendering = function () {
  17159. if (this._edgesRenderer) {
  17160. this._edgesRenderer.dispose();
  17161. this._edgesRenderer = null;
  17162. }
  17163. return this;
  17164. };
  17165. /**
  17166. * Enables the edge rendering mode on the mesh.
  17167. * This mode makes the mesh edges visible.
  17168. * Returns the AbstractMesh.
  17169. */
  17170. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17171. if (epsilon === void 0) { epsilon = 0.95; }
  17172. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17173. this.disableEdgesRendering();
  17174. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17175. return this;
  17176. };
  17177. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17178. /**
  17179. * Returns true if the mesh is blocked. Used by the class Mesh.
  17180. * Returns the boolean `false` by default.
  17181. */
  17182. get: function () {
  17183. return false;
  17184. },
  17185. enumerable: true,
  17186. configurable: true
  17187. });
  17188. /**
  17189. * Returns the mesh itself by default, used by the class Mesh.
  17190. * Returned type : AbstractMesh
  17191. */
  17192. AbstractMesh.prototype.getLOD = function (camera) {
  17193. return this;
  17194. };
  17195. /**
  17196. * Returns 0 by default, used by the class Mesh.
  17197. * Returns an integer.
  17198. */
  17199. AbstractMesh.prototype.getTotalVertices = function () {
  17200. return 0;
  17201. };
  17202. /**
  17203. * Returns null by default, used by the class Mesh.
  17204. * Returned type : integer array
  17205. */
  17206. AbstractMesh.prototype.getIndices = function () {
  17207. return null;
  17208. };
  17209. /**
  17210. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17211. * Returned type : float array or Float32Array
  17212. */
  17213. AbstractMesh.prototype.getVerticesData = function (kind) {
  17214. return null;
  17215. };
  17216. /**
  17217. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17218. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17219. * The `data` are either a numeric array either a Float32Array.
  17220. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17221. * 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).
  17222. * Note that a new underlying VertexBuffer object is created each call.
  17223. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17224. *
  17225. * Possible `kind` values :
  17226. * - BABYLON.VertexBuffer.PositionKind
  17227. * - BABYLON.VertexBuffer.UVKind
  17228. * - BABYLON.VertexBuffer.UV2Kind
  17229. * - BABYLON.VertexBuffer.UV3Kind
  17230. * - BABYLON.VertexBuffer.UV4Kind
  17231. * - BABYLON.VertexBuffer.UV5Kind
  17232. * - BABYLON.VertexBuffer.UV6Kind
  17233. * - BABYLON.VertexBuffer.ColorKind
  17234. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17235. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17236. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17237. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17238. *
  17239. * Returns the Mesh.
  17240. */
  17241. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17242. return this;
  17243. };
  17244. /**
  17245. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17246. * If the mesh has no geometry, it is simply returned as it is.
  17247. * The `data` are either a numeric array either a Float32Array.
  17248. * No new underlying VertexBuffer object is created.
  17249. * 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.
  17250. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17251. *
  17252. * Possible `kind` values :
  17253. * - BABYLON.VertexBuffer.PositionKind
  17254. * - BABYLON.VertexBuffer.UVKind
  17255. * - BABYLON.VertexBuffer.UV2Kind
  17256. * - BABYLON.VertexBuffer.UV3Kind
  17257. * - BABYLON.VertexBuffer.UV4Kind
  17258. * - BABYLON.VertexBuffer.UV5Kind
  17259. * - BABYLON.VertexBuffer.UV6Kind
  17260. * - BABYLON.VertexBuffer.ColorKind
  17261. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17262. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17263. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17264. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17265. *
  17266. * Returns the Mesh.
  17267. */
  17268. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17269. return this;
  17270. };
  17271. /**
  17272. * Sets the mesh indices.
  17273. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17274. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17275. * This method creates a new index buffer each call.
  17276. * Returns the Mesh.
  17277. */
  17278. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17279. return this;
  17280. };
  17281. /** Returns false by default, used by the class Mesh.
  17282. * Returns a boolean
  17283. */
  17284. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17285. return false;
  17286. };
  17287. /**
  17288. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17289. * Returns a BoundingInfo
  17290. */
  17291. AbstractMesh.prototype.getBoundingInfo = function () {
  17292. if (this._masterMesh) {
  17293. return this._masterMesh.getBoundingInfo();
  17294. }
  17295. if (!this._boundingInfo) {
  17296. // this._boundingInfo is being created here
  17297. this._updateBoundingInfo();
  17298. }
  17299. // cannot be null.
  17300. return this._boundingInfo;
  17301. };
  17302. /**
  17303. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17304. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17305. */
  17306. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17307. if (includeDescendants === void 0) { includeDescendants = true; }
  17308. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17309. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17310. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17311. if (maxDimension === 0) {
  17312. return this;
  17313. }
  17314. var scale = 1 / maxDimension;
  17315. this.scaling.scaleInPlace(scale);
  17316. return this;
  17317. };
  17318. /**
  17319. * Sets a mesh new object BoundingInfo.
  17320. * Returns the AbstractMesh.
  17321. */
  17322. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17323. this._boundingInfo = boundingInfo;
  17324. return this;
  17325. };
  17326. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17327. get: function () {
  17328. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17329. },
  17330. enumerable: true,
  17331. configurable: true
  17332. });
  17333. AbstractMesh.prototype._preActivate = function () {
  17334. };
  17335. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17336. };
  17337. AbstractMesh.prototype._activate = function (renderId) {
  17338. this._renderId = renderId;
  17339. };
  17340. /**
  17341. * Returns the latest update of the World matrix
  17342. * Returns a Matrix.
  17343. */
  17344. AbstractMesh.prototype.getWorldMatrix = function () {
  17345. if (this._masterMesh) {
  17346. return this._masterMesh.getWorldMatrix();
  17347. }
  17348. return _super.prototype.getWorldMatrix.call(this);
  17349. };
  17350. /**
  17351. * Returns the latest update of the World matrix determinant.
  17352. */
  17353. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17354. if (this._masterMesh) {
  17355. return this._masterMesh._getWorldMatrixDeterminant();
  17356. }
  17357. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17358. };
  17359. // ================================== Point of View Movement =================================
  17360. /**
  17361. * Perform relative position change from the point of view of behind the front of the mesh.
  17362. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17363. * Supports definition of mesh facing forward or backward.
  17364. * @param {number} amountRight
  17365. * @param {number} amountUp
  17366. * @param {number} amountForward
  17367. *
  17368. * Returns the AbstractMesh.
  17369. */
  17370. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17371. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17372. return this;
  17373. };
  17374. /**
  17375. * Calculate relative position change from the point of view of behind the front of the mesh.
  17376. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17377. * Supports definition of mesh facing forward or backward.
  17378. * @param {number} amountRight
  17379. * @param {number} amountUp
  17380. * @param {number} amountForward
  17381. *
  17382. * Returns a new Vector3.
  17383. */
  17384. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17385. var rotMatrix = new BABYLON.Matrix();
  17386. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17387. rotQuaternion.toRotationMatrix(rotMatrix);
  17388. var translationDelta = BABYLON.Vector3.Zero();
  17389. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17390. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17391. return translationDelta;
  17392. };
  17393. // ================================== Point of View Rotation =================================
  17394. /**
  17395. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17396. * Supports definition of mesh facing forward or backward.
  17397. * @param {number} flipBack
  17398. * @param {number} twirlClockwise
  17399. * @param {number} tiltRight
  17400. *
  17401. * Returns the AbstractMesh.
  17402. */
  17403. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17404. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17405. return this;
  17406. };
  17407. /**
  17408. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17409. * Supports definition of mesh facing forward or backward.
  17410. * @param {number} flipBack
  17411. * @param {number} twirlClockwise
  17412. * @param {number} tiltRight
  17413. *
  17414. * Returns a new Vector3.
  17415. */
  17416. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17417. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17418. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17419. };
  17420. /**
  17421. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17422. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17423. */
  17424. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17425. if (includeDescendants === void 0) { includeDescendants = true; }
  17426. this.computeWorldMatrix(true);
  17427. var min;
  17428. var max;
  17429. var boundingInfo = this.getBoundingInfo();
  17430. if (!this.subMeshes) {
  17431. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17432. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17433. }
  17434. else {
  17435. min = boundingInfo.boundingBox.minimumWorld;
  17436. max = boundingInfo.boundingBox.maximumWorld;
  17437. }
  17438. if (includeDescendants) {
  17439. var descendants = this.getDescendants(false);
  17440. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17441. var descendant = descendants_1[_i];
  17442. var childMesh = descendant;
  17443. childMesh.computeWorldMatrix(true);
  17444. //make sure we have the needed params to get mix and max
  17445. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17446. continue;
  17447. }
  17448. var childBoundingInfo = childMesh.getBoundingInfo();
  17449. var boundingBox = childBoundingInfo.boundingBox;
  17450. var minBox = boundingBox.minimumWorld;
  17451. var maxBox = boundingBox.maximumWorld;
  17452. BABYLON.Tools.CheckExtends(minBox, min, max);
  17453. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17454. }
  17455. }
  17456. return {
  17457. min: min,
  17458. max: max
  17459. };
  17460. };
  17461. /**
  17462. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17463. * Returns the AbstractMesh.
  17464. */
  17465. AbstractMesh.prototype._updateBoundingInfo = function () {
  17466. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17467. this._boundingInfo.update(this.worldMatrixFromCache);
  17468. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17469. return this;
  17470. };
  17471. /**
  17472. * Update a mesh's children BoundingInfo objects only.
  17473. * Returns the AbstractMesh.
  17474. */
  17475. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17476. if (!this.subMeshes) {
  17477. return this;
  17478. }
  17479. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17480. var subMesh = this.subMeshes[subIndex];
  17481. if (!subMesh.IsGlobal) {
  17482. subMesh.updateBoundingInfo(matrix);
  17483. }
  17484. }
  17485. return this;
  17486. };
  17487. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17488. // Bounding info
  17489. this._updateBoundingInfo();
  17490. };
  17491. /**
  17492. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17493. * A mesh is in the frustum if its bounding box intersects the frustum.
  17494. * Boolean returned.
  17495. */
  17496. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17497. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17498. };
  17499. /**
  17500. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17501. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17502. * Boolean returned.
  17503. */
  17504. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17505. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17506. ;
  17507. };
  17508. /**
  17509. * True if the mesh intersects another mesh or a SolidParticle object.
  17510. * 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)
  17511. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17512. * Returns a boolean.
  17513. */
  17514. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17515. if (precise === void 0) { precise = false; }
  17516. if (!this._boundingInfo || !mesh._boundingInfo) {
  17517. return false;
  17518. }
  17519. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17520. return true;
  17521. }
  17522. if (includeDescendants) {
  17523. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17524. var child = _a[_i];
  17525. if (child.intersectsMesh(mesh, precise, true)) {
  17526. return true;
  17527. }
  17528. }
  17529. }
  17530. return false;
  17531. };
  17532. /**
  17533. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17534. * Returns a boolean.
  17535. */
  17536. AbstractMesh.prototype.intersectsPoint = function (point) {
  17537. if (!this._boundingInfo) {
  17538. return false;
  17539. }
  17540. return this._boundingInfo.intersectsPoint(point);
  17541. };
  17542. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17543. return this.physicsImpostor;
  17544. };
  17545. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17546. if (camera === void 0) { camera = null; }
  17547. if (!camera) {
  17548. camera = this.getScene().activeCamera;
  17549. }
  17550. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17551. };
  17552. /**
  17553. * Returns the distance from the mesh to the active camera.
  17554. * Returns a float.
  17555. */
  17556. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17557. if (camera === void 0) { camera = null; }
  17558. if (!camera) {
  17559. camera = this.getScene().activeCamera;
  17560. }
  17561. return this.absolutePosition.subtract(camera.position).length();
  17562. };
  17563. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17564. if (!this.physicsImpostor) {
  17565. return this;
  17566. }
  17567. this.physicsImpostor.applyImpulse(force, contactPoint);
  17568. return this;
  17569. };
  17570. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17571. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17572. return this;
  17573. }
  17574. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17575. mainPivot: pivot1,
  17576. connectedPivot: pivot2,
  17577. nativeParams: options
  17578. });
  17579. return this;
  17580. };
  17581. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17582. // Collisions
  17583. /**
  17584. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17585. * Default `false`.
  17586. */
  17587. get: function () {
  17588. return this._checkCollisions;
  17589. },
  17590. set: function (collisionEnabled) {
  17591. this._checkCollisions = collisionEnabled;
  17592. if (this.getScene().workerCollisions) {
  17593. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17594. }
  17595. },
  17596. enumerable: true,
  17597. configurable: true
  17598. });
  17599. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17600. /**
  17601. * Gets Collider object used to compute collisions (not physics)
  17602. */
  17603. get: function () {
  17604. return this._collider;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17610. var globalPosition = this.getAbsolutePosition();
  17611. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17612. if (!this._collider) {
  17613. this._collider = new BABYLON.Collider();
  17614. }
  17615. this._collider._radius = this.ellipsoid;
  17616. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17617. return this;
  17618. };
  17619. // Submeshes octree
  17620. /**
  17621. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17622. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17623. * Returns an Octree of submeshes.
  17624. */
  17625. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17626. if (maxCapacity === void 0) { maxCapacity = 64; }
  17627. if (maxDepth === void 0) { maxDepth = 2; }
  17628. if (!this._submeshesOctree) {
  17629. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17630. }
  17631. this.computeWorldMatrix(true);
  17632. var boundingInfo = this.getBoundingInfo();
  17633. // Update octree
  17634. var bbox = boundingInfo.boundingBox;
  17635. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17636. return this._submeshesOctree;
  17637. };
  17638. // Collisions
  17639. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17640. this._generatePointsArray();
  17641. if (!this._positions) {
  17642. return this;
  17643. }
  17644. // Transformation
  17645. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17646. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17647. subMesh._lastColliderWorldVertices = [];
  17648. subMesh._trianglePlanes = [];
  17649. var start = subMesh.verticesStart;
  17650. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17651. for (var i = start; i < end; i++) {
  17652. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17653. }
  17654. }
  17655. // Collide
  17656. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17657. if (collider.collisionFound) {
  17658. collider.collidedMesh = this;
  17659. }
  17660. return this;
  17661. };
  17662. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17663. var subMeshes;
  17664. var len;
  17665. // Octrees
  17666. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17667. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17668. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17669. len = intersections.length;
  17670. subMeshes = intersections.data;
  17671. }
  17672. else {
  17673. subMeshes = this.subMeshes;
  17674. len = subMeshes.length;
  17675. }
  17676. for (var index = 0; index < len; index++) {
  17677. var subMesh = subMeshes[index];
  17678. // Bounding test
  17679. if (len > 1 && !subMesh._checkCollision(collider))
  17680. continue;
  17681. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17682. }
  17683. return this;
  17684. };
  17685. AbstractMesh.prototype._checkCollision = function (collider) {
  17686. // Bounding box test
  17687. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17688. return this;
  17689. // Transformation matrix
  17690. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17691. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17692. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17693. return this;
  17694. };
  17695. // Picking
  17696. AbstractMesh.prototype._generatePointsArray = function () {
  17697. return false;
  17698. };
  17699. /**
  17700. * Checks if the passed Ray intersects with the mesh.
  17701. * Returns an object PickingInfo.
  17702. */
  17703. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17704. var pickingInfo = new BABYLON.PickingInfo();
  17705. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17706. return pickingInfo;
  17707. }
  17708. if (!this._generatePointsArray()) {
  17709. return pickingInfo;
  17710. }
  17711. var intersectInfo = null;
  17712. // Octrees
  17713. var subMeshes;
  17714. var len;
  17715. if (this._submeshesOctree && this.useOctreeForPicking) {
  17716. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17717. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17718. len = intersections.length;
  17719. subMeshes = intersections.data;
  17720. }
  17721. else {
  17722. subMeshes = this.subMeshes;
  17723. len = subMeshes.length;
  17724. }
  17725. for (var index = 0; index < len; index++) {
  17726. var subMesh = subMeshes[index];
  17727. // Bounding test
  17728. if (len > 1 && !subMesh.canIntersects(ray))
  17729. continue;
  17730. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17731. if (currentIntersectInfo) {
  17732. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17733. intersectInfo = currentIntersectInfo;
  17734. intersectInfo.subMeshId = index;
  17735. if (fastCheck) {
  17736. break;
  17737. }
  17738. }
  17739. }
  17740. }
  17741. if (intersectInfo) {
  17742. // Get picked point
  17743. var world = this.getWorldMatrix();
  17744. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17745. var direction = ray.direction.clone();
  17746. direction = direction.scale(intersectInfo.distance);
  17747. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17748. var pickedPoint = worldOrigin.add(worldDirection);
  17749. // Return result
  17750. pickingInfo.hit = true;
  17751. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17752. pickingInfo.pickedPoint = pickedPoint;
  17753. pickingInfo.pickedMesh = this;
  17754. pickingInfo.bu = intersectInfo.bu || 0;
  17755. pickingInfo.bv = intersectInfo.bv || 0;
  17756. pickingInfo.faceId = intersectInfo.faceId;
  17757. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17758. return pickingInfo;
  17759. }
  17760. return pickingInfo;
  17761. };
  17762. /**
  17763. * Clones the mesh, used by the class Mesh.
  17764. * Just returns `null` for an AbstractMesh.
  17765. */
  17766. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17767. return null;
  17768. };
  17769. /**
  17770. * Disposes all the mesh submeshes.
  17771. * Returns the AbstractMesh.
  17772. */
  17773. AbstractMesh.prototype.releaseSubMeshes = function () {
  17774. if (this.subMeshes) {
  17775. while (this.subMeshes.length) {
  17776. this.subMeshes[0].dispose();
  17777. }
  17778. }
  17779. else {
  17780. this.subMeshes = new Array();
  17781. }
  17782. return this;
  17783. };
  17784. /**
  17785. * Disposes the AbstractMesh.
  17786. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17787. * Returns nothing.
  17788. */
  17789. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17790. var _this = this;
  17791. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17792. var index;
  17793. // Action manager
  17794. if (this.actionManager !== undefined && this.actionManager !== null) {
  17795. this.actionManager.dispose();
  17796. this.actionManager = null;
  17797. }
  17798. // Skeleton
  17799. this.skeleton = null;
  17800. // Physics
  17801. if (this.physicsImpostor) {
  17802. this.physicsImpostor.dispose();
  17803. }
  17804. // Intersections in progress
  17805. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17806. var other = this._intersectionsInProgress[index];
  17807. var pos = other._intersectionsInProgress.indexOf(this);
  17808. other._intersectionsInProgress.splice(pos, 1);
  17809. }
  17810. this._intersectionsInProgress = [];
  17811. // Lights
  17812. var lights = this.getScene().lights;
  17813. lights.forEach(function (light) {
  17814. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17815. if (meshIndex !== -1) {
  17816. light.includedOnlyMeshes.splice(meshIndex, 1);
  17817. }
  17818. meshIndex = light.excludedMeshes.indexOf(_this);
  17819. if (meshIndex !== -1) {
  17820. light.excludedMeshes.splice(meshIndex, 1);
  17821. }
  17822. // Shadow generators
  17823. var generator = light.getShadowGenerator();
  17824. if (generator) {
  17825. var shadowMap = generator.getShadowMap();
  17826. if (shadowMap && shadowMap.renderList) {
  17827. meshIndex = shadowMap.renderList.indexOf(_this);
  17828. if (meshIndex !== -1) {
  17829. shadowMap.renderList.splice(meshIndex, 1);
  17830. }
  17831. }
  17832. }
  17833. });
  17834. // Edges
  17835. if (this._edgesRenderer) {
  17836. this._edgesRenderer.dispose();
  17837. this._edgesRenderer = null;
  17838. }
  17839. // SubMeshes
  17840. if (this.getClassName() !== "InstancedMesh") {
  17841. this.releaseSubMeshes();
  17842. }
  17843. // Octree
  17844. var sceneOctree = this.getScene().selectionOctree;
  17845. if (sceneOctree !== undefined && sceneOctree !== null) {
  17846. var index = sceneOctree.dynamicContent.indexOf(this);
  17847. if (index !== -1) {
  17848. sceneOctree.dynamicContent.splice(index, 1);
  17849. }
  17850. }
  17851. // Query
  17852. var engine = this.getScene().getEngine();
  17853. if (this._occlusionQuery) {
  17854. this._isOcclusionQueryInProgress = false;
  17855. engine.deleteQuery(this._occlusionQuery);
  17856. this._occlusionQuery = null;
  17857. }
  17858. // Engine
  17859. engine.wipeCaches();
  17860. // Remove from scene
  17861. this.getScene().removeMesh(this);
  17862. if (disposeMaterialAndTextures) {
  17863. if (this.material) {
  17864. this.material.dispose(false, true);
  17865. }
  17866. }
  17867. if (!doNotRecurse) {
  17868. // Particles
  17869. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17870. if (this.getScene().particleSystems[index].emitter === this) {
  17871. this.getScene().particleSystems[index].dispose();
  17872. index--;
  17873. }
  17874. }
  17875. }
  17876. // facet data
  17877. if (this._facetDataEnabled) {
  17878. this.disableFacetData();
  17879. }
  17880. this.onAfterWorldMatrixUpdateObservable.clear();
  17881. this.onCollideObservable.clear();
  17882. this.onCollisionPositionChangeObservable.clear();
  17883. this._isDisposed = true;
  17884. _super.prototype.dispose.call(this, doNotRecurse);
  17885. };
  17886. /**
  17887. * Adds the passed mesh as a child to the current mesh.
  17888. * Returns the AbstractMesh.
  17889. */
  17890. AbstractMesh.prototype.addChild = function (mesh) {
  17891. mesh.setParent(this);
  17892. return this;
  17893. };
  17894. /**
  17895. * Removes the passed mesh from the current mesh children list.
  17896. * Returns the AbstractMesh.
  17897. */
  17898. AbstractMesh.prototype.removeChild = function (mesh) {
  17899. mesh.setParent(null);
  17900. return this;
  17901. };
  17902. // Facet data
  17903. /**
  17904. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17905. * Returns the AbstractMesh.
  17906. */
  17907. AbstractMesh.prototype._initFacetData = function () {
  17908. if (!this._facetNormals) {
  17909. this._facetNormals = new Array();
  17910. }
  17911. if (!this._facetPositions) {
  17912. this._facetPositions = new Array();
  17913. }
  17914. if (!this._facetPartitioning) {
  17915. this._facetPartitioning = new Array();
  17916. }
  17917. this._facetNb = (this.getIndices().length / 3) | 0;
  17918. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17919. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17920. for (var f = 0; f < this._facetNb; f++) {
  17921. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17922. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17923. }
  17924. this._facetDataEnabled = true;
  17925. return this;
  17926. };
  17927. /**
  17928. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17929. * This method can be called within the render loop.
  17930. * 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.
  17931. * Returns the AbstractMesh.
  17932. */
  17933. AbstractMesh.prototype.updateFacetData = function () {
  17934. if (!this._facetDataEnabled) {
  17935. this._initFacetData();
  17936. }
  17937. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17938. var indices = this.getIndices();
  17939. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17940. var bInfo = this.getBoundingInfo();
  17941. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17942. // init arrays, matrix and sort function on first call
  17943. this._facetDepthSortEnabled = true;
  17944. if (indices instanceof Uint16Array) {
  17945. this._depthSortedIndices = new Uint16Array(indices);
  17946. }
  17947. else if (indices instanceof Uint32Array) {
  17948. this._depthSortedIndices = new Uint32Array(indices);
  17949. }
  17950. else {
  17951. var needs32bits = false;
  17952. for (var i = 0; i < indices.length; i++) {
  17953. if (indices[i] > 65535) {
  17954. needs32bits = true;
  17955. break;
  17956. }
  17957. }
  17958. if (needs32bits) {
  17959. this._depthSortedIndices = new Uint32Array(indices);
  17960. }
  17961. else {
  17962. this._depthSortedIndices = new Uint16Array(indices);
  17963. }
  17964. }
  17965. this._facetDepthSortFunction = function (f1, f2) {
  17966. return (f2.sqDistance - f1.sqDistance);
  17967. };
  17968. if (!this._facetDepthSortFrom) {
  17969. var camera = this.getScene().activeCamera;
  17970. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17971. }
  17972. this._depthSortedFacets = [];
  17973. for (var f = 0; f < this._facetNb; f++) {
  17974. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17975. this._depthSortedFacets.push(depthSortedFacet);
  17976. }
  17977. this._invertedMatrix = BABYLON.Matrix.Identity();
  17978. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17979. }
  17980. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17981. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17982. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17983. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17984. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17985. this._subDiv.max = this._partitioningSubdivisions;
  17986. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17987. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17988. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17989. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17990. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17991. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17992. // set the parameters for ComputeNormals()
  17993. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17994. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17995. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17996. this._facetParameters.bInfo = bInfo;
  17997. this._facetParameters.bbSize = this._bbSize;
  17998. this._facetParameters.subDiv = this._subDiv;
  17999. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18000. this._facetParameters.depthSort = this._facetDepthSort;
  18001. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18002. this.computeWorldMatrix(true);
  18003. this._worldMatrix.invertToRef(this._invertedMatrix);
  18004. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18005. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18006. }
  18007. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18008. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18009. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18010. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18011. var l = (this._depthSortedIndices.length / 3) | 0;
  18012. for (var f = 0; f < l; f++) {
  18013. var sind = this._depthSortedFacets[f].ind;
  18014. this._depthSortedIndices[f * 3] = indices[sind];
  18015. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18016. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18017. }
  18018. this.updateIndices(this._depthSortedIndices);
  18019. }
  18020. return this;
  18021. };
  18022. /**
  18023. * Returns the facetLocalNormals array.
  18024. * The normals are expressed in the mesh local space.
  18025. */
  18026. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18027. if (!this._facetNormals) {
  18028. this.updateFacetData();
  18029. }
  18030. return this._facetNormals;
  18031. };
  18032. /**
  18033. * Returns the facetLocalPositions array.
  18034. * The facet positions are expressed in the mesh local space.
  18035. */
  18036. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18037. if (!this._facetPositions) {
  18038. this.updateFacetData();
  18039. }
  18040. return this._facetPositions;
  18041. };
  18042. /**
  18043. * Returns the facetLocalPartioning array.
  18044. */
  18045. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18046. if (!this._facetPartitioning) {
  18047. this.updateFacetData();
  18048. }
  18049. return this._facetPartitioning;
  18050. };
  18051. /**
  18052. * Returns the i-th facet position in the world system.
  18053. * This method allocates a new Vector3 per call.
  18054. */
  18055. AbstractMesh.prototype.getFacetPosition = function (i) {
  18056. var pos = BABYLON.Vector3.Zero();
  18057. this.getFacetPositionToRef(i, pos);
  18058. return pos;
  18059. };
  18060. /**
  18061. * Sets the reference Vector3 with the i-th facet position in the world system.
  18062. * Returns the AbstractMesh.
  18063. */
  18064. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18065. var localPos = (this.getFacetLocalPositions())[i];
  18066. var world = this.getWorldMatrix();
  18067. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18068. return this;
  18069. };
  18070. /**
  18071. * Returns the i-th facet normal in the world system.
  18072. * This method allocates a new Vector3 per call.
  18073. */
  18074. AbstractMesh.prototype.getFacetNormal = function (i) {
  18075. var norm = BABYLON.Vector3.Zero();
  18076. this.getFacetNormalToRef(i, norm);
  18077. return norm;
  18078. };
  18079. /**
  18080. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18081. * Returns the AbstractMesh.
  18082. */
  18083. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18084. var localNorm = (this.getFacetLocalNormals())[i];
  18085. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18086. return this;
  18087. };
  18088. /**
  18089. * 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).
  18090. */
  18091. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18092. var bInfo = this.getBoundingInfo();
  18093. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18094. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18095. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18096. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18097. return null;
  18098. }
  18099. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18100. };
  18101. /**
  18102. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18103. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18104. * 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.
  18105. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18106. * 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.
  18107. */
  18108. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18109. if (checkFace === void 0) { checkFace = false; }
  18110. if (facing === void 0) { facing = true; }
  18111. var world = this.getWorldMatrix();
  18112. var invMat = BABYLON.Tmp.Matrix[5];
  18113. world.invertToRef(invMat);
  18114. var invVect = BABYLON.Tmp.Vector3[8];
  18115. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18116. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18117. if (projected) {
  18118. // tranform the local computed projected vector to world coordinates
  18119. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18120. }
  18121. return closest;
  18122. };
  18123. /**
  18124. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18125. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18126. * 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.
  18127. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18128. * 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.
  18129. */
  18130. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18131. if (checkFace === void 0) { checkFace = false; }
  18132. if (facing === void 0) { facing = true; }
  18133. var closest = null;
  18134. var tmpx = 0.0;
  18135. var tmpy = 0.0;
  18136. var tmpz = 0.0;
  18137. var d = 0.0; // tmp dot facet normal * facet position
  18138. var t0 = 0.0;
  18139. var projx = 0.0;
  18140. var projy = 0.0;
  18141. var projz = 0.0;
  18142. // Get all the facets in the same partitioning block than (x, y, z)
  18143. var facetPositions = this.getFacetLocalPositions();
  18144. var facetNormals = this.getFacetLocalNormals();
  18145. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18146. if (!facetsInBlock) {
  18147. return null;
  18148. }
  18149. // Get the closest facet to (x, y, z)
  18150. var shortest = Number.MAX_VALUE; // init distance vars
  18151. var tmpDistance = shortest;
  18152. var fib; // current facet in the block
  18153. var norm; // current facet normal
  18154. var p0; // current facet barycenter position
  18155. // loop on all the facets in the current partitioning block
  18156. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18157. fib = facetsInBlock[idx];
  18158. norm = facetNormals[fib];
  18159. p0 = facetPositions[fib];
  18160. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18161. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18162. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18163. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18164. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18165. projx = x + norm.x * t0;
  18166. projy = y + norm.y * t0;
  18167. projz = z + norm.z * t0;
  18168. tmpx = projx - x;
  18169. tmpy = projy - y;
  18170. tmpz = projz - z;
  18171. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18172. if (tmpDistance < shortest) {
  18173. shortest = tmpDistance;
  18174. closest = fib;
  18175. if (projected) {
  18176. projected.x = projx;
  18177. projected.y = projy;
  18178. projected.z = projz;
  18179. }
  18180. }
  18181. }
  18182. }
  18183. return closest;
  18184. };
  18185. /**
  18186. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18187. */
  18188. AbstractMesh.prototype.getFacetDataParameters = function () {
  18189. return this._facetParameters;
  18190. };
  18191. /**
  18192. * Disables the feature FacetData and frees the related memory.
  18193. * Returns the AbstractMesh.
  18194. */
  18195. AbstractMesh.prototype.disableFacetData = function () {
  18196. if (this._facetDataEnabled) {
  18197. this._facetDataEnabled = false;
  18198. this._facetPositions = new Array();
  18199. this._facetNormals = new Array();
  18200. this._facetPartitioning = new Array();
  18201. this._facetParameters = null;
  18202. this._depthSortedIndices = new Uint32Array(0);
  18203. }
  18204. return this;
  18205. };
  18206. /**
  18207. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18208. * Returns the mesh.
  18209. */
  18210. AbstractMesh.prototype.updateIndices = function (indices) {
  18211. return this;
  18212. };
  18213. /**
  18214. * The mesh Geometry. Actually used by the Mesh object.
  18215. * Returns a blank geometry object.
  18216. */
  18217. /**
  18218. * Creates new normals data for the mesh.
  18219. * @param updatable.
  18220. */
  18221. AbstractMesh.prototype.createNormals = function (updatable) {
  18222. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18223. var indices = this.getIndices();
  18224. var normals;
  18225. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18226. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18227. }
  18228. else {
  18229. normals = [];
  18230. }
  18231. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18232. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18233. };
  18234. /**
  18235. * Align the mesh with a normal.
  18236. * Returns the mesh.
  18237. */
  18238. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18239. if (!upDirection) {
  18240. upDirection = BABYLON.Axis.Y;
  18241. }
  18242. var axisX = BABYLON.Tmp.Vector3[0];
  18243. var axisZ = BABYLON.Tmp.Vector3[1];
  18244. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18245. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18246. if (this.rotationQuaternion) {
  18247. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18248. }
  18249. else {
  18250. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18251. }
  18252. return this;
  18253. };
  18254. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18255. var engine = this.getEngine();
  18256. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18257. this._isOccluded = false;
  18258. return;
  18259. }
  18260. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18261. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18262. if (isOcclusionQueryAvailable) {
  18263. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18264. this._isOcclusionQueryInProgress = false;
  18265. this._occlusionInternalRetryCounter = 0;
  18266. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18267. }
  18268. else {
  18269. this._occlusionInternalRetryCounter++;
  18270. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18271. this._isOcclusionQueryInProgress = false;
  18272. this._occlusionInternalRetryCounter = 0;
  18273. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18274. // if strict continue the last state of the object.
  18275. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18276. }
  18277. else {
  18278. return;
  18279. }
  18280. }
  18281. }
  18282. var scene = this.getScene();
  18283. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18284. if (!this._occlusionQuery) {
  18285. this._occlusionQuery = engine.createQuery();
  18286. }
  18287. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18288. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18289. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18290. this._isOcclusionQueryInProgress = true;
  18291. };
  18292. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18293. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18294. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18295. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18296. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18297. return AbstractMesh;
  18298. }(BABYLON.TransformNode));
  18299. BABYLON.AbstractMesh = AbstractMesh;
  18300. })(BABYLON || (BABYLON = {}));
  18301. //# sourceMappingURL=babylon.abstractMesh.js.map
  18302. var BABYLON;
  18303. (function (BABYLON) {
  18304. /**
  18305. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18306. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18307. * 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.
  18308. */
  18309. var Light = /** @class */ (function (_super) {
  18310. __extends(Light, _super);
  18311. /**
  18312. * Creates a Light object in the scene.
  18313. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18314. * @param name The firendly name of the light
  18315. * @param scene The scene the light belongs too
  18316. */
  18317. function Light(name, scene) {
  18318. var _this = _super.call(this, name, scene) || this;
  18319. /**
  18320. * Diffuse gives the basic color to an object.
  18321. */
  18322. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18323. /**
  18324. * Specular produces a highlight color on an object.
  18325. * Note: This is note affecting PBR materials.
  18326. */
  18327. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18328. /**
  18329. * Strength of the light.
  18330. * Note: By default it is define in the framework own unit.
  18331. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18332. */
  18333. _this.intensity = 1.0;
  18334. /**
  18335. * Defines how far from the source the light is impacting in scene units.
  18336. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18337. */
  18338. _this.range = Number.MAX_VALUE;
  18339. /**
  18340. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18341. * of light.
  18342. */
  18343. _this._photometricScale = 1.0;
  18344. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18345. _this._radius = 0.00001;
  18346. /**
  18347. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18348. * exceeding the number allowed of the materials.
  18349. */
  18350. _this.renderPriority = 0;
  18351. /**
  18352. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18353. * the current shadow generator.
  18354. */
  18355. _this.shadowEnabled = true;
  18356. _this._excludeWithLayerMask = 0;
  18357. _this._includeOnlyWithLayerMask = 0;
  18358. _this._lightmapMode = 0;
  18359. /**
  18360. * @ignore Internal use only.
  18361. */
  18362. _this._excludedMeshesIds = new Array();
  18363. /**
  18364. * @ignore Internal use only.
  18365. */
  18366. _this._includedOnlyMeshesIds = new Array();
  18367. _this.getScene().addLight(_this);
  18368. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18369. _this._buildUniformLayout();
  18370. _this.includedOnlyMeshes = new Array();
  18371. _this.excludedMeshes = new Array();
  18372. _this._resyncMeshes();
  18373. return _this;
  18374. }
  18375. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18376. /**
  18377. * If every light affecting the material is in this lightmapMode,
  18378. * material.lightmapTexture adds or multiplies
  18379. * (depends on material.useLightmapAsShadowmap)
  18380. * after every other light calculations.
  18381. */
  18382. get: function () {
  18383. return Light._LIGHTMAP_DEFAULT;
  18384. },
  18385. enumerable: true,
  18386. configurable: true
  18387. });
  18388. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18389. /**
  18390. * material.lightmapTexture as only diffuse lighting from this light
  18391. * adds only specular lighting from this light
  18392. * adds dynamic shadows
  18393. */
  18394. get: function () {
  18395. return Light._LIGHTMAP_SPECULAR;
  18396. },
  18397. enumerable: true,
  18398. configurable: true
  18399. });
  18400. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18401. /**
  18402. * material.lightmapTexture as only lighting
  18403. * no light calculation from this light
  18404. * only adds dynamic shadows from this light
  18405. */
  18406. get: function () {
  18407. return Light._LIGHTMAP_SHADOWSONLY;
  18408. },
  18409. enumerable: true,
  18410. configurable: true
  18411. });
  18412. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18413. /**
  18414. * Each light type uses the default quantity according to its type:
  18415. * point/spot lights use luminous intensity
  18416. * directional lights use illuminance
  18417. */
  18418. get: function () {
  18419. return Light._INTENSITYMODE_AUTOMATIC;
  18420. },
  18421. enumerable: true,
  18422. configurable: true
  18423. });
  18424. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18425. /**
  18426. * lumen (lm)
  18427. */
  18428. get: function () {
  18429. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18430. },
  18431. enumerable: true,
  18432. configurable: true
  18433. });
  18434. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18435. /**
  18436. * candela (lm/sr)
  18437. */
  18438. get: function () {
  18439. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18440. },
  18441. enumerable: true,
  18442. configurable: true
  18443. });
  18444. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18445. /**
  18446. * lux (lm/m^2)
  18447. */
  18448. get: function () {
  18449. return Light._INTENSITYMODE_ILLUMINANCE;
  18450. },
  18451. enumerable: true,
  18452. configurable: true
  18453. });
  18454. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18455. /**
  18456. * nit (cd/m^2)
  18457. */
  18458. get: function () {
  18459. return Light._INTENSITYMODE_LUMINANCE;
  18460. },
  18461. enumerable: true,
  18462. configurable: true
  18463. });
  18464. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18465. /**
  18466. * Light type const id of the point light.
  18467. */
  18468. get: function () {
  18469. return Light._LIGHTTYPEID_POINTLIGHT;
  18470. },
  18471. enumerable: true,
  18472. configurable: true
  18473. });
  18474. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18475. /**
  18476. * Light type const id of the directional light.
  18477. */
  18478. get: function () {
  18479. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18480. },
  18481. enumerable: true,
  18482. configurable: true
  18483. });
  18484. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18485. /**
  18486. * Light type const id of the spot light.
  18487. */
  18488. get: function () {
  18489. return Light._LIGHTTYPEID_SPOTLIGHT;
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18495. /**
  18496. * Light type const id of the hemispheric light.
  18497. */
  18498. get: function () {
  18499. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18500. },
  18501. enumerable: true,
  18502. configurable: true
  18503. });
  18504. Object.defineProperty(Light.prototype, "intensityMode", {
  18505. /**
  18506. * Gets the photometric scale used to interpret the intensity.
  18507. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18508. */
  18509. get: function () {
  18510. return this._intensityMode;
  18511. },
  18512. /**
  18513. * Sets the photometric scale used to interpret the intensity.
  18514. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18515. */
  18516. set: function (value) {
  18517. this._intensityMode = value;
  18518. this._computePhotometricScale();
  18519. },
  18520. enumerable: true,
  18521. configurable: true
  18522. });
  18523. ;
  18524. ;
  18525. Object.defineProperty(Light.prototype, "radius", {
  18526. /**
  18527. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18528. */
  18529. get: function () {
  18530. return this._radius;
  18531. },
  18532. /**
  18533. * sets the light radius used by PBR Materials to simulate soft area lights.
  18534. */
  18535. set: function (value) {
  18536. this._radius = value;
  18537. this._computePhotometricScale();
  18538. },
  18539. enumerable: true,
  18540. configurable: true
  18541. });
  18542. ;
  18543. ;
  18544. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18545. /**
  18546. * Gets the only meshes impacted by this light.
  18547. */
  18548. get: function () {
  18549. return this._includedOnlyMeshes;
  18550. },
  18551. /**
  18552. * Sets the only meshes impacted by this light.
  18553. */
  18554. set: function (value) {
  18555. this._includedOnlyMeshes = value;
  18556. this._hookArrayForIncludedOnly(value);
  18557. },
  18558. enumerable: true,
  18559. configurable: true
  18560. });
  18561. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18562. /**
  18563. * Gets the meshes not impacted by this light.
  18564. */
  18565. get: function () {
  18566. return this._excludedMeshes;
  18567. },
  18568. /**
  18569. * Sets the meshes not impacted by this light.
  18570. */
  18571. set: function (value) {
  18572. this._excludedMeshes = value;
  18573. this._hookArrayForExcluded(value);
  18574. },
  18575. enumerable: true,
  18576. configurable: true
  18577. });
  18578. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18579. /**
  18580. * Gets the layer id use to find what meshes are not impacted by the light.
  18581. * Inactive if 0
  18582. */
  18583. get: function () {
  18584. return this._excludeWithLayerMask;
  18585. },
  18586. /**
  18587. * Sets the layer id use to find what meshes are not impacted by the light.
  18588. * Inactive if 0
  18589. */
  18590. set: function (value) {
  18591. this._excludeWithLayerMask = value;
  18592. this._resyncMeshes();
  18593. },
  18594. enumerable: true,
  18595. configurable: true
  18596. });
  18597. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18598. /**
  18599. * Gets the layer id use to find what meshes are impacted by the light.
  18600. * Inactive if 0
  18601. */
  18602. get: function () {
  18603. return this._includeOnlyWithLayerMask;
  18604. },
  18605. /**
  18606. * Sets the layer id use to find what meshes are impacted by the light.
  18607. * Inactive if 0
  18608. */
  18609. set: function (value) {
  18610. this._includeOnlyWithLayerMask = value;
  18611. this._resyncMeshes();
  18612. },
  18613. enumerable: true,
  18614. configurable: true
  18615. });
  18616. Object.defineProperty(Light.prototype, "lightmapMode", {
  18617. /**
  18618. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18619. */
  18620. get: function () {
  18621. return this._lightmapMode;
  18622. },
  18623. /**
  18624. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18625. */
  18626. set: function (value) {
  18627. if (this._lightmapMode === value) {
  18628. return;
  18629. }
  18630. this._lightmapMode = value;
  18631. this._markMeshesAsLightDirty();
  18632. },
  18633. enumerable: true,
  18634. configurable: true
  18635. });
  18636. /**
  18637. * Returns the string "Light".
  18638. * @returns the class name
  18639. */
  18640. Light.prototype.getClassName = function () {
  18641. return "Light";
  18642. };
  18643. /**
  18644. * Converts the light information to a readable string for debug purpose.
  18645. * @param fullDetails Supports for multiple levels of logging within scene loading
  18646. * @returns the human readable light info
  18647. */
  18648. Light.prototype.toString = function (fullDetails) {
  18649. var ret = "Name: " + this.name;
  18650. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18651. if (this.animations) {
  18652. for (var i = 0; i < this.animations.length; i++) {
  18653. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18654. }
  18655. }
  18656. if (fullDetails) {
  18657. }
  18658. return ret;
  18659. };
  18660. /**
  18661. * Set the enabled state of this node.
  18662. * @param value - the new enabled state
  18663. * @see isEnabled
  18664. */
  18665. Light.prototype.setEnabled = function (value) {
  18666. _super.prototype.setEnabled.call(this, value);
  18667. this._resyncMeshes();
  18668. };
  18669. /**
  18670. * Returns the Light associated shadow generator if any.
  18671. * @return the associated shadow generator.
  18672. */
  18673. Light.prototype.getShadowGenerator = function () {
  18674. return this._shadowGenerator;
  18675. };
  18676. /**
  18677. * Returns a Vector3, the absolute light position in the World.
  18678. * @returns the world space position of the light
  18679. */
  18680. Light.prototype.getAbsolutePosition = function () {
  18681. return BABYLON.Vector3.Zero();
  18682. };
  18683. /**
  18684. * Specifies if the light will affect the passed mesh.
  18685. * @param mesh The mesh to test against the light
  18686. * @return true the mesh is affected otherwise, false.
  18687. */
  18688. Light.prototype.canAffectMesh = function (mesh) {
  18689. if (!mesh) {
  18690. return true;
  18691. }
  18692. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18693. return false;
  18694. }
  18695. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18696. return false;
  18697. }
  18698. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18699. return false;
  18700. }
  18701. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18702. return false;
  18703. }
  18704. return true;
  18705. };
  18706. /**
  18707. * Computes and Returns the light World matrix.
  18708. * @returns the world matrix
  18709. */
  18710. Light.prototype.getWorldMatrix = function () {
  18711. this._currentRenderId = this.getScene().getRenderId();
  18712. var worldMatrix = this._getWorldMatrix();
  18713. if (this.parent && this.parent.getWorldMatrix) {
  18714. if (!this._parentedWorldMatrix) {
  18715. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18716. }
  18717. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18718. this._markSyncedWithParent();
  18719. return this._parentedWorldMatrix;
  18720. }
  18721. return worldMatrix;
  18722. };
  18723. /**
  18724. * Sort function to order lights for rendering.
  18725. * @param a First Light object to compare to second.
  18726. * @param b Second Light object to compare first.
  18727. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18728. */
  18729. Light.CompareLightsPriority = function (a, b) {
  18730. //shadow-casting lights have priority over non-shadow-casting lights
  18731. //the renderPrioirty is a secondary sort criterion
  18732. if (a.shadowEnabled !== b.shadowEnabled) {
  18733. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18734. }
  18735. return b.renderPriority - a.renderPriority;
  18736. };
  18737. /**
  18738. * Disposes the light.
  18739. */
  18740. Light.prototype.dispose = function () {
  18741. if (this._shadowGenerator) {
  18742. this._shadowGenerator.dispose();
  18743. this._shadowGenerator = null;
  18744. }
  18745. // Animations
  18746. this.getScene().stopAnimation(this);
  18747. // Remove from meshes
  18748. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18749. var mesh = _a[_i];
  18750. mesh._removeLightSource(this);
  18751. }
  18752. this._uniformBuffer.dispose();
  18753. // Remove from scene
  18754. this.getScene().removeLight(this);
  18755. _super.prototype.dispose.call(this);
  18756. };
  18757. /**
  18758. * Returns the light type ID (integer).
  18759. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18760. */
  18761. Light.prototype.getTypeID = function () {
  18762. return 0;
  18763. };
  18764. /**
  18765. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18766. * @returns the scaled intensity in intensity mode unit
  18767. */
  18768. Light.prototype.getScaledIntensity = function () {
  18769. return this._photometricScale * this.intensity;
  18770. };
  18771. /**
  18772. * Returns a new Light object, named "name", from the current one.
  18773. * @param name The name of the cloned light
  18774. * @returns the new created light
  18775. */
  18776. Light.prototype.clone = function (name) {
  18777. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18778. if (!constructor) {
  18779. return null;
  18780. }
  18781. return BABYLON.SerializationHelper.Clone(constructor, this);
  18782. };
  18783. /**
  18784. * Serializes the current light into a Serialization object.
  18785. * @returns the serialized object.
  18786. */
  18787. Light.prototype.serialize = function () {
  18788. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18789. // Type
  18790. serializationObject.type = this.getTypeID();
  18791. // Parent
  18792. if (this.parent) {
  18793. serializationObject.parentId = this.parent.id;
  18794. }
  18795. // Inclusion / exclusions
  18796. if (this.excludedMeshes.length > 0) {
  18797. serializationObject.excludedMeshesIds = [];
  18798. this.excludedMeshes.forEach(function (mesh) {
  18799. serializationObject.excludedMeshesIds.push(mesh.id);
  18800. });
  18801. }
  18802. if (this.includedOnlyMeshes.length > 0) {
  18803. serializationObject.includedOnlyMeshesIds = [];
  18804. this.includedOnlyMeshes.forEach(function (mesh) {
  18805. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18806. });
  18807. }
  18808. // Animations
  18809. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18810. serializationObject.ranges = this.serializeAnimationRanges();
  18811. return serializationObject;
  18812. };
  18813. /**
  18814. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18815. * This new light is named "name" and added to the passed scene.
  18816. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18817. * @param name The friendly name of the light
  18818. * @param scene The scene the new light will belong to
  18819. * @returns the constructor function
  18820. */
  18821. Light.GetConstructorFromName = function (type, name, scene) {
  18822. switch (type) {
  18823. case 0:
  18824. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18825. case 1:
  18826. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18827. case 2:
  18828. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18829. case 3:
  18830. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18831. }
  18832. return null;
  18833. };
  18834. /**
  18835. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18836. * @param parsedLight The JSON representation of the light
  18837. * @param scene The scene to create the parsed light in
  18838. * @returns the created light after parsing
  18839. */
  18840. Light.Parse = function (parsedLight, scene) {
  18841. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18842. if (!constructor) {
  18843. return null;
  18844. }
  18845. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18846. // Inclusion / exclusions
  18847. if (parsedLight.excludedMeshesIds) {
  18848. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18849. }
  18850. if (parsedLight.includedOnlyMeshesIds) {
  18851. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18852. }
  18853. // Parent
  18854. if (parsedLight.parentId) {
  18855. light._waitingParentId = parsedLight.parentId;
  18856. }
  18857. // Animations
  18858. if (parsedLight.animations) {
  18859. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18860. var parsedAnimation = parsedLight.animations[animationIndex];
  18861. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18862. }
  18863. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18864. }
  18865. if (parsedLight.autoAnimate) {
  18866. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18867. }
  18868. return light;
  18869. };
  18870. Light.prototype._hookArrayForExcluded = function (array) {
  18871. var _this = this;
  18872. var oldPush = array.push;
  18873. array.push = function () {
  18874. var items = [];
  18875. for (var _i = 0; _i < arguments.length; _i++) {
  18876. items[_i] = arguments[_i];
  18877. }
  18878. var result = oldPush.apply(array, items);
  18879. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18880. var item = items_1[_a];
  18881. item._resyncLighSource(_this);
  18882. }
  18883. return result;
  18884. };
  18885. var oldSplice = array.splice;
  18886. array.splice = function (index, deleteCount) {
  18887. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18888. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18889. var item = deleted_1[_i];
  18890. item._resyncLighSource(_this);
  18891. }
  18892. return deleted;
  18893. };
  18894. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18895. var item = array_1[_i];
  18896. item._resyncLighSource(this);
  18897. }
  18898. };
  18899. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18900. var _this = this;
  18901. var oldPush = array.push;
  18902. array.push = function () {
  18903. var items = [];
  18904. for (var _i = 0; _i < arguments.length; _i++) {
  18905. items[_i] = arguments[_i];
  18906. }
  18907. var result = oldPush.apply(array, items);
  18908. _this._resyncMeshes();
  18909. return result;
  18910. };
  18911. var oldSplice = array.splice;
  18912. array.splice = function (index, deleteCount) {
  18913. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18914. _this._resyncMeshes();
  18915. return deleted;
  18916. };
  18917. this._resyncMeshes();
  18918. };
  18919. Light.prototype._resyncMeshes = function () {
  18920. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18921. var mesh = _a[_i];
  18922. mesh._resyncLighSource(this);
  18923. }
  18924. };
  18925. /**
  18926. * Forces the meshes to update their light related information in their rendering used effects
  18927. * @ignore Internal Use Only
  18928. */
  18929. Light.prototype._markMeshesAsLightDirty = function () {
  18930. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18931. var mesh = _a[_i];
  18932. if (mesh._lightSources.indexOf(this) !== -1) {
  18933. mesh._markSubMeshesAsLightDirty();
  18934. }
  18935. }
  18936. };
  18937. /**
  18938. * Recomputes the cached photometric scale if needed.
  18939. */
  18940. Light.prototype._computePhotometricScale = function () {
  18941. this._photometricScale = this._getPhotometricScale();
  18942. this.getScene().resetCachedMaterial();
  18943. };
  18944. /**
  18945. * Returns the Photometric Scale according to the light type and intensity mode.
  18946. */
  18947. Light.prototype._getPhotometricScale = function () {
  18948. var photometricScale = 0.0;
  18949. var lightTypeID = this.getTypeID();
  18950. //get photometric mode
  18951. var photometricMode = this.intensityMode;
  18952. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18953. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18954. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18955. }
  18956. else {
  18957. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18958. }
  18959. }
  18960. //compute photometric scale
  18961. switch (lightTypeID) {
  18962. case Light.LIGHTTYPEID_POINTLIGHT:
  18963. case Light.LIGHTTYPEID_SPOTLIGHT:
  18964. switch (photometricMode) {
  18965. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18966. photometricScale = 1.0 / (4.0 * Math.PI);
  18967. break;
  18968. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18969. photometricScale = 1.0;
  18970. break;
  18971. case Light.INTENSITYMODE_LUMINANCE:
  18972. photometricScale = this.radius * this.radius;
  18973. break;
  18974. }
  18975. break;
  18976. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18977. switch (photometricMode) {
  18978. case Light.INTENSITYMODE_ILLUMINANCE:
  18979. photometricScale = 1.0;
  18980. break;
  18981. case Light.INTENSITYMODE_LUMINANCE:
  18982. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18983. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18984. var apexAngleRadians = this.radius;
  18985. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18986. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18987. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18988. photometricScale = solidAngle;
  18989. break;
  18990. }
  18991. break;
  18992. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18993. // No fall off in hemisperic light.
  18994. photometricScale = 1.0;
  18995. break;
  18996. }
  18997. return photometricScale;
  18998. };
  18999. /**
  19000. * Reorder the light in the scene according to their defined priority.
  19001. * @ignore Internal Use Only
  19002. */
  19003. Light.prototype._reorderLightsInScene = function () {
  19004. var scene = this.getScene();
  19005. if (this._renderPriority != 0) {
  19006. scene.requireLightSorting = true;
  19007. }
  19008. this.getScene().sortLightsByPriority();
  19009. };
  19010. //lightmapMode Consts
  19011. Light._LIGHTMAP_DEFAULT = 0;
  19012. Light._LIGHTMAP_SPECULAR = 1;
  19013. Light._LIGHTMAP_SHADOWSONLY = 2;
  19014. // Intensity Mode Consts
  19015. Light._INTENSITYMODE_AUTOMATIC = 0;
  19016. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19017. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19018. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19019. Light._INTENSITYMODE_LUMINANCE = 4;
  19020. // Light types ids const.
  19021. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19022. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19023. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19024. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19025. __decorate([
  19026. BABYLON.serializeAsColor3()
  19027. ], Light.prototype, "diffuse", void 0);
  19028. __decorate([
  19029. BABYLON.serializeAsColor3()
  19030. ], Light.prototype, "specular", void 0);
  19031. __decorate([
  19032. BABYLON.serialize()
  19033. ], Light.prototype, "intensity", void 0);
  19034. __decorate([
  19035. BABYLON.serialize()
  19036. ], Light.prototype, "range", void 0);
  19037. __decorate([
  19038. BABYLON.serialize()
  19039. ], Light.prototype, "intensityMode", null);
  19040. __decorate([
  19041. BABYLON.serialize()
  19042. ], Light.prototype, "radius", null);
  19043. __decorate([
  19044. BABYLON.serialize()
  19045. ], Light.prototype, "_renderPriority", void 0);
  19046. __decorate([
  19047. BABYLON.expandToProperty("_reorderLightsInScene")
  19048. ], Light.prototype, "renderPriority", void 0);
  19049. __decorate([
  19050. BABYLON.serialize()
  19051. ], Light.prototype, "shadowEnabled", void 0);
  19052. __decorate([
  19053. BABYLON.serialize("excludeWithLayerMask")
  19054. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19055. __decorate([
  19056. BABYLON.serialize("includeOnlyWithLayerMask")
  19057. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19058. __decorate([
  19059. BABYLON.serialize("lightmapMode")
  19060. ], Light.prototype, "_lightmapMode", void 0);
  19061. return Light;
  19062. }(BABYLON.Node));
  19063. BABYLON.Light = Light;
  19064. })(BABYLON || (BABYLON = {}));
  19065. //# sourceMappingURL=babylon.light.js.map
  19066. var BABYLON;
  19067. (function (BABYLON) {
  19068. var Camera = /** @class */ (function (_super) {
  19069. __extends(Camera, _super);
  19070. function Camera(name, position, scene) {
  19071. var _this = _super.call(this, name, scene) || this;
  19072. /**
  19073. * The vector the camera should consider as up.
  19074. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19075. */
  19076. _this.upVector = BABYLON.Vector3.Up();
  19077. _this.orthoLeft = null;
  19078. _this.orthoRight = null;
  19079. _this.orthoBottom = null;
  19080. _this.orthoTop = null;
  19081. /**
  19082. * FOV is set in Radians. (default is 0.8)
  19083. */
  19084. _this.fov = 0.8;
  19085. _this.minZ = 1;
  19086. _this.maxZ = 10000.0;
  19087. _this.inertia = 0.9;
  19088. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19089. _this.isIntermediate = false;
  19090. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19091. /**
  19092. * Restricts the camera to viewing objects with the same layerMask.
  19093. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19094. */
  19095. _this.layerMask = 0x0FFFFFFF;
  19096. /**
  19097. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19098. */
  19099. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19100. // Camera rig members
  19101. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19102. _this._rigCameras = new Array();
  19103. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19104. _this._skipRendering = false;
  19105. _this.customRenderTargets = new Array();
  19106. // Observables
  19107. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19108. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19109. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19110. _this.onRestoreStateObservable = new BABYLON.Observable();
  19111. // Cache
  19112. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19113. _this._projectionMatrix = new BABYLON.Matrix();
  19114. _this._doNotComputeProjectionMatrix = false;
  19115. _this._postProcesses = new Array();
  19116. _this._transformMatrix = BABYLON.Matrix.Zero();
  19117. _this._activeMeshes = new BABYLON.SmartArray(256);
  19118. _this._globalPosition = BABYLON.Vector3.Zero();
  19119. _this._refreshFrustumPlanes = true;
  19120. _this.getScene().addCamera(_this);
  19121. if (!_this.getScene().activeCamera) {
  19122. _this.getScene().activeCamera = _this;
  19123. }
  19124. _this.position = position;
  19125. return _this;
  19126. }
  19127. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19128. get: function () {
  19129. return Camera._PERSPECTIVE_CAMERA;
  19130. },
  19131. enumerable: true,
  19132. configurable: true
  19133. });
  19134. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19135. get: function () {
  19136. return Camera._ORTHOGRAPHIC_CAMERA;
  19137. },
  19138. enumerable: true,
  19139. configurable: true
  19140. });
  19141. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19142. /**
  19143. * This is the default FOV mode for perspective cameras.
  19144. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19145. *
  19146. */
  19147. get: function () {
  19148. return Camera._FOVMODE_VERTICAL_FIXED;
  19149. },
  19150. enumerable: true,
  19151. configurable: true
  19152. });
  19153. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19154. /**
  19155. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19156. *
  19157. */
  19158. get: function () {
  19159. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19160. },
  19161. enumerable: true,
  19162. configurable: true
  19163. });
  19164. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19165. get: function () {
  19166. return Camera._RIG_MODE_NONE;
  19167. },
  19168. enumerable: true,
  19169. configurable: true
  19170. });
  19171. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19172. get: function () {
  19173. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19174. },
  19175. enumerable: true,
  19176. configurable: true
  19177. });
  19178. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19179. get: function () {
  19180. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19181. },
  19182. enumerable: true,
  19183. configurable: true
  19184. });
  19185. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19186. get: function () {
  19187. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19188. },
  19189. enumerable: true,
  19190. configurable: true
  19191. });
  19192. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19193. get: function () {
  19194. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19195. },
  19196. enumerable: true,
  19197. configurable: true
  19198. });
  19199. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19200. get: function () {
  19201. return Camera._RIG_MODE_VR;
  19202. },
  19203. enumerable: true,
  19204. configurable: true
  19205. });
  19206. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19207. get: function () {
  19208. return Camera._RIG_MODE_WEBVR;
  19209. },
  19210. enumerable: true,
  19211. configurable: true
  19212. });
  19213. /**
  19214. * Store current camera state (fov, position, etc..)
  19215. */
  19216. Camera.prototype.storeState = function () {
  19217. this._stateStored = true;
  19218. this._storedFov = this.fov;
  19219. return this;
  19220. };
  19221. /**
  19222. * Restores the camera state values if it has been stored. You must call storeState() first
  19223. */
  19224. Camera.prototype._restoreStateValues = function () {
  19225. if (!this._stateStored) {
  19226. return false;
  19227. }
  19228. this.fov = this._storedFov;
  19229. return true;
  19230. };
  19231. /**
  19232. * Restored camera state. You must call storeState() first
  19233. */
  19234. Camera.prototype.restoreState = function () {
  19235. if (this._restoreStateValues()) {
  19236. this.onRestoreStateObservable.notifyObservers(this);
  19237. return true;
  19238. }
  19239. return false;
  19240. };
  19241. Camera.prototype.getClassName = function () {
  19242. return "Camera";
  19243. };
  19244. /**
  19245. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19246. */
  19247. Camera.prototype.toString = function (fullDetails) {
  19248. var ret = "Name: " + this.name;
  19249. ret += ", type: " + this.getClassName();
  19250. if (this.animations) {
  19251. for (var i = 0; i < this.animations.length; i++) {
  19252. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19253. }
  19254. }
  19255. if (fullDetails) {
  19256. }
  19257. return ret;
  19258. };
  19259. Object.defineProperty(Camera.prototype, "globalPosition", {
  19260. get: function () {
  19261. return this._globalPosition;
  19262. },
  19263. enumerable: true,
  19264. configurable: true
  19265. });
  19266. Camera.prototype.getActiveMeshes = function () {
  19267. return this._activeMeshes;
  19268. };
  19269. Camera.prototype.isActiveMesh = function (mesh) {
  19270. return (this._activeMeshes.indexOf(mesh) !== -1);
  19271. };
  19272. //Cache
  19273. Camera.prototype._initCache = function () {
  19274. _super.prototype._initCache.call(this);
  19275. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19276. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19277. this._cache.mode = undefined;
  19278. this._cache.minZ = undefined;
  19279. this._cache.maxZ = undefined;
  19280. this._cache.fov = undefined;
  19281. this._cache.fovMode = undefined;
  19282. this._cache.aspectRatio = undefined;
  19283. this._cache.orthoLeft = undefined;
  19284. this._cache.orthoRight = undefined;
  19285. this._cache.orthoBottom = undefined;
  19286. this._cache.orthoTop = undefined;
  19287. this._cache.renderWidth = undefined;
  19288. this._cache.renderHeight = undefined;
  19289. };
  19290. Camera.prototype._updateCache = function (ignoreParentClass) {
  19291. if (!ignoreParentClass) {
  19292. _super.prototype._updateCache.call(this);
  19293. }
  19294. this._cache.position.copyFrom(this.position);
  19295. this._cache.upVector.copyFrom(this.upVector);
  19296. };
  19297. // Synchronized
  19298. Camera.prototype._isSynchronized = function () {
  19299. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19300. };
  19301. Camera.prototype._isSynchronizedViewMatrix = function () {
  19302. if (!_super.prototype._isSynchronized.call(this))
  19303. return false;
  19304. return this._cache.position.equals(this.position)
  19305. && this._cache.upVector.equals(this.upVector)
  19306. && this.isSynchronizedWithParent();
  19307. };
  19308. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19309. var check = this._cache.mode === this.mode
  19310. && this._cache.minZ === this.minZ
  19311. && this._cache.maxZ === this.maxZ;
  19312. if (!check) {
  19313. return false;
  19314. }
  19315. var engine = this.getEngine();
  19316. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19317. check = this._cache.fov === this.fov
  19318. && this._cache.fovMode === this.fovMode
  19319. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19320. }
  19321. else {
  19322. check = this._cache.orthoLeft === this.orthoLeft
  19323. && this._cache.orthoRight === this.orthoRight
  19324. && this._cache.orthoBottom === this.orthoBottom
  19325. && this._cache.orthoTop === this.orthoTop
  19326. && this._cache.renderWidth === engine.getRenderWidth()
  19327. && this._cache.renderHeight === engine.getRenderHeight();
  19328. }
  19329. return check;
  19330. };
  19331. // Controls
  19332. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19333. };
  19334. Camera.prototype.detachControl = function (element) {
  19335. };
  19336. Camera.prototype.update = function () {
  19337. this._checkInputs();
  19338. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19339. this._updateRigCameras();
  19340. }
  19341. };
  19342. Camera.prototype._checkInputs = function () {
  19343. this.onAfterCheckInputsObservable.notifyObservers(this);
  19344. };
  19345. Object.defineProperty(Camera.prototype, "rigCameras", {
  19346. get: function () {
  19347. return this._rigCameras;
  19348. },
  19349. enumerable: true,
  19350. configurable: true
  19351. });
  19352. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19353. get: function () {
  19354. return this._rigPostProcess;
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19360. // invalidate framebuffer
  19361. if (this._postProcesses.length > 0) {
  19362. this._postProcesses[0].markTextureDirty();
  19363. }
  19364. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19365. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19366. var cam = this._rigCameras[i];
  19367. var rigPostProcess = cam._rigPostProcess;
  19368. // for VR rig, there does not have to be a post process
  19369. if (rigPostProcess) {
  19370. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19371. if (isPass) {
  19372. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19373. cam.isIntermediate = this._postProcesses.length === 0;
  19374. }
  19375. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19376. rigPostProcess.markTextureDirty();
  19377. }
  19378. else {
  19379. cam._postProcesses = this._postProcesses.slice(0);
  19380. }
  19381. }
  19382. };
  19383. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19384. if (insertAt === void 0) { insertAt = null; }
  19385. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19386. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19387. return 0;
  19388. }
  19389. if (insertAt == null || insertAt < 0) {
  19390. this._postProcesses.push(postProcess);
  19391. }
  19392. else {
  19393. this._postProcesses.splice(insertAt, 0, postProcess);
  19394. }
  19395. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19396. return this._postProcesses.indexOf(postProcess);
  19397. };
  19398. Camera.prototype.detachPostProcess = function (postProcess) {
  19399. var idx = this._postProcesses.indexOf(postProcess);
  19400. if (idx !== -1) {
  19401. this._postProcesses.splice(idx, 1);
  19402. }
  19403. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19404. };
  19405. Camera.prototype.getWorldMatrix = function () {
  19406. if (!this._worldMatrix) {
  19407. this._worldMatrix = BABYLON.Matrix.Identity();
  19408. }
  19409. var viewMatrix = this.getViewMatrix();
  19410. viewMatrix.invertToRef(this._worldMatrix);
  19411. return this._worldMatrix;
  19412. };
  19413. Camera.prototype._getViewMatrix = function () {
  19414. return BABYLON.Matrix.Identity();
  19415. };
  19416. Camera.prototype.getViewMatrix = function (force) {
  19417. if (!force && this._isSynchronizedViewMatrix()) {
  19418. return this._computedViewMatrix;
  19419. }
  19420. this.updateCache();
  19421. this._computedViewMatrix = this._getViewMatrix();
  19422. this._currentRenderId = this.getScene().getRenderId();
  19423. this._refreshFrustumPlanes = true;
  19424. if (!this.parent || !this.parent.getWorldMatrix) {
  19425. this._globalPosition.copyFrom(this.position);
  19426. }
  19427. else {
  19428. if (!this._worldMatrix) {
  19429. this._worldMatrix = BABYLON.Matrix.Identity();
  19430. }
  19431. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19432. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19433. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19434. this._computedViewMatrix.invert();
  19435. this._markSyncedWithParent();
  19436. }
  19437. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19438. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19439. }
  19440. this.onViewMatrixChangedObservable.notifyObservers(this);
  19441. return this._computedViewMatrix;
  19442. };
  19443. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19444. this._doNotComputeProjectionMatrix = true;
  19445. if (projection !== undefined) {
  19446. this._projectionMatrix = projection;
  19447. }
  19448. };
  19449. ;
  19450. Camera.prototype.unfreezeProjectionMatrix = function () {
  19451. this._doNotComputeProjectionMatrix = false;
  19452. };
  19453. ;
  19454. Camera.prototype.getProjectionMatrix = function (force) {
  19455. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19456. return this._projectionMatrix;
  19457. }
  19458. // Cache
  19459. this._cache.mode = this.mode;
  19460. this._cache.minZ = this.minZ;
  19461. this._cache.maxZ = this.maxZ;
  19462. // Matrix
  19463. this._refreshFrustumPlanes = true;
  19464. var engine = this.getEngine();
  19465. var scene = this.getScene();
  19466. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19467. this._cache.fov = this.fov;
  19468. this._cache.fovMode = this.fovMode;
  19469. this._cache.aspectRatio = engine.getAspectRatio(this);
  19470. if (this.minZ <= 0) {
  19471. this.minZ = 0.1;
  19472. }
  19473. if (scene.useRightHandedSystem) {
  19474. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19475. }
  19476. else {
  19477. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19478. }
  19479. }
  19480. else {
  19481. var halfWidth = engine.getRenderWidth() / 2.0;
  19482. var halfHeight = engine.getRenderHeight() / 2.0;
  19483. if (scene.useRightHandedSystem) {
  19484. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19485. }
  19486. else {
  19487. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19488. }
  19489. this._cache.orthoLeft = this.orthoLeft;
  19490. this._cache.orthoRight = this.orthoRight;
  19491. this._cache.orthoBottom = this.orthoBottom;
  19492. this._cache.orthoTop = this.orthoTop;
  19493. this._cache.renderWidth = engine.getRenderWidth();
  19494. this._cache.renderHeight = engine.getRenderHeight();
  19495. }
  19496. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19497. return this._projectionMatrix;
  19498. };
  19499. Camera.prototype.getTranformationMatrix = function () {
  19500. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19501. return this._transformMatrix;
  19502. };
  19503. Camera.prototype.updateFrustumPlanes = function () {
  19504. if (!this._refreshFrustumPlanes) {
  19505. return;
  19506. }
  19507. this.getTranformationMatrix();
  19508. if (!this._frustumPlanes) {
  19509. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19510. }
  19511. else {
  19512. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19513. }
  19514. this._refreshFrustumPlanes = false;
  19515. };
  19516. Camera.prototype.isInFrustum = function (target) {
  19517. this.updateFrustumPlanes();
  19518. return target.isInFrustum(this._frustumPlanes);
  19519. };
  19520. Camera.prototype.isCompletelyInFrustum = function (target) {
  19521. this.updateFrustumPlanes();
  19522. return target.isCompletelyInFrustum(this._frustumPlanes);
  19523. };
  19524. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19525. if (length === void 0) { length = 100; }
  19526. if (!transform) {
  19527. transform = this.getWorldMatrix();
  19528. }
  19529. if (!origin) {
  19530. origin = this.position;
  19531. }
  19532. var forward = new BABYLON.Vector3(0, 0, 1);
  19533. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19534. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19535. return new BABYLON.Ray(origin, direction, length);
  19536. };
  19537. Camera.prototype.dispose = function () {
  19538. // Observables
  19539. this.onViewMatrixChangedObservable.clear();
  19540. this.onProjectionMatrixChangedObservable.clear();
  19541. this.onAfterCheckInputsObservable.clear();
  19542. this.onRestoreStateObservable.clear();
  19543. // Inputs
  19544. if (this.inputs) {
  19545. this.inputs.clear();
  19546. }
  19547. // Animations
  19548. this.getScene().stopAnimation(this);
  19549. // Remove from scene
  19550. this.getScene().removeCamera(this);
  19551. while (this._rigCameras.length > 0) {
  19552. var camera = this._rigCameras.pop();
  19553. if (camera) {
  19554. camera.dispose();
  19555. }
  19556. }
  19557. // Postprocesses
  19558. if (this._rigPostProcess) {
  19559. this._rigPostProcess.dispose(this);
  19560. this._rigPostProcess = null;
  19561. this._postProcesses = [];
  19562. }
  19563. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19564. this._rigPostProcess = null;
  19565. this._postProcesses = [];
  19566. }
  19567. else {
  19568. var i = this._postProcesses.length;
  19569. while (--i >= 0) {
  19570. this._postProcesses[i].dispose(this);
  19571. }
  19572. }
  19573. // Render targets
  19574. var i = this.customRenderTargets.length;
  19575. while (--i >= 0) {
  19576. this.customRenderTargets[i].dispose();
  19577. }
  19578. this.customRenderTargets = [];
  19579. // Active Meshes
  19580. this._activeMeshes.dispose();
  19581. _super.prototype.dispose.call(this);
  19582. };
  19583. Object.defineProperty(Camera.prototype, "leftCamera", {
  19584. // ---- Camera rigs section ----
  19585. get: function () {
  19586. if (this._rigCameras.length < 1) {
  19587. return null;
  19588. }
  19589. return this._rigCameras[0];
  19590. },
  19591. enumerable: true,
  19592. configurable: true
  19593. });
  19594. Object.defineProperty(Camera.prototype, "rightCamera", {
  19595. get: function () {
  19596. if (this._rigCameras.length < 2) {
  19597. return null;
  19598. }
  19599. return this._rigCameras[1];
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Camera.prototype.getLeftTarget = function () {
  19605. if (this._rigCameras.length < 1) {
  19606. return null;
  19607. }
  19608. return this._rigCameras[0].getTarget();
  19609. };
  19610. Camera.prototype.getRightTarget = function () {
  19611. if (this._rigCameras.length < 2) {
  19612. return null;
  19613. }
  19614. return this._rigCameras[1].getTarget();
  19615. };
  19616. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19617. if (this.cameraRigMode === mode) {
  19618. return;
  19619. }
  19620. while (this._rigCameras.length > 0) {
  19621. var camera = this._rigCameras.pop();
  19622. if (camera) {
  19623. camera.dispose();
  19624. }
  19625. }
  19626. this.cameraRigMode = mode;
  19627. this._cameraRigParams = {};
  19628. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19629. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19630. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19631. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19632. // create the rig cameras, unless none
  19633. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19634. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19635. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19636. if (leftCamera && rightCamera) {
  19637. this._rigCameras.push(leftCamera);
  19638. this._rigCameras.push(rightCamera);
  19639. }
  19640. }
  19641. switch (this.cameraRigMode) {
  19642. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19643. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19644. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19645. break;
  19646. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19647. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19648. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19649. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19650. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19651. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19652. break;
  19653. case Camera.RIG_MODE_VR:
  19654. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19655. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19656. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19657. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19658. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19659. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19660. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19661. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19662. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19663. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19664. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19665. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19666. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19667. if (metrics.compensateDistortion) {
  19668. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19669. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19670. }
  19671. break;
  19672. case Camera.RIG_MODE_WEBVR:
  19673. if (rigParams.vrDisplay) {
  19674. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19675. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19676. //Left eye
  19677. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19678. this._rigCameras[0].setCameraRigParameter("left", true);
  19679. //leaving this for future reference
  19680. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19681. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19682. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19683. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19684. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19685. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19686. this._rigCameras[0].parent = this;
  19687. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19688. //Right eye
  19689. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19690. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19691. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19692. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19693. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19694. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19695. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19696. this._rigCameras[1].parent = this;
  19697. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19698. if (Camera.UseAlternateWebVRRendering) {
  19699. this._rigCameras[1]._skipRendering = true;
  19700. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19701. }
  19702. }
  19703. break;
  19704. }
  19705. this._cascadePostProcessesToRigCams();
  19706. this.update();
  19707. };
  19708. Camera.prototype._getVRProjectionMatrix = function () {
  19709. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19710. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19711. return this._projectionMatrix;
  19712. };
  19713. Camera.prototype._updateCameraRotationMatrix = function () {
  19714. //Here for WebVR
  19715. };
  19716. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19717. //Here for WebVR
  19718. };
  19719. /**
  19720. * This function MUST be overwritten by the different WebVR cameras available.
  19721. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19722. */
  19723. Camera.prototype._getWebVRProjectionMatrix = function () {
  19724. return BABYLON.Matrix.Identity();
  19725. };
  19726. /**
  19727. * This function MUST be overwritten by the different WebVR cameras available.
  19728. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19729. */
  19730. Camera.prototype._getWebVRViewMatrix = function () {
  19731. return BABYLON.Matrix.Identity();
  19732. };
  19733. Camera.prototype.setCameraRigParameter = function (name, value) {
  19734. if (!this._cameraRigParams) {
  19735. this._cameraRigParams = {};
  19736. }
  19737. this._cameraRigParams[name] = value;
  19738. //provisionnally:
  19739. if (name === "interaxialDistance") {
  19740. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19741. }
  19742. };
  19743. /**
  19744. * needs to be overridden by children so sub has required properties to be copied
  19745. */
  19746. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19747. return null;
  19748. };
  19749. /**
  19750. * May need to be overridden by children
  19751. */
  19752. Camera.prototype._updateRigCameras = function () {
  19753. for (var i = 0; i < this._rigCameras.length; i++) {
  19754. this._rigCameras[i].minZ = this.minZ;
  19755. this._rigCameras[i].maxZ = this.maxZ;
  19756. this._rigCameras[i].fov = this.fov;
  19757. }
  19758. // only update viewport when ANAGLYPH
  19759. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19760. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19761. }
  19762. };
  19763. Camera.prototype._setupInputs = function () {
  19764. };
  19765. Camera.prototype.serialize = function () {
  19766. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19767. // Type
  19768. serializationObject.type = this.getClassName();
  19769. // Parent
  19770. if (this.parent) {
  19771. serializationObject.parentId = this.parent.id;
  19772. }
  19773. if (this.inputs) {
  19774. this.inputs.serialize(serializationObject);
  19775. }
  19776. // Animations
  19777. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19778. serializationObject.ranges = this.serializeAnimationRanges();
  19779. return serializationObject;
  19780. };
  19781. Camera.prototype.clone = function (name) {
  19782. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19783. };
  19784. Camera.prototype.getDirection = function (localAxis) {
  19785. var result = BABYLON.Vector3.Zero();
  19786. this.getDirectionToRef(localAxis, result);
  19787. return result;
  19788. };
  19789. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19790. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19791. };
  19792. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19793. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19794. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19795. switch (type) {
  19796. case "ArcRotateCamera":
  19797. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19798. case "DeviceOrientationCamera":
  19799. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19800. case "FollowCamera":
  19801. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19802. case "ArcFollowCamera":
  19803. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19804. case "GamepadCamera":
  19805. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19806. case "TouchCamera":
  19807. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19808. case "VirtualJoysticksCamera":
  19809. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19810. case "WebVRFreeCamera":
  19811. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19812. case "WebVRGamepadCamera":
  19813. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19814. case "VRDeviceOrientationFreeCamera":
  19815. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19816. case "VRDeviceOrientationGamepadCamera":
  19817. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19818. case "AnaglyphArcRotateCamera":
  19819. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19820. case "AnaglyphFreeCamera":
  19821. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19822. case "AnaglyphGamepadCamera":
  19823. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19824. case "AnaglyphUniversalCamera":
  19825. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19826. case "StereoscopicArcRotateCamera":
  19827. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19828. case "StereoscopicFreeCamera":
  19829. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19830. case "StereoscopicGamepadCamera":
  19831. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19832. case "StereoscopicUniversalCamera":
  19833. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19834. case "FreeCamera":// Forcing Universal here
  19835. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19836. default:// Universal Camera is the default value
  19837. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19838. }
  19839. };
  19840. Camera.prototype.computeWorldMatrix = function () {
  19841. return this.getWorldMatrix();
  19842. };
  19843. Camera.Parse = function (parsedCamera, scene) {
  19844. var type = parsedCamera.type;
  19845. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19846. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19847. // Parent
  19848. if (parsedCamera.parentId) {
  19849. camera._waitingParentId = parsedCamera.parentId;
  19850. }
  19851. //If camera has an input manager, let it parse inputs settings
  19852. if (camera.inputs) {
  19853. camera.inputs.parse(parsedCamera);
  19854. camera._setupInputs();
  19855. }
  19856. if (camera.setPosition) {
  19857. camera.position.copyFromFloats(0, 0, 0);
  19858. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19859. }
  19860. // Target
  19861. if (parsedCamera.target) {
  19862. if (camera.setTarget) {
  19863. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19864. }
  19865. }
  19866. // Apply 3d rig, when found
  19867. if (parsedCamera.cameraRigMode) {
  19868. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19869. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19870. }
  19871. // Animations
  19872. if (parsedCamera.animations) {
  19873. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19874. var parsedAnimation = parsedCamera.animations[animationIndex];
  19875. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19876. }
  19877. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19878. }
  19879. if (parsedCamera.autoAnimate) {
  19880. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19881. }
  19882. return camera;
  19883. };
  19884. // Statics
  19885. Camera._PERSPECTIVE_CAMERA = 0;
  19886. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19887. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19888. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19889. Camera._RIG_MODE_NONE = 0;
  19890. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19891. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19892. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19893. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19894. Camera._RIG_MODE_VR = 20;
  19895. Camera._RIG_MODE_WEBVR = 21;
  19896. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19897. Camera.UseAlternateWebVRRendering = false;
  19898. __decorate([
  19899. BABYLON.serializeAsVector3()
  19900. ], Camera.prototype, "position", void 0);
  19901. __decorate([
  19902. BABYLON.serializeAsVector3()
  19903. ], Camera.prototype, "upVector", void 0);
  19904. __decorate([
  19905. BABYLON.serialize()
  19906. ], Camera.prototype, "orthoLeft", void 0);
  19907. __decorate([
  19908. BABYLON.serialize()
  19909. ], Camera.prototype, "orthoRight", void 0);
  19910. __decorate([
  19911. BABYLON.serialize()
  19912. ], Camera.prototype, "orthoBottom", void 0);
  19913. __decorate([
  19914. BABYLON.serialize()
  19915. ], Camera.prototype, "orthoTop", void 0);
  19916. __decorate([
  19917. BABYLON.serialize()
  19918. ], Camera.prototype, "fov", void 0);
  19919. __decorate([
  19920. BABYLON.serialize()
  19921. ], Camera.prototype, "minZ", void 0);
  19922. __decorate([
  19923. BABYLON.serialize()
  19924. ], Camera.prototype, "maxZ", void 0);
  19925. __decorate([
  19926. BABYLON.serialize()
  19927. ], Camera.prototype, "inertia", void 0);
  19928. __decorate([
  19929. BABYLON.serialize()
  19930. ], Camera.prototype, "mode", void 0);
  19931. __decorate([
  19932. BABYLON.serialize()
  19933. ], Camera.prototype, "layerMask", void 0);
  19934. __decorate([
  19935. BABYLON.serialize()
  19936. ], Camera.prototype, "fovMode", void 0);
  19937. __decorate([
  19938. BABYLON.serialize()
  19939. ], Camera.prototype, "cameraRigMode", void 0);
  19940. __decorate([
  19941. BABYLON.serialize()
  19942. ], Camera.prototype, "interaxialDistance", void 0);
  19943. __decorate([
  19944. BABYLON.serialize()
  19945. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19946. return Camera;
  19947. }(BABYLON.Node));
  19948. BABYLON.Camera = Camera;
  19949. })(BABYLON || (BABYLON = {}));
  19950. //# sourceMappingURL=babylon.camera.js.map
  19951. var BABYLON;
  19952. (function (BABYLON) {
  19953. var RenderingManager = /** @class */ (function () {
  19954. function RenderingManager(scene) {
  19955. this._renderingGroups = new Array();
  19956. this._autoClearDepthStencil = {};
  19957. this._customOpaqueSortCompareFn = {};
  19958. this._customAlphaTestSortCompareFn = {};
  19959. this._customTransparentSortCompareFn = {};
  19960. this._renderinGroupInfo = null;
  19961. this._scene = scene;
  19962. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19963. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19964. }
  19965. }
  19966. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19967. if (depth === void 0) { depth = true; }
  19968. if (stencil === void 0) { stencil = true; }
  19969. if (this._depthStencilBufferAlreadyCleaned) {
  19970. return;
  19971. }
  19972. this._scene.getEngine().clear(null, false, depth, stencil);
  19973. this._depthStencilBufferAlreadyCleaned = true;
  19974. };
  19975. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19976. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19977. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19978. var info = null;
  19979. if (observable) {
  19980. if (!this._renderinGroupInfo) {
  19981. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19982. }
  19983. info = this._renderinGroupInfo;
  19984. info.scene = this._scene;
  19985. info.camera = this._scene.activeCamera;
  19986. }
  19987. // Dispatch sprites
  19988. if (renderSprites) {
  19989. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19990. var manager = this._scene.spriteManagers[index];
  19991. this.dispatchSprites(manager);
  19992. }
  19993. }
  19994. // Render
  19995. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19996. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19997. var renderingGroup = this._renderingGroups[index];
  19998. if (!renderingGroup && !observable)
  19999. continue;
  20000. var renderingGroupMask = 0;
  20001. // Fire PRECLEAR stage
  20002. if (observable && info) {
  20003. renderingGroupMask = Math.pow(2, index);
  20004. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20005. info.renderingGroupId = index;
  20006. observable.notifyObservers(info, renderingGroupMask);
  20007. }
  20008. // Clear depth/stencil if needed
  20009. if (RenderingManager.AUTOCLEAR) {
  20010. var autoClear = this._autoClearDepthStencil[index];
  20011. if (autoClear && autoClear.autoClear) {
  20012. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20013. }
  20014. }
  20015. if (observable && info) {
  20016. // Fire PREOPAQUE stage
  20017. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20018. observable.notifyObservers(info, renderingGroupMask);
  20019. // Fire PRETRANSPARENT stage
  20020. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20021. observable.notifyObservers(info, renderingGroupMask);
  20022. }
  20023. if (renderingGroup)
  20024. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20025. // Fire POSTTRANSPARENT stage
  20026. if (observable && info) {
  20027. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20028. observable.notifyObservers(info, renderingGroupMask);
  20029. }
  20030. }
  20031. };
  20032. RenderingManager.prototype.reset = function () {
  20033. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20034. var renderingGroup = this._renderingGroups[index];
  20035. if (renderingGroup) {
  20036. renderingGroup.prepare();
  20037. }
  20038. }
  20039. };
  20040. RenderingManager.prototype.dispose = function () {
  20041. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20042. var renderingGroup = this._renderingGroups[index];
  20043. if (renderingGroup) {
  20044. renderingGroup.dispose();
  20045. }
  20046. }
  20047. this._renderingGroups.length = 0;
  20048. };
  20049. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20050. if (this._renderingGroups[renderingGroupId] === undefined) {
  20051. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20052. }
  20053. };
  20054. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20055. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20056. this._prepareRenderingGroup(renderingGroupId);
  20057. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20058. };
  20059. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20060. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20061. this._prepareRenderingGroup(renderingGroupId);
  20062. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20063. };
  20064. /**
  20065. * @param subMesh The submesh to dispatch
  20066. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20067. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20068. */
  20069. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20070. if (mesh === undefined) {
  20071. mesh = subMesh.getMesh();
  20072. }
  20073. var renderingGroupId = mesh.renderingGroupId || 0;
  20074. this._prepareRenderingGroup(renderingGroupId);
  20075. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20076. };
  20077. /**
  20078. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20079. * This allowed control for front to back rendering or reversly depending of the special needs.
  20080. *
  20081. * @param renderingGroupId The rendering group id corresponding to its index
  20082. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20083. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20084. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20085. */
  20086. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20087. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20088. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20089. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20090. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20091. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20092. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20093. if (this._renderingGroups[renderingGroupId]) {
  20094. var group = this._renderingGroups[renderingGroupId];
  20095. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20096. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20097. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20098. }
  20099. };
  20100. /**
  20101. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20102. *
  20103. * @param renderingGroupId The rendering group id corresponding to its index
  20104. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20105. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20106. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20107. */
  20108. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20109. if (depth === void 0) { depth = true; }
  20110. if (stencil === void 0) { stencil = true; }
  20111. this._autoClearDepthStencil[renderingGroupId] = {
  20112. autoClear: autoClearDepthStencil,
  20113. depth: depth,
  20114. stencil: stencil
  20115. };
  20116. };
  20117. /**
  20118. * The max id used for rendering groups (not included)
  20119. */
  20120. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20121. /**
  20122. * The min id used for rendering groups (included)
  20123. */
  20124. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20125. /**
  20126. * Used to globally prevent autoclearing scenes.
  20127. */
  20128. RenderingManager.AUTOCLEAR = true;
  20129. return RenderingManager;
  20130. }());
  20131. BABYLON.RenderingManager = RenderingManager;
  20132. })(BABYLON || (BABYLON = {}));
  20133. //# sourceMappingURL=babylon.renderingManager.js.map
  20134. var BABYLON;
  20135. (function (BABYLON) {
  20136. var RenderingGroup = /** @class */ (function () {
  20137. /**
  20138. * Creates a new rendering group.
  20139. * @param index The rendering group index
  20140. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20141. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20142. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20143. */
  20144. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20145. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20146. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20147. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20148. this.index = index;
  20149. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20150. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20151. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20152. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20153. this._particleSystems = new BABYLON.SmartArray(256);
  20154. this._spriteManagers = new BABYLON.SmartArray(256);
  20155. this._edgesRenderers = new BABYLON.SmartArray(16);
  20156. this._scene = scene;
  20157. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20158. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20159. this.transparentSortCompareFn = transparentSortCompareFn;
  20160. }
  20161. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20162. /**
  20163. * Set the opaque sort comparison function.
  20164. * If null the sub meshes will be render in the order they were created
  20165. */
  20166. set: function (value) {
  20167. this._opaqueSortCompareFn = value;
  20168. if (value) {
  20169. this._renderOpaque = this.renderOpaqueSorted;
  20170. }
  20171. else {
  20172. this._renderOpaque = RenderingGroup.renderUnsorted;
  20173. }
  20174. },
  20175. enumerable: true,
  20176. configurable: true
  20177. });
  20178. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20179. /**
  20180. * Set the alpha test sort comparison function.
  20181. * If null the sub meshes will be render in the order they were created
  20182. */
  20183. set: function (value) {
  20184. this._alphaTestSortCompareFn = value;
  20185. if (value) {
  20186. this._renderAlphaTest = this.renderAlphaTestSorted;
  20187. }
  20188. else {
  20189. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20190. }
  20191. },
  20192. enumerable: true,
  20193. configurable: true
  20194. });
  20195. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20196. /**
  20197. * Set the transparent sort comparison function.
  20198. * If null the sub meshes will be render in the order they were created
  20199. */
  20200. set: function (value) {
  20201. if (value) {
  20202. this._transparentSortCompareFn = value;
  20203. }
  20204. else {
  20205. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20206. }
  20207. this._renderTransparent = this.renderTransparentSorted;
  20208. },
  20209. enumerable: true,
  20210. configurable: true
  20211. });
  20212. /**
  20213. * Render all the sub meshes contained in the group.
  20214. * @param customRenderFunction Used to override the default render behaviour of the group.
  20215. * @returns true if rendered some submeshes.
  20216. */
  20217. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20218. if (customRenderFunction) {
  20219. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20220. return;
  20221. }
  20222. var engine = this._scene.getEngine();
  20223. // Depth only
  20224. if (this._depthOnlySubMeshes.length !== 0) {
  20225. engine.setColorWrite(false);
  20226. this._renderAlphaTest(this._depthOnlySubMeshes);
  20227. engine.setColorWrite(true);
  20228. }
  20229. // Opaque
  20230. if (this._opaqueSubMeshes.length !== 0) {
  20231. this._renderOpaque(this._opaqueSubMeshes);
  20232. }
  20233. // Alpha test
  20234. if (this._alphaTestSubMeshes.length !== 0) {
  20235. this._renderAlphaTest(this._alphaTestSubMeshes);
  20236. }
  20237. var stencilState = engine.getStencilBuffer();
  20238. engine.setStencilBuffer(false);
  20239. // Sprites
  20240. if (renderSprites) {
  20241. this._renderSprites();
  20242. }
  20243. // Particles
  20244. if (renderParticles) {
  20245. this._renderParticles(activeMeshes);
  20246. }
  20247. if (this.onBeforeTransparentRendering) {
  20248. this.onBeforeTransparentRendering();
  20249. }
  20250. // Transparent
  20251. if (this._transparentSubMeshes.length !== 0) {
  20252. this._renderTransparent(this._transparentSubMeshes);
  20253. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20254. }
  20255. // Set back stencil to false in case it changes before the edge renderer.
  20256. engine.setStencilBuffer(false);
  20257. // Edges
  20258. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20259. this._edgesRenderers.data[edgesRendererIndex].render();
  20260. }
  20261. // Restore Stencil state.
  20262. engine.setStencilBuffer(stencilState);
  20263. };
  20264. /**
  20265. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20266. * @param subMeshes The submeshes to render
  20267. */
  20268. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20269. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20270. };
  20271. /**
  20272. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20273. * @param subMeshes The submeshes to render
  20274. */
  20275. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20276. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20277. };
  20278. /**
  20279. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20280. * @param subMeshes The submeshes to render
  20281. */
  20282. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20283. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20284. };
  20285. /**
  20286. * Renders the submeshes in a specified order.
  20287. * @param subMeshes The submeshes to sort before render
  20288. * @param sortCompareFn The comparison function use to sort
  20289. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20290. * @param transparent Specifies to activate blending if true
  20291. */
  20292. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20293. var subIndex = 0;
  20294. var subMesh;
  20295. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20296. for (; subIndex < subMeshes.length; subIndex++) {
  20297. subMesh = subMeshes.data[subIndex];
  20298. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20299. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20300. }
  20301. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20302. if (sortCompareFn) {
  20303. sortedArray.sort(sortCompareFn);
  20304. }
  20305. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20306. subMesh = sortedArray[subIndex];
  20307. if (transparent) {
  20308. var material = subMesh.getMaterial();
  20309. if (material && material.needDepthPrePass) {
  20310. var engine = material.getScene().getEngine();
  20311. engine.setColorWrite(false);
  20312. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20313. subMesh.render(false);
  20314. engine.setColorWrite(true);
  20315. }
  20316. }
  20317. subMesh.render(transparent);
  20318. }
  20319. };
  20320. /**
  20321. * Renders the submeshes in the order they were dispatched (no sort applied).
  20322. * @param subMeshes The submeshes to render
  20323. */
  20324. RenderingGroup.renderUnsorted = function (subMeshes) {
  20325. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20326. var submesh = subMeshes.data[subIndex];
  20327. submesh.render(false);
  20328. }
  20329. };
  20330. /**
  20331. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20332. * are rendered back to front if in the same alpha index.
  20333. *
  20334. * @param a The first submesh
  20335. * @param b The second submesh
  20336. * @returns The result of the comparison
  20337. */
  20338. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20339. // Alpha index first
  20340. if (a._alphaIndex > b._alphaIndex) {
  20341. return 1;
  20342. }
  20343. if (a._alphaIndex < b._alphaIndex) {
  20344. return -1;
  20345. }
  20346. // Then distance to camera
  20347. return RenderingGroup.backToFrontSortCompare(a, b);
  20348. };
  20349. /**
  20350. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20351. * are rendered back to front.
  20352. *
  20353. * @param a The first submesh
  20354. * @param b The second submesh
  20355. * @returns The result of the comparison
  20356. */
  20357. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20358. // Then distance to camera
  20359. if (a._distanceToCamera < b._distanceToCamera) {
  20360. return 1;
  20361. }
  20362. if (a._distanceToCamera > b._distanceToCamera) {
  20363. return -1;
  20364. }
  20365. return 0;
  20366. };
  20367. /**
  20368. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20369. * are rendered front to back (prevent overdraw).
  20370. *
  20371. * @param a The first submesh
  20372. * @param b The second submesh
  20373. * @returns The result of the comparison
  20374. */
  20375. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20376. // Then distance to camera
  20377. if (a._distanceToCamera < b._distanceToCamera) {
  20378. return -1;
  20379. }
  20380. if (a._distanceToCamera > b._distanceToCamera) {
  20381. return 1;
  20382. }
  20383. return 0;
  20384. };
  20385. /**
  20386. * Resets the different lists of submeshes to prepare a new frame.
  20387. */
  20388. RenderingGroup.prototype.prepare = function () {
  20389. this._opaqueSubMeshes.reset();
  20390. this._transparentSubMeshes.reset();
  20391. this._alphaTestSubMeshes.reset();
  20392. this._depthOnlySubMeshes.reset();
  20393. this._particleSystems.reset();
  20394. this._spriteManagers.reset();
  20395. this._edgesRenderers.reset();
  20396. };
  20397. RenderingGroup.prototype.dispose = function () {
  20398. this._opaqueSubMeshes.dispose();
  20399. this._transparentSubMeshes.dispose();
  20400. this._alphaTestSubMeshes.dispose();
  20401. this._depthOnlySubMeshes.dispose();
  20402. this._particleSystems.dispose();
  20403. this._spriteManagers.dispose();
  20404. this._edgesRenderers.dispose();
  20405. };
  20406. /**
  20407. * Inserts the submesh in its correct queue depending on its material.
  20408. * @param subMesh The submesh to dispatch
  20409. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20410. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20411. */
  20412. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20413. // Get mesh and materials if not provided
  20414. if (mesh === undefined) {
  20415. mesh = subMesh.getMesh();
  20416. }
  20417. if (material === undefined) {
  20418. material = subMesh.getMaterial();
  20419. }
  20420. if (material === null || material === undefined) {
  20421. return;
  20422. }
  20423. if (material.needAlphaBlendingForMesh(mesh)) {
  20424. this._transparentSubMeshes.push(subMesh);
  20425. }
  20426. else if (material.needAlphaTesting()) {
  20427. if (material.needDepthPrePass) {
  20428. this._depthOnlySubMeshes.push(subMesh);
  20429. }
  20430. this._alphaTestSubMeshes.push(subMesh);
  20431. }
  20432. else {
  20433. if (material.needDepthPrePass) {
  20434. this._depthOnlySubMeshes.push(subMesh);
  20435. }
  20436. this._opaqueSubMeshes.push(subMesh); // Opaque
  20437. }
  20438. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20439. this._edgesRenderers.push(mesh._edgesRenderer);
  20440. }
  20441. };
  20442. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20443. this._spriteManagers.push(spriteManager);
  20444. };
  20445. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20446. this._particleSystems.push(particleSystem);
  20447. };
  20448. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20449. if (this._particleSystems.length === 0) {
  20450. return;
  20451. }
  20452. // Particles
  20453. var activeCamera = this._scene.activeCamera;
  20454. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20455. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  20456. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  20457. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20458. continue;
  20459. }
  20460. var emitter = particleSystem.emitter;
  20461. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20462. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20463. }
  20464. }
  20465. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20466. };
  20467. RenderingGroup.prototype._renderSprites = function () {
  20468. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20469. return;
  20470. }
  20471. // Sprites
  20472. var activeCamera = this._scene.activeCamera;
  20473. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20474. for (var id = 0; id < this._spriteManagers.length; id++) {
  20475. var spriteManager = this._spriteManagers.data[id];
  20476. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20477. spriteManager.render();
  20478. }
  20479. }
  20480. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20481. };
  20482. return RenderingGroup;
  20483. }());
  20484. BABYLON.RenderingGroup = RenderingGroup;
  20485. })(BABYLON || (BABYLON = {}));
  20486. //# sourceMappingURL=babylon.renderingGroup.js.map
  20487. var BABYLON;
  20488. (function (BABYLON) {
  20489. var ClickInfo = /** @class */ (function () {
  20490. function ClickInfo() {
  20491. this._singleClick = false;
  20492. this._doubleClick = false;
  20493. this._hasSwiped = false;
  20494. this._ignore = false;
  20495. }
  20496. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20497. get: function () {
  20498. return this._singleClick;
  20499. },
  20500. set: function (b) {
  20501. this._singleClick = b;
  20502. },
  20503. enumerable: true,
  20504. configurable: true
  20505. });
  20506. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20507. get: function () {
  20508. return this._doubleClick;
  20509. },
  20510. set: function (b) {
  20511. this._doubleClick = b;
  20512. },
  20513. enumerable: true,
  20514. configurable: true
  20515. });
  20516. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20517. get: function () {
  20518. return this._hasSwiped;
  20519. },
  20520. set: function (b) {
  20521. this._hasSwiped = b;
  20522. },
  20523. enumerable: true,
  20524. configurable: true
  20525. });
  20526. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20527. get: function () {
  20528. return this._ignore;
  20529. },
  20530. set: function (b) {
  20531. this._ignore = b;
  20532. },
  20533. enumerable: true,
  20534. configurable: true
  20535. });
  20536. return ClickInfo;
  20537. }());
  20538. /**
  20539. * This class is used by the onRenderingGroupObservable
  20540. */
  20541. var RenderingGroupInfo = /** @class */ (function () {
  20542. function RenderingGroupInfo() {
  20543. }
  20544. /**
  20545. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20546. * This stage will be fired no matter what
  20547. */
  20548. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20549. /**
  20550. * Called before opaque object are rendered.
  20551. * This stage will be fired only if there's 3D Opaque content to render
  20552. */
  20553. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20554. /**
  20555. * Called after the opaque objects are rendered and before the transparent ones
  20556. * This stage will be fired only if there's 3D transparent content to render
  20557. */
  20558. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20559. /**
  20560. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20561. * This stage will be fired no matter what
  20562. */
  20563. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20564. return RenderingGroupInfo;
  20565. }());
  20566. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20567. /**
  20568. * Represents a scene to be rendered by the engine.
  20569. * @see http://doc.babylonjs.com/page.php?p=21911
  20570. */
  20571. var Scene = /** @class */ (function () {
  20572. /**
  20573. * @constructor
  20574. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20575. */
  20576. function Scene(engine) {
  20577. // Members
  20578. this.autoClear = true;
  20579. this.autoClearDepthAndStencil = true;
  20580. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20581. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20582. this.forceWireframe = false;
  20583. this._forcePointsCloud = false;
  20584. this.forceShowBoundingBoxes = false;
  20585. this.animationsEnabled = true;
  20586. this.useConstantAnimationDeltaTime = false;
  20587. this.constantlyUpdateMeshUnderPointer = false;
  20588. this.hoverCursor = "pointer";
  20589. this.defaultCursor = "";
  20590. /**
  20591. * This is used to call preventDefault() on pointer down
  20592. * in order to block unwanted artifacts like system double clicks
  20593. */
  20594. this.preventDefaultOnPointerDown = true;
  20595. // Metadata
  20596. this.metadata = null;
  20597. /**
  20598. * An event triggered when the scene is disposed.
  20599. * @type {BABYLON.Observable}
  20600. */
  20601. this.onDisposeObservable = new BABYLON.Observable();
  20602. /**
  20603. * An event triggered before rendering the scene (right after animations and physics)
  20604. * @type {BABYLON.Observable}
  20605. */
  20606. this.onBeforeRenderObservable = new BABYLON.Observable();
  20607. /**
  20608. * An event triggered after rendering the scene
  20609. * @type {BABYLON.Observable}
  20610. */
  20611. this.onAfterRenderObservable = new BABYLON.Observable();
  20612. /**
  20613. * An event triggered before animating the scene
  20614. * @type {BABYLON.Observable}
  20615. */
  20616. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20617. /**
  20618. * An event triggered after animations processing
  20619. * @type {BABYLON.Observable}
  20620. */
  20621. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20622. /**
  20623. * An event triggered before draw calls are ready to be sent
  20624. * @type {BABYLON.Observable}
  20625. */
  20626. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20627. /**
  20628. * An event triggered after draw calls have been sent
  20629. * @type {BABYLON.Observable}
  20630. */
  20631. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20632. /**
  20633. * An event triggered when physic simulation is about to be run
  20634. * @type {BABYLON.Observable}
  20635. */
  20636. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20637. /**
  20638. * An event triggered when physic simulation has been done
  20639. * @type {BABYLON.Observable}
  20640. */
  20641. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20642. /**
  20643. * An event triggered when the scene is ready
  20644. * @type {BABYLON.Observable}
  20645. */
  20646. this.onReadyObservable = new BABYLON.Observable();
  20647. /**
  20648. * An event triggered before rendering a camera
  20649. * @type {BABYLON.Observable}
  20650. */
  20651. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20652. /**
  20653. * An event triggered after rendering a camera
  20654. * @type {BABYLON.Observable}
  20655. */
  20656. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20657. /**
  20658. * An event triggered when active meshes evaluation is about to start
  20659. * @type {BABYLON.Observable}
  20660. */
  20661. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20662. /**
  20663. * An event triggered when active meshes evaluation is done
  20664. * @type {BABYLON.Observable}
  20665. */
  20666. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20667. /**
  20668. * An event triggered when particles rendering is about to start
  20669. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20670. * @type {BABYLON.Observable}
  20671. */
  20672. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20673. /**
  20674. * An event triggered when particles rendering is done
  20675. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20676. * @type {BABYLON.Observable}
  20677. */
  20678. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20679. /**
  20680. * An event triggered when sprites rendering is about to start
  20681. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20682. * @type {BABYLON.Observable}
  20683. */
  20684. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20685. /**
  20686. * An event triggered when sprites rendering is done
  20687. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20688. * @type {BABYLON.Observable}
  20689. */
  20690. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20691. /**
  20692. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20693. * @type {BABYLON.Observable}
  20694. */
  20695. this.onDataLoadedObservable = new BABYLON.Observable();
  20696. /**
  20697. * An event triggered when a camera is created
  20698. * @type {BABYLON.Observable}
  20699. */
  20700. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20701. /**
  20702. * An event triggered when a camera is removed
  20703. * @type {BABYLON.Observable}
  20704. */
  20705. this.onCameraRemovedObservable = new BABYLON.Observable();
  20706. /**
  20707. * An event triggered when a light is created
  20708. * @type {BABYLON.Observable}
  20709. */
  20710. this.onNewLightAddedObservable = new BABYLON.Observable();
  20711. /**
  20712. * An event triggered when a light is removed
  20713. * @type {BABYLON.Observable}
  20714. */
  20715. this.onLightRemovedObservable = new BABYLON.Observable();
  20716. /**
  20717. * An event triggered when a geometry is created
  20718. * @type {BABYLON.Observable}
  20719. */
  20720. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20721. /**
  20722. * An event triggered when a geometry is removed
  20723. * @type {BABYLON.Observable}
  20724. */
  20725. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20726. /**
  20727. * An event triggered when a transform node is created
  20728. * @type {BABYLON.Observable}
  20729. */
  20730. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20731. /**
  20732. * An event triggered when a transform node is removed
  20733. * @type {BABYLON.Observable}
  20734. */
  20735. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20736. /**
  20737. * An event triggered when a mesh is created
  20738. * @type {BABYLON.Observable}
  20739. */
  20740. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20741. /**
  20742. * An event triggered when a mesh is removed
  20743. * @type {BABYLON.Observable}
  20744. */
  20745. this.onMeshRemovedObservable = new BABYLON.Observable();
  20746. /**
  20747. * An event triggered when render targets are about to be rendered
  20748. * Can happen multiple times per frame.
  20749. * @type {BABYLON.Observable}
  20750. */
  20751. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20752. /**
  20753. * An event triggered when render targets were rendered.
  20754. * Can happen multiple times per frame.
  20755. * @type {BABYLON.Observable}
  20756. */
  20757. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20758. /**
  20759. * An event triggered before calculating deterministic simulation step
  20760. * @type {BABYLON.Observable}
  20761. */
  20762. this.onBeforeStepObservable = new BABYLON.Observable();
  20763. /**
  20764. * An event triggered after calculating deterministic simulation step
  20765. * @type {BABYLON.Observable}
  20766. */
  20767. this.onAfterStepObservable = new BABYLON.Observable();
  20768. /**
  20769. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20770. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20771. * 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)
  20772. */
  20773. this.onRenderingGroupObservable = new BABYLON.Observable();
  20774. // Animations
  20775. this.animations = [];
  20776. /**
  20777. * 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).
  20778. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20779. */
  20780. this.onPrePointerObservable = new BABYLON.Observable();
  20781. /**
  20782. * Observable event triggered each time an input event is received from the rendering canvas
  20783. */
  20784. this.onPointerObservable = new BABYLON.Observable();
  20785. this._meshPickProceed = false;
  20786. this._currentPickResult = null;
  20787. this._previousPickResult = null;
  20788. this._totalPointersPressed = 0;
  20789. this._doubleClickOccured = false;
  20790. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20791. this.cameraToUseForPointers = null;
  20792. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20793. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20794. this._startingPointerTime = 0;
  20795. this._previousStartingPointerTime = 0;
  20796. // Deterministic lockstep
  20797. this._timeAccumulator = 0;
  20798. this._currentStepId = 0;
  20799. this._currentInternalStep = 0;
  20800. // Keyboard
  20801. /**
  20802. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20803. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20804. */
  20805. this.onPreKeyboardObservable = new BABYLON.Observable();
  20806. /**
  20807. * Observable event triggered each time an keyboard event is received from the hosting window
  20808. */
  20809. this.onKeyboardObservable = new BABYLON.Observable();
  20810. // Coordinate system
  20811. /**
  20812. * use right-handed coordinate system on this scene.
  20813. * @type {boolean}
  20814. */
  20815. this._useRightHandedSystem = false;
  20816. // Fog
  20817. this._fogEnabled = true;
  20818. this._fogMode = Scene.FOGMODE_NONE;
  20819. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20820. this.fogDensity = 0.1;
  20821. this.fogStart = 0;
  20822. this.fogEnd = 1000.0;
  20823. // Lights
  20824. /**
  20825. * is shadow enabled on this scene.
  20826. * @type {boolean}
  20827. */
  20828. this._shadowsEnabled = true;
  20829. /**
  20830. * is light enabled on this scene.
  20831. * @type {boolean}
  20832. */
  20833. this._lightsEnabled = true;
  20834. /**
  20835. * All of the lights added to this scene.
  20836. * @see BABYLON.Light
  20837. * @type {BABYLON.Light[]}
  20838. */
  20839. this.lights = new Array();
  20840. // Cameras
  20841. /** All of the cameras added to this scene. */
  20842. this.cameras = new Array();
  20843. /** All of the active cameras added to this scene. */
  20844. this.activeCameras = new Array();
  20845. // Meshes
  20846. /**
  20847. * All of the tranform nodes added to this scene.
  20848. * @see BABYLON.TransformNode
  20849. * @type {BABYLON.TransformNode[]}
  20850. */
  20851. this.transformNodes = new Array();
  20852. /**
  20853. * All of the (abstract) meshes added to this scene.
  20854. * @see BABYLON.AbstractMesh
  20855. * @type {BABYLON.AbstractMesh[]}
  20856. */
  20857. this.meshes = new Array();
  20858. /**
  20859. * All of the animation groups added to this scene.
  20860. * @see BABYLON.AnimationGroup
  20861. * @type {BABYLON.AnimationGroup[]}
  20862. */
  20863. this.animationGroups = new Array();
  20864. // Geometries
  20865. this._geometries = new Array();
  20866. this.materials = new Array();
  20867. this.multiMaterials = new Array();
  20868. // Textures
  20869. this._texturesEnabled = true;
  20870. this.textures = new Array();
  20871. // Particles
  20872. this.particlesEnabled = true;
  20873. this.particleSystems = new Array();
  20874. // Sprites
  20875. this.spritesEnabled = true;
  20876. this.spriteManagers = new Array();
  20877. // Layers
  20878. this.layers = new Array();
  20879. this.highlightLayers = new Array();
  20880. // Skeletons
  20881. this._skeletonsEnabled = true;
  20882. this.skeletons = new Array();
  20883. // Morph targets
  20884. this.morphTargetManagers = new Array();
  20885. // Lens flares
  20886. this.lensFlaresEnabled = true;
  20887. this.lensFlareSystems = new Array();
  20888. // Collisions
  20889. this.collisionsEnabled = true;
  20890. /** Defines the gravity applied to this scene */
  20891. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20892. // Postprocesses
  20893. this.postProcesses = new Array();
  20894. this.postProcessesEnabled = true;
  20895. // Customs render targets
  20896. this.renderTargetsEnabled = true;
  20897. this.dumpNextRenderTargets = false;
  20898. this.customRenderTargets = new Array();
  20899. // Imported meshes
  20900. this.importedMeshesFiles = new Array();
  20901. // Probes
  20902. this.probesEnabled = true;
  20903. this.reflectionProbes = new Array();
  20904. this._actionManagers = new Array();
  20905. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20906. // Procedural textures
  20907. this.proceduralTexturesEnabled = true;
  20908. this._proceduralTextures = new Array();
  20909. this.soundTracks = new Array();
  20910. this._audioEnabled = true;
  20911. this._headphone = false;
  20912. // Performance counters
  20913. this._totalVertices = new BABYLON.PerfCounter();
  20914. this._activeIndices = new BABYLON.PerfCounter();
  20915. this._activeParticles = new BABYLON.PerfCounter();
  20916. this._activeBones = new BABYLON.PerfCounter();
  20917. this._animationTime = 0;
  20918. this.animationTimeScale = 1;
  20919. this._renderId = 0;
  20920. this._executeWhenReadyTimeoutId = -1;
  20921. this._intermediateRendering = false;
  20922. this._viewUpdateFlag = -1;
  20923. this._projectionUpdateFlag = -1;
  20924. this._alternateViewUpdateFlag = -1;
  20925. this._alternateProjectionUpdateFlag = -1;
  20926. this._toBeDisposed = new BABYLON.SmartArray(256);
  20927. this._activeRequests = new Array();
  20928. this._pendingData = new Array();
  20929. this._isDisposed = false;
  20930. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20931. this._activeMeshes = new BABYLON.SmartArray(256);
  20932. this._processedMaterials = new BABYLON.SmartArray(256);
  20933. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20934. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20935. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20936. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20937. this._activeAnimatables = new Array();
  20938. this._transformMatrix = BABYLON.Matrix.Zero();
  20939. this._useAlternateCameraConfiguration = false;
  20940. this._alternateRendering = false;
  20941. this.requireLightSorting = false;
  20942. this._activeMeshesFrozen = false;
  20943. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20944. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20945. this._engine.scenes.push(this);
  20946. this._uid = null;
  20947. this._renderingManager = new BABYLON.RenderingManager(this);
  20948. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20949. if (BABYLON.OutlineRenderer) {
  20950. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20951. }
  20952. if (BABYLON.Tools.IsWindowObjectExist()) {
  20953. this.attachControl();
  20954. }
  20955. //simplification queue
  20956. if (BABYLON.SimplificationQueue) {
  20957. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20958. }
  20959. //collision coordinator initialization. For now legacy per default.
  20960. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20961. // Uniform Buffer
  20962. this._createUbo();
  20963. // Default Image processing definition.
  20964. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20965. }
  20966. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20967. /** The fog is deactivated */
  20968. get: function () {
  20969. return Scene._FOGMODE_NONE;
  20970. },
  20971. enumerable: true,
  20972. configurable: true
  20973. });
  20974. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20975. /** The fog density is following an exponential function */
  20976. get: function () {
  20977. return Scene._FOGMODE_EXP;
  20978. },
  20979. enumerable: true,
  20980. configurable: true
  20981. });
  20982. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20983. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20984. get: function () {
  20985. return Scene._FOGMODE_EXP2;
  20986. },
  20987. enumerable: true,
  20988. configurable: true
  20989. });
  20990. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20991. /** The fog density is following a linear function. */
  20992. get: function () {
  20993. return Scene._FOGMODE_LINEAR;
  20994. },
  20995. enumerable: true,
  20996. configurable: true
  20997. });
  20998. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20999. /**
  21000. * Texture used in all pbr material as the reflection texture.
  21001. * As in the majority of the scene they are the same (exception for multi room and so on),
  21002. * this is easier to reference from here than from all the materials.
  21003. */
  21004. get: function () {
  21005. return this._environmentTexture;
  21006. },
  21007. /**
  21008. * Texture used in all pbr material as the reflection texture.
  21009. * As in the majority of the scene they are the same (exception for multi room and so on),
  21010. * this is easier to set here than in all the materials.
  21011. */
  21012. set: function (value) {
  21013. if (this._environmentTexture === value) {
  21014. return;
  21015. }
  21016. this._environmentTexture = value;
  21017. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21018. },
  21019. enumerable: true,
  21020. configurable: true
  21021. });
  21022. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21023. /**
  21024. * Default image processing configuration used either in the rendering
  21025. * Forward main pass or through the imageProcessingPostProcess if present.
  21026. * As in the majority of the scene they are the same (exception for multi camera),
  21027. * this is easier to reference from here than from all the materials and post process.
  21028. *
  21029. * No setter as we it is a shared configuration, you can set the values instead.
  21030. */
  21031. get: function () {
  21032. return this._imageProcessingConfiguration;
  21033. },
  21034. enumerable: true,
  21035. configurable: true
  21036. });
  21037. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21038. get: function () {
  21039. return this._forcePointsCloud;
  21040. },
  21041. set: function (value) {
  21042. if (this._forcePointsCloud === value) {
  21043. return;
  21044. }
  21045. this._forcePointsCloud = value;
  21046. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21047. },
  21048. enumerable: true,
  21049. configurable: true
  21050. });
  21051. Object.defineProperty(Scene.prototype, "onDispose", {
  21052. /** A function to be executed when this scene is disposed. */
  21053. set: function (callback) {
  21054. if (this._onDisposeObserver) {
  21055. this.onDisposeObservable.remove(this._onDisposeObserver);
  21056. }
  21057. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21058. },
  21059. enumerable: true,
  21060. configurable: true
  21061. });
  21062. Object.defineProperty(Scene.prototype, "beforeRender", {
  21063. /** A function to be executed before rendering this scene */
  21064. set: function (callback) {
  21065. if (this._onBeforeRenderObserver) {
  21066. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21067. }
  21068. if (callback) {
  21069. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21070. }
  21071. },
  21072. enumerable: true,
  21073. configurable: true
  21074. });
  21075. Object.defineProperty(Scene.prototype, "afterRender", {
  21076. /** A function to be executed after rendering this scene */
  21077. set: function (callback) {
  21078. if (this._onAfterRenderObserver) {
  21079. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21080. }
  21081. if (callback) {
  21082. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21083. }
  21084. },
  21085. enumerable: true,
  21086. configurable: true
  21087. });
  21088. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21089. set: function (callback) {
  21090. if (this._onBeforeCameraRenderObserver) {
  21091. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21092. }
  21093. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21094. },
  21095. enumerable: true,
  21096. configurable: true
  21097. });
  21098. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21099. set: function (callback) {
  21100. if (this._onAfterCameraRenderObserver) {
  21101. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21102. }
  21103. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21104. },
  21105. enumerable: true,
  21106. configurable: true
  21107. });
  21108. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21109. get: function () {
  21110. if (!this._gamepadManager) {
  21111. this._gamepadManager = new BABYLON.GamepadManager(this);
  21112. }
  21113. return this._gamepadManager;
  21114. },
  21115. enumerable: true,
  21116. configurable: true
  21117. });
  21118. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21119. get: function () {
  21120. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21121. },
  21122. enumerable: true,
  21123. configurable: true
  21124. });
  21125. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21126. get: function () {
  21127. return this._useRightHandedSystem;
  21128. },
  21129. set: function (value) {
  21130. if (this._useRightHandedSystem === value) {
  21131. return;
  21132. }
  21133. this._useRightHandedSystem = value;
  21134. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21135. },
  21136. enumerable: true,
  21137. configurable: true
  21138. });
  21139. Scene.prototype.setStepId = function (newStepId) {
  21140. this._currentStepId = newStepId;
  21141. };
  21142. ;
  21143. Scene.prototype.getStepId = function () {
  21144. return this._currentStepId;
  21145. };
  21146. ;
  21147. Scene.prototype.getInternalStep = function () {
  21148. return this._currentInternalStep;
  21149. };
  21150. ;
  21151. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21152. get: function () {
  21153. return this._fogEnabled;
  21154. },
  21155. /**
  21156. * is fog enabled on this scene.
  21157. */
  21158. set: function (value) {
  21159. if (this._fogEnabled === value) {
  21160. return;
  21161. }
  21162. this._fogEnabled = value;
  21163. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21164. },
  21165. enumerable: true,
  21166. configurable: true
  21167. });
  21168. Object.defineProperty(Scene.prototype, "fogMode", {
  21169. get: function () {
  21170. return this._fogMode;
  21171. },
  21172. set: function (value) {
  21173. if (this._fogMode === value) {
  21174. return;
  21175. }
  21176. this._fogMode = value;
  21177. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21178. },
  21179. enumerable: true,
  21180. configurable: true
  21181. });
  21182. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21183. get: function () {
  21184. return this._shadowsEnabled;
  21185. },
  21186. set: function (value) {
  21187. if (this._shadowsEnabled === value) {
  21188. return;
  21189. }
  21190. this._shadowsEnabled = value;
  21191. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21192. },
  21193. enumerable: true,
  21194. configurable: true
  21195. });
  21196. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21197. get: function () {
  21198. return this._lightsEnabled;
  21199. },
  21200. set: function (value) {
  21201. if (this._lightsEnabled === value) {
  21202. return;
  21203. }
  21204. this._lightsEnabled = value;
  21205. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21206. },
  21207. enumerable: true,
  21208. configurable: true
  21209. });
  21210. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21211. /** The default material used on meshes when no material is affected */
  21212. get: function () {
  21213. if (!this._defaultMaterial) {
  21214. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21215. }
  21216. return this._defaultMaterial;
  21217. },
  21218. /** The default material used on meshes when no material is affected */
  21219. set: function (value) {
  21220. this._defaultMaterial = value;
  21221. },
  21222. enumerable: true,
  21223. configurable: true
  21224. });
  21225. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21226. get: function () {
  21227. return this._texturesEnabled;
  21228. },
  21229. set: function (value) {
  21230. if (this._texturesEnabled === value) {
  21231. return;
  21232. }
  21233. this._texturesEnabled = value;
  21234. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21235. },
  21236. enumerable: true,
  21237. configurable: true
  21238. });
  21239. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21240. get: function () {
  21241. return this._skeletonsEnabled;
  21242. },
  21243. set: function (value) {
  21244. if (this._skeletonsEnabled === value) {
  21245. return;
  21246. }
  21247. this._skeletonsEnabled = value;
  21248. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21249. },
  21250. enumerable: true,
  21251. configurable: true
  21252. });
  21253. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21254. get: function () {
  21255. if (!this._postProcessRenderPipelineManager) {
  21256. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21257. }
  21258. return this._postProcessRenderPipelineManager;
  21259. },
  21260. enumerable: true,
  21261. configurable: true
  21262. });
  21263. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21264. get: function () {
  21265. if (!this._mainSoundTrack) {
  21266. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21267. }
  21268. return this._mainSoundTrack;
  21269. },
  21270. enumerable: true,
  21271. configurable: true
  21272. });
  21273. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21274. get: function () {
  21275. return this._alternateRendering;
  21276. },
  21277. enumerable: true,
  21278. configurable: true
  21279. });
  21280. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21281. get: function () {
  21282. return this._frustumPlanes;
  21283. },
  21284. enumerable: true,
  21285. configurable: true
  21286. });
  21287. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21288. /**
  21289. * Gets the current geometry buffer associated to the scene.
  21290. */
  21291. get: function () {
  21292. return this._geometryBufferRenderer;
  21293. },
  21294. /**
  21295. * Sets the current geometry buffer for the scene.
  21296. */
  21297. set: function (geometryBufferRenderer) {
  21298. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21299. this._geometryBufferRenderer = geometryBufferRenderer;
  21300. }
  21301. },
  21302. enumerable: true,
  21303. configurable: true
  21304. });
  21305. Object.defineProperty(Scene.prototype, "debugLayer", {
  21306. // Properties
  21307. get: function () {
  21308. if (!this._debugLayer) {
  21309. this._debugLayer = new BABYLON.DebugLayer(this);
  21310. }
  21311. return this._debugLayer;
  21312. },
  21313. enumerable: true,
  21314. configurable: true
  21315. });
  21316. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21317. get: function () {
  21318. return this._workerCollisions;
  21319. },
  21320. set: function (enabled) {
  21321. if (!BABYLON.CollisionCoordinatorLegacy) {
  21322. return;
  21323. }
  21324. enabled = (enabled && !!Worker);
  21325. this._workerCollisions = enabled;
  21326. if (this.collisionCoordinator) {
  21327. this.collisionCoordinator.destroy();
  21328. }
  21329. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21330. this.collisionCoordinator.init(this);
  21331. },
  21332. enumerable: true,
  21333. configurable: true
  21334. });
  21335. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21336. get: function () {
  21337. return this._selectionOctree;
  21338. },
  21339. enumerable: true,
  21340. configurable: true
  21341. });
  21342. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21343. /**
  21344. * The mesh that is currently under the pointer.
  21345. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21346. */
  21347. get: function () {
  21348. return this._pointerOverMesh;
  21349. },
  21350. enumerable: true,
  21351. configurable: true
  21352. });
  21353. Object.defineProperty(Scene.prototype, "pointerX", {
  21354. /**
  21355. * Current on-screen X position of the pointer
  21356. * @return {number} X position of the pointer
  21357. */
  21358. get: function () {
  21359. return this._pointerX;
  21360. },
  21361. enumerable: true,
  21362. configurable: true
  21363. });
  21364. Object.defineProperty(Scene.prototype, "pointerY", {
  21365. /**
  21366. * Current on-screen Y position of the pointer
  21367. * @return {number} Y position of the pointer
  21368. */
  21369. get: function () {
  21370. return this._pointerY;
  21371. },
  21372. enumerable: true,
  21373. configurable: true
  21374. });
  21375. Scene.prototype.getCachedMaterial = function () {
  21376. return this._cachedMaterial;
  21377. };
  21378. Scene.prototype.getCachedEffect = function () {
  21379. return this._cachedEffect;
  21380. };
  21381. Scene.prototype.getCachedVisibility = function () {
  21382. return this._cachedVisibility;
  21383. };
  21384. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21385. if (visibility === void 0) { visibility = 1; }
  21386. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21387. };
  21388. Scene.prototype.getBoundingBoxRenderer = function () {
  21389. if (!this._boundingBoxRenderer) {
  21390. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21391. }
  21392. return this._boundingBoxRenderer;
  21393. };
  21394. Scene.prototype.getOutlineRenderer = function () {
  21395. return this._outlineRenderer;
  21396. };
  21397. Scene.prototype.getEngine = function () {
  21398. return this._engine;
  21399. };
  21400. Scene.prototype.getTotalVertices = function () {
  21401. return this._totalVertices.current;
  21402. };
  21403. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21404. get: function () {
  21405. return this._totalVertices;
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Scene.prototype.getActiveIndices = function () {
  21411. return this._activeIndices.current;
  21412. };
  21413. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21414. get: function () {
  21415. return this._activeIndices;
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. Scene.prototype.getActiveParticles = function () {
  21421. return this._activeParticles.current;
  21422. };
  21423. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21424. get: function () {
  21425. return this._activeParticles;
  21426. },
  21427. enumerable: true,
  21428. configurable: true
  21429. });
  21430. Scene.prototype.getActiveBones = function () {
  21431. return this._activeBones.current;
  21432. };
  21433. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21434. get: function () {
  21435. return this._activeBones;
  21436. },
  21437. enumerable: true,
  21438. configurable: true
  21439. });
  21440. // Stats
  21441. Scene.prototype.getInterFramePerfCounter = function () {
  21442. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21443. return 0;
  21444. };
  21445. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21446. get: function () {
  21447. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21448. return null;
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. Scene.prototype.getLastFrameDuration = function () {
  21454. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21455. return 0;
  21456. };
  21457. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21458. get: function () {
  21459. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21460. return null;
  21461. },
  21462. enumerable: true,
  21463. configurable: true
  21464. });
  21465. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21466. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21467. return 0;
  21468. };
  21469. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21470. get: function () {
  21471. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21472. return null;
  21473. },
  21474. enumerable: true,
  21475. configurable: true
  21476. });
  21477. Scene.prototype.getActiveMeshes = function () {
  21478. return this._activeMeshes;
  21479. };
  21480. Scene.prototype.getRenderTargetsDuration = function () {
  21481. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21482. return 0;
  21483. };
  21484. Scene.prototype.getRenderDuration = function () {
  21485. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21486. return 0;
  21487. };
  21488. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21489. get: function () {
  21490. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21491. return null;
  21492. },
  21493. enumerable: true,
  21494. configurable: true
  21495. });
  21496. Scene.prototype.getParticlesDuration = function () {
  21497. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21498. return 0;
  21499. };
  21500. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21501. get: function () {
  21502. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21503. return null;
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Scene.prototype.getSpritesDuration = function () {
  21509. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21510. return 0;
  21511. };
  21512. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21513. get: function () {
  21514. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21515. return null;
  21516. },
  21517. enumerable: true,
  21518. configurable: true
  21519. });
  21520. Scene.prototype.getAnimationRatio = function () {
  21521. return this._animationRatio;
  21522. };
  21523. Scene.prototype.getRenderId = function () {
  21524. return this._renderId;
  21525. };
  21526. Scene.prototype.incrementRenderId = function () {
  21527. this._renderId++;
  21528. };
  21529. Scene.prototype._updatePointerPosition = function (evt) {
  21530. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21531. if (!canvasRect) {
  21532. return;
  21533. }
  21534. this._pointerX = evt.clientX - canvasRect.left;
  21535. this._pointerY = evt.clientY - canvasRect.top;
  21536. this._unTranslatedPointerX = this._pointerX;
  21537. this._unTranslatedPointerY = this._pointerY;
  21538. };
  21539. Scene.prototype._createUbo = function () {
  21540. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21541. this._sceneUbo.addUniform("viewProjection", 16);
  21542. this._sceneUbo.addUniform("view", 16);
  21543. };
  21544. Scene.prototype._createAlternateUbo = function () {
  21545. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21546. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21547. this._alternateSceneUbo.addUniform("view", 16);
  21548. };
  21549. // Pointers handling
  21550. /**
  21551. * Use this method to simulate a pointer move on a mesh
  21552. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21553. */
  21554. Scene.prototype.simulatePointerMove = function (pickResult) {
  21555. var evt = new PointerEvent("pointermove");
  21556. return this._processPointerMove(pickResult, evt);
  21557. };
  21558. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21559. var canvas = this._engine.getRenderingCanvas();
  21560. if (!canvas) {
  21561. return this;
  21562. }
  21563. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21564. this.setPointerOverSprite(null);
  21565. this.setPointerOverMesh(pickResult.pickedMesh);
  21566. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21567. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21568. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21569. }
  21570. else {
  21571. canvas.style.cursor = this.hoverCursor;
  21572. }
  21573. }
  21574. else {
  21575. canvas.style.cursor = this.defaultCursor;
  21576. }
  21577. }
  21578. else {
  21579. this.setPointerOverMesh(null);
  21580. // Sprites
  21581. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21582. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21583. this.setPointerOverSprite(pickResult.pickedSprite);
  21584. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21585. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21586. }
  21587. else {
  21588. canvas.style.cursor = this.hoverCursor;
  21589. }
  21590. }
  21591. else {
  21592. this.setPointerOverSprite(null);
  21593. // Restore pointer
  21594. canvas.style.cursor = this.defaultCursor;
  21595. }
  21596. }
  21597. if (pickResult) {
  21598. if (this.onPointerMove) {
  21599. this.onPointerMove(evt, pickResult);
  21600. }
  21601. if (this.onPointerObservable.hasObservers()) {
  21602. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21603. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21604. this.onPointerObservable.notifyObservers(pi, type);
  21605. }
  21606. }
  21607. return this;
  21608. };
  21609. /**
  21610. * Use this method to simulate a pointer down on a mesh
  21611. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21612. */
  21613. Scene.prototype.simulatePointerDown = function (pickResult) {
  21614. var evt = new PointerEvent("pointerdown");
  21615. return this._processPointerDown(pickResult, evt);
  21616. };
  21617. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21618. var _this = this;
  21619. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21620. this._pickedDownMesh = pickResult.pickedMesh;
  21621. var actionManager = pickResult.pickedMesh.actionManager;
  21622. if (actionManager) {
  21623. if (actionManager.hasPickTriggers) {
  21624. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21625. switch (evt.button) {
  21626. case 0:
  21627. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21628. break;
  21629. case 1:
  21630. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21631. break;
  21632. case 2:
  21633. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21634. break;
  21635. }
  21636. }
  21637. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21638. window.setTimeout(function () {
  21639. 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);
  21640. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21641. if (_this._totalPointersPressed !== 0 &&
  21642. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21643. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21644. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21645. _this._startingPointerTime = 0;
  21646. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21647. }
  21648. }
  21649. }, Scene.LongPressDelay);
  21650. }
  21651. }
  21652. }
  21653. if (pickResult) {
  21654. if (this.onPointerDown) {
  21655. this.onPointerDown(evt, pickResult);
  21656. }
  21657. if (this.onPointerObservable.hasObservers()) {
  21658. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21659. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21660. this.onPointerObservable.notifyObservers(pi, type);
  21661. }
  21662. }
  21663. return this;
  21664. };
  21665. /**
  21666. * Use this method to simulate a pointer up on a mesh
  21667. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21668. */
  21669. Scene.prototype.simulatePointerUp = function (pickResult) {
  21670. var evt = new PointerEvent("pointerup");
  21671. var clickInfo = new ClickInfo();
  21672. clickInfo.singleClick = true;
  21673. clickInfo.ignore = true;
  21674. return this._processPointerUp(pickResult, evt, clickInfo);
  21675. };
  21676. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21677. if (pickResult && pickResult && pickResult.pickedMesh) {
  21678. this._pickedUpMesh = pickResult.pickedMesh;
  21679. if (this._pickedDownMesh === this._pickedUpMesh) {
  21680. if (this.onPointerPick) {
  21681. this.onPointerPick(evt, pickResult);
  21682. }
  21683. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21684. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21685. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21686. this.onPointerObservable.notifyObservers(pi, type);
  21687. }
  21688. }
  21689. if (pickResult.pickedMesh.actionManager) {
  21690. if (clickInfo.ignore) {
  21691. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21692. }
  21693. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21694. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21695. }
  21696. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21697. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21698. }
  21699. }
  21700. }
  21701. if (this._pickedDownMesh &&
  21702. this._pickedDownMesh.actionManager &&
  21703. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21704. this._pickedDownMesh !== this._pickedUpMesh) {
  21705. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21706. }
  21707. if (this.onPointerUp) {
  21708. this.onPointerUp(evt, pickResult);
  21709. }
  21710. if (this.onPointerObservable.hasObservers()) {
  21711. if (!clickInfo.ignore) {
  21712. if (!clickInfo.hasSwiped) {
  21713. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21714. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21715. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21716. this.onPointerObservable.notifyObservers(pi, type);
  21717. }
  21718. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21719. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21720. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21721. this.onPointerObservable.notifyObservers(pi, type);
  21722. }
  21723. }
  21724. }
  21725. else {
  21726. var type = BABYLON.PointerEventTypes.POINTERUP;
  21727. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21728. this.onPointerObservable.notifyObservers(pi, type);
  21729. }
  21730. }
  21731. return this;
  21732. };
  21733. /**
  21734. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21735. * @param attachUp defines if you want to attach events to pointerup
  21736. * @param attachDown defines if you want to attach events to pointerdown
  21737. * @param attachMove defines if you want to attach events to pointermove
  21738. */
  21739. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21740. var _this = this;
  21741. if (attachUp === void 0) { attachUp = true; }
  21742. if (attachDown === void 0) { attachDown = true; }
  21743. if (attachMove === void 0) { attachMove = true; }
  21744. this._initActionManager = function (act, clickInfo) {
  21745. if (!_this._meshPickProceed) {
  21746. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21747. _this._currentPickResult = pickResult;
  21748. if (pickResult) {
  21749. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21750. }
  21751. _this._meshPickProceed = true;
  21752. }
  21753. return act;
  21754. };
  21755. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21756. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21757. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21758. btn !== _this._previousButtonPressed) {
  21759. _this._doubleClickOccured = false;
  21760. clickInfo.singleClick = true;
  21761. clickInfo.ignore = false;
  21762. cb(clickInfo, _this._currentPickResult);
  21763. }
  21764. };
  21765. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21766. var clickInfo = new ClickInfo();
  21767. _this._currentPickResult = null;
  21768. var act = null;
  21769. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21770. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21771. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21772. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21773. act = _this._initActionManager(act, clickInfo);
  21774. if (act)
  21775. checkPicking = act.hasPickTriggers;
  21776. }
  21777. if (checkPicking) {
  21778. var btn = evt.button;
  21779. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21780. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21781. if (!clickInfo.hasSwiped) {
  21782. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21783. if (!checkSingleClickImmediately) {
  21784. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21785. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21786. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21787. act = _this._initActionManager(act, clickInfo);
  21788. if (act)
  21789. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21790. }
  21791. }
  21792. if (checkSingleClickImmediately) {
  21793. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21794. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21795. btn !== _this._previousButtonPressed) {
  21796. clickInfo.singleClick = true;
  21797. cb(clickInfo, _this._currentPickResult);
  21798. }
  21799. }
  21800. else {
  21801. // wait that no double click has been raised during the double click delay
  21802. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21803. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21804. }
  21805. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21806. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21807. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21808. act = _this._initActionManager(act, clickInfo);
  21809. if (act)
  21810. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21811. }
  21812. if (checkDoubleClick) {
  21813. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21814. if (btn === _this._previousButtonPressed &&
  21815. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21816. !_this._doubleClickOccured) {
  21817. // pointer has not moved for 2 clicks, it's a double click
  21818. if (!clickInfo.hasSwiped &&
  21819. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21820. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21821. _this._previousStartingPointerTime = 0;
  21822. _this._doubleClickOccured = true;
  21823. clickInfo.doubleClick = true;
  21824. clickInfo.ignore = false;
  21825. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21826. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21827. }
  21828. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21829. cb(clickInfo, _this._currentPickResult);
  21830. }
  21831. else {
  21832. _this._doubleClickOccured = false;
  21833. _this._previousStartingPointerTime = _this._startingPointerTime;
  21834. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21835. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21836. _this._previousButtonPressed = btn;
  21837. if (Scene.ExclusiveDoubleClickMode) {
  21838. if (_this._previousDelayedSimpleClickTimeout) {
  21839. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21840. }
  21841. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21842. cb(clickInfo, _this._previousPickResult);
  21843. }
  21844. else {
  21845. cb(clickInfo, _this._currentPickResult);
  21846. }
  21847. }
  21848. }
  21849. else {
  21850. _this._doubleClickOccured = false;
  21851. _this._previousStartingPointerTime = _this._startingPointerTime;
  21852. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21853. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21854. _this._previousButtonPressed = btn;
  21855. }
  21856. }
  21857. }
  21858. }
  21859. clickInfo.ignore = true;
  21860. cb(clickInfo, _this._currentPickResult);
  21861. };
  21862. this._spritePredicate = function (sprite) {
  21863. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21864. };
  21865. this._onPointerMove = function (evt) {
  21866. _this._updatePointerPosition(evt);
  21867. // PreObservable support
  21868. if (_this.onPrePointerObservable.hasObservers()) {
  21869. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21870. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21871. _this.onPrePointerObservable.notifyObservers(pi, type);
  21872. if (pi.skipOnPointerObservable) {
  21873. return;
  21874. }
  21875. }
  21876. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21877. return;
  21878. }
  21879. if (!_this.pointerMovePredicate) {
  21880. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21881. }
  21882. // Meshes
  21883. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21884. _this._processPointerMove(pickResult, evt);
  21885. };
  21886. this._onPointerDown = function (evt) {
  21887. _this._totalPointersPressed++;
  21888. _this._pickedDownMesh = null;
  21889. _this._meshPickProceed = false;
  21890. _this._updatePointerPosition(evt);
  21891. if (_this.preventDefaultOnPointerDown && canvas) {
  21892. evt.preventDefault();
  21893. canvas.focus();
  21894. }
  21895. // PreObservable support
  21896. if (_this.onPrePointerObservable.hasObservers()) {
  21897. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21898. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21899. _this.onPrePointerObservable.notifyObservers(pi, type);
  21900. if (pi.skipOnPointerObservable) {
  21901. return;
  21902. }
  21903. }
  21904. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21905. return;
  21906. }
  21907. _this._startingPointerPosition.x = _this._pointerX;
  21908. _this._startingPointerPosition.y = _this._pointerY;
  21909. _this._startingPointerTime = new Date().getTime();
  21910. if (!_this.pointerDownPredicate) {
  21911. _this.pointerDownPredicate = function (mesh) {
  21912. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21913. };
  21914. }
  21915. // Meshes
  21916. _this._pickedDownMesh = null;
  21917. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21918. _this._processPointerDown(pickResult, evt);
  21919. // Sprites
  21920. _this._pickedDownSprite = null;
  21921. if (_this.spriteManagers.length > 0) {
  21922. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21923. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21924. if (pickResult.pickedSprite.actionManager) {
  21925. _this._pickedDownSprite = pickResult.pickedSprite;
  21926. switch (evt.button) {
  21927. case 0:
  21928. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21929. break;
  21930. case 1:
  21931. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21932. break;
  21933. case 2:
  21934. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21935. break;
  21936. }
  21937. if (pickResult.pickedSprite.actionManager) {
  21938. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21939. }
  21940. }
  21941. }
  21942. }
  21943. };
  21944. this._onPointerUp = function (evt) {
  21945. if (_this._totalPointersPressed === 0) {
  21946. return; // So we need to test it the pointer down was pressed before.
  21947. }
  21948. _this._totalPointersPressed--;
  21949. _this._pickedUpMesh = null;
  21950. _this._meshPickProceed = false;
  21951. _this._updatePointerPosition(evt);
  21952. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21953. // PreObservable support
  21954. if (_this.onPrePointerObservable.hasObservers()) {
  21955. if (!clickInfo.ignore) {
  21956. if (!clickInfo.hasSwiped) {
  21957. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21958. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21959. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21960. _this.onPrePointerObservable.notifyObservers(pi, type);
  21961. if (pi.skipOnPointerObservable) {
  21962. return;
  21963. }
  21964. }
  21965. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21966. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21967. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21968. _this.onPrePointerObservable.notifyObservers(pi, type);
  21969. if (pi.skipOnPointerObservable) {
  21970. return;
  21971. }
  21972. }
  21973. }
  21974. }
  21975. else {
  21976. var type = BABYLON.PointerEventTypes.POINTERUP;
  21977. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21978. _this.onPrePointerObservable.notifyObservers(pi, type);
  21979. if (pi.skipOnPointerObservable) {
  21980. return;
  21981. }
  21982. }
  21983. }
  21984. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21985. return;
  21986. }
  21987. if (!_this.pointerUpPredicate) {
  21988. _this.pointerUpPredicate = function (mesh) {
  21989. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21990. };
  21991. }
  21992. // Meshes
  21993. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21994. _this._initActionManager(null, clickInfo);
  21995. }
  21996. if (!pickResult) {
  21997. pickResult = _this._currentPickResult;
  21998. }
  21999. _this._processPointerUp(pickResult, evt, clickInfo);
  22000. // Sprites
  22001. if (_this.spriteManagers.length > 0) {
  22002. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22003. if (spritePickResult) {
  22004. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22005. if (spritePickResult.pickedSprite.actionManager) {
  22006. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22007. if (spritePickResult.pickedSprite.actionManager) {
  22008. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22009. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22010. }
  22011. }
  22012. }
  22013. }
  22014. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22015. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22016. }
  22017. }
  22018. }
  22019. _this._previousPickResult = _this._currentPickResult;
  22020. });
  22021. };
  22022. this._onKeyDown = function (evt) {
  22023. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22024. if (_this.onPreKeyboardObservable.hasObservers()) {
  22025. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22026. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22027. if (pi.skipOnPointerObservable) {
  22028. return;
  22029. }
  22030. }
  22031. if (_this.onKeyboardObservable.hasObservers()) {
  22032. var pi = new BABYLON.KeyboardInfo(type, evt);
  22033. _this.onKeyboardObservable.notifyObservers(pi, type);
  22034. }
  22035. if (_this.actionManager) {
  22036. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22037. }
  22038. };
  22039. this._onKeyUp = function (evt) {
  22040. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22041. if (_this.onPreKeyboardObservable.hasObservers()) {
  22042. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22043. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22044. if (pi.skipOnPointerObservable) {
  22045. return;
  22046. }
  22047. }
  22048. if (_this.onKeyboardObservable.hasObservers()) {
  22049. var pi = new BABYLON.KeyboardInfo(type, evt);
  22050. _this.onKeyboardObservable.notifyObservers(pi, type);
  22051. }
  22052. if (_this.actionManager) {
  22053. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22054. }
  22055. };
  22056. var engine = this.getEngine();
  22057. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22058. if (!canvas) {
  22059. return;
  22060. }
  22061. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22062. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22063. });
  22064. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22065. if (!canvas) {
  22066. return;
  22067. }
  22068. canvas.removeEventListener("keydown", _this._onKeyDown);
  22069. canvas.removeEventListener("keyup", _this._onKeyUp);
  22070. });
  22071. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22072. var canvas = this._engine.getRenderingCanvas();
  22073. if (!canvas) {
  22074. return;
  22075. }
  22076. if (attachMove) {
  22077. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22078. // Wheel
  22079. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22080. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22081. }
  22082. if (attachDown) {
  22083. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22084. }
  22085. if (attachUp) {
  22086. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22087. }
  22088. canvas.tabIndex = 1;
  22089. };
  22090. Scene.prototype.detachControl = function () {
  22091. var engine = this.getEngine();
  22092. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22093. var canvas = engine.getRenderingCanvas();
  22094. if (!canvas) {
  22095. return;
  22096. }
  22097. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22098. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22099. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22100. if (this._onCanvasBlurObserver) {
  22101. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22102. }
  22103. if (this._onCanvasFocusObserver) {
  22104. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22105. }
  22106. // Wheel
  22107. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22108. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22109. // Keyboard
  22110. canvas.removeEventListener("keydown", this._onKeyDown);
  22111. canvas.removeEventListener("keyup", this._onKeyUp);
  22112. // Observables
  22113. this.onKeyboardObservable.clear();
  22114. this.onPreKeyboardObservable.clear();
  22115. this.onPointerObservable.clear();
  22116. this.onPrePointerObservable.clear();
  22117. };
  22118. /**
  22119. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22120. * Delay loaded resources are not taking in account
  22121. * @return true if all required resources are ready
  22122. */
  22123. Scene.prototype.isReady = function () {
  22124. if (this._isDisposed) {
  22125. return false;
  22126. }
  22127. if (this._pendingData.length > 0) {
  22128. return false;
  22129. }
  22130. var index;
  22131. var engine = this.getEngine();
  22132. // Geometries
  22133. for (index = 0; index < this._geometries.length; index++) {
  22134. var geometry = this._geometries[index];
  22135. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22136. return false;
  22137. }
  22138. }
  22139. // Meshes
  22140. for (index = 0; index < this.meshes.length; index++) {
  22141. var mesh = this.meshes[index];
  22142. if (!mesh.isEnabled()) {
  22143. continue;
  22144. }
  22145. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22146. continue;
  22147. }
  22148. if (!mesh.isReady()) {
  22149. return false;
  22150. }
  22151. // Highlight layers
  22152. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22153. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  22154. var layer = _a[_i];
  22155. if (!layer.hasMesh(mesh)) {
  22156. continue;
  22157. }
  22158. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22159. var subMesh = _c[_b];
  22160. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22161. return false;
  22162. }
  22163. }
  22164. }
  22165. }
  22166. return true;
  22167. };
  22168. Scene.prototype.resetCachedMaterial = function () {
  22169. this._cachedMaterial = null;
  22170. this._cachedEffect = null;
  22171. this._cachedVisibility = null;
  22172. };
  22173. Scene.prototype.registerBeforeRender = function (func) {
  22174. this.onBeforeRenderObservable.add(func);
  22175. };
  22176. Scene.prototype.unregisterBeforeRender = function (func) {
  22177. this.onBeforeRenderObservable.removeCallback(func);
  22178. };
  22179. Scene.prototype.registerAfterRender = function (func) {
  22180. this.onAfterRenderObservable.add(func);
  22181. };
  22182. Scene.prototype.unregisterAfterRender = function (func) {
  22183. this.onAfterRenderObservable.removeCallback(func);
  22184. };
  22185. Scene.prototype._executeOnceBeforeRender = function (func) {
  22186. var _this = this;
  22187. var execFunc = function () {
  22188. func();
  22189. setTimeout(function () {
  22190. _this.unregisterBeforeRender(execFunc);
  22191. });
  22192. };
  22193. this.registerBeforeRender(execFunc);
  22194. };
  22195. /**
  22196. * The provided function will run before render once and will be disposed afterwards.
  22197. * A timeout delay can be provided so that the function will be executed in N ms.
  22198. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22199. * @param func The function to be executed.
  22200. * @param timeout optional delay in ms
  22201. */
  22202. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22203. var _this = this;
  22204. if (timeout !== undefined) {
  22205. setTimeout(function () {
  22206. _this._executeOnceBeforeRender(func);
  22207. }, timeout);
  22208. }
  22209. else {
  22210. this._executeOnceBeforeRender(func);
  22211. }
  22212. };
  22213. Scene.prototype._addPendingData = function (data) {
  22214. this._pendingData.push(data);
  22215. };
  22216. Scene.prototype._removePendingData = function (data) {
  22217. var wasLoading = this.isLoading;
  22218. var index = this._pendingData.indexOf(data);
  22219. if (index !== -1) {
  22220. this._pendingData.splice(index, 1);
  22221. }
  22222. if (wasLoading && !this.isLoading) {
  22223. this.onDataLoadedObservable.notifyObservers(this);
  22224. }
  22225. };
  22226. Scene.prototype.getWaitingItemsCount = function () {
  22227. return this._pendingData.length;
  22228. };
  22229. Object.defineProperty(Scene.prototype, "isLoading", {
  22230. get: function () {
  22231. return this._pendingData.length > 0;
  22232. },
  22233. enumerable: true,
  22234. configurable: true
  22235. });
  22236. /**
  22237. * Registers a function to be executed when the scene is ready.
  22238. * @param {Function} func - the function to be executed.
  22239. */
  22240. Scene.prototype.executeWhenReady = function (func) {
  22241. var _this = this;
  22242. this.onReadyObservable.add(func);
  22243. if (this._executeWhenReadyTimeoutId !== -1) {
  22244. return;
  22245. }
  22246. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22247. _this._checkIsReady();
  22248. }, 150);
  22249. };
  22250. Scene.prototype._checkIsReady = function () {
  22251. var _this = this;
  22252. if (this.isReady()) {
  22253. this.onReadyObservable.notifyObservers(this);
  22254. this.onReadyObservable.clear();
  22255. this._executeWhenReadyTimeoutId = -1;
  22256. return;
  22257. }
  22258. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22259. _this._checkIsReady();
  22260. }, 150);
  22261. };
  22262. // Animations
  22263. /**
  22264. * Will start the animation sequence of a given target
  22265. * @param target - the target
  22266. * @param {number} from - from which frame should animation start
  22267. * @param {number} to - till which frame should animation run.
  22268. * @param {boolean} [loop] - should the animation loop
  22269. * @param {number} [speedRatio] - the speed in which to run the animation
  22270. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22271. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22272. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22273. * See BABYLON.Animatable
  22274. */
  22275. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22276. if (speedRatio === void 0) { speedRatio = 1.0; }
  22277. if (from > to && speedRatio > 0) {
  22278. speedRatio *= -1;
  22279. }
  22280. this.stopAnimation(target);
  22281. if (!animatable) {
  22282. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22283. }
  22284. // Local animations
  22285. if (target.animations) {
  22286. animatable.appendAnimations(target, target.animations);
  22287. }
  22288. // Children animations
  22289. if (target.getAnimatables) {
  22290. var animatables = target.getAnimatables();
  22291. for (var index = 0; index < animatables.length; index++) {
  22292. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22293. }
  22294. }
  22295. animatable.reset();
  22296. return animatable;
  22297. };
  22298. /**
  22299. * Begin a new animation on a given node
  22300. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22301. * @param {BABYLON.Animation[]} defines the list of animations to start
  22302. * @param {number} from defines the initial value
  22303. * @param {number} to defines the final value
  22304. * @param {boolean} loop defines if you want animation to loop (off by default)
  22305. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22306. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22307. * @returns the list of created animatables
  22308. */
  22309. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22310. if (speedRatio === undefined) {
  22311. speedRatio = 1.0;
  22312. }
  22313. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22314. return animatable;
  22315. };
  22316. /**
  22317. * Begin a new animation on a given node and its hierarchy
  22318. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22319. * @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.
  22320. * @param {BABYLON.Animation[]} defines the list of animations to start
  22321. * @param {number} from defines the initial value
  22322. * @param {number} to defines the final value
  22323. * @param {boolean} loop defines if you want animation to loop (off by default)
  22324. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22325. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22326. * @returns the list of animatables created for all nodes
  22327. */
  22328. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22329. var children = target.getDescendants(directDescendantsOnly);
  22330. var result = [];
  22331. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22332. var child = children_1[_i];
  22333. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22334. }
  22335. return result;
  22336. };
  22337. Scene.prototype.getAnimatableByTarget = function (target) {
  22338. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22339. if (this._activeAnimatables[index].target === target) {
  22340. return this._activeAnimatables[index];
  22341. }
  22342. }
  22343. return null;
  22344. };
  22345. Object.defineProperty(Scene.prototype, "animatables", {
  22346. get: function () {
  22347. return this._activeAnimatables;
  22348. },
  22349. enumerable: true,
  22350. configurable: true
  22351. });
  22352. /**
  22353. * Will stop the animation of the given target
  22354. * @param target - the target
  22355. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22356. * @see beginAnimation
  22357. */
  22358. Scene.prototype.stopAnimation = function (target, animationName) {
  22359. var animatable = this.getAnimatableByTarget(target);
  22360. if (animatable) {
  22361. animatable.stop(animationName);
  22362. }
  22363. };
  22364. /**
  22365. * Stops and removes all animations that have been applied to the scene
  22366. */
  22367. Scene.prototype.stopAllAnimations = function () {
  22368. if (this._activeAnimatables) {
  22369. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22370. this._activeAnimatables[i].stop();
  22371. }
  22372. this._activeAnimatables = [];
  22373. }
  22374. };
  22375. Scene.prototype._animate = function () {
  22376. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22377. return;
  22378. }
  22379. // Getting time
  22380. var now = BABYLON.Tools.Now;
  22381. if (!this._animationTimeLast) {
  22382. if (this._pendingData.length > 0) {
  22383. return;
  22384. }
  22385. this._animationTimeLast = now;
  22386. }
  22387. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22388. this._animationTime += deltaTime;
  22389. this._animationTimeLast = now;
  22390. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22391. this._activeAnimatables[index]._animate(this._animationTime);
  22392. }
  22393. };
  22394. // Matrix
  22395. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22396. this._useAlternateCameraConfiguration = active;
  22397. };
  22398. Scene.prototype.getViewMatrix = function () {
  22399. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22400. };
  22401. Scene.prototype.getProjectionMatrix = function () {
  22402. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22403. };
  22404. Scene.prototype.getTransformMatrix = function () {
  22405. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22406. };
  22407. Scene.prototype.setTransformMatrix = function (view, projection) {
  22408. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22409. return;
  22410. }
  22411. this._viewUpdateFlag = view.updateFlag;
  22412. this._projectionUpdateFlag = projection.updateFlag;
  22413. this._viewMatrix = view;
  22414. this._projectionMatrix = projection;
  22415. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22416. // Update frustum
  22417. if (!this._frustumPlanes) {
  22418. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22419. }
  22420. else {
  22421. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22422. }
  22423. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22424. var otherCamera = this.activeCamera._alternateCamera;
  22425. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22426. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22427. }
  22428. if (this._sceneUbo.useUbo) {
  22429. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22430. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22431. this._sceneUbo.update();
  22432. }
  22433. };
  22434. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22435. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22436. return;
  22437. }
  22438. this._alternateViewUpdateFlag = view.updateFlag;
  22439. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22440. this._alternateViewMatrix = view;
  22441. this._alternateProjectionMatrix = projection;
  22442. if (!this._alternateTransformMatrix) {
  22443. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22444. }
  22445. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22446. if (!this._alternateSceneUbo) {
  22447. this._createAlternateUbo();
  22448. }
  22449. if (this._alternateSceneUbo.useUbo) {
  22450. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22451. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22452. this._alternateSceneUbo.update();
  22453. }
  22454. };
  22455. Scene.prototype.getSceneUniformBuffer = function () {
  22456. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22457. };
  22458. // Methods
  22459. Scene.prototype.getUniqueId = function () {
  22460. var result = Scene._uniqueIdCounter;
  22461. Scene._uniqueIdCounter++;
  22462. return result;
  22463. };
  22464. Scene.prototype.addMesh = function (newMesh) {
  22465. this.meshes.push(newMesh);
  22466. //notify the collision coordinator
  22467. if (this.collisionCoordinator) {
  22468. this.collisionCoordinator.onMeshAdded(newMesh);
  22469. }
  22470. newMesh._resyncLightSources();
  22471. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22472. };
  22473. Scene.prototype.removeMesh = function (toRemove) {
  22474. var index = this.meshes.indexOf(toRemove);
  22475. if (index !== -1) {
  22476. // Remove from the scene if mesh found
  22477. this.meshes.splice(index, 1);
  22478. }
  22479. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22480. return index;
  22481. };
  22482. Scene.prototype.addTransformNode = function (newTransformNode) {
  22483. this.transformNodes.push(newTransformNode);
  22484. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22485. };
  22486. Scene.prototype.removeTransformNode = function (toRemove) {
  22487. var index = this.transformNodes.indexOf(toRemove);
  22488. if (index !== -1) {
  22489. // Remove from the scene if found
  22490. this.transformNodes.splice(index, 1);
  22491. }
  22492. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22493. return index;
  22494. };
  22495. Scene.prototype.removeSkeleton = function (toRemove) {
  22496. var index = this.skeletons.indexOf(toRemove);
  22497. if (index !== -1) {
  22498. // Remove from the scene if found
  22499. this.skeletons.splice(index, 1);
  22500. }
  22501. return index;
  22502. };
  22503. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22504. var index = this.morphTargetManagers.indexOf(toRemove);
  22505. if (index !== -1) {
  22506. // Remove from the scene if found
  22507. this.morphTargetManagers.splice(index, 1);
  22508. }
  22509. return index;
  22510. };
  22511. Scene.prototype.removeLight = function (toRemove) {
  22512. var index = this.lights.indexOf(toRemove);
  22513. if (index !== -1) {
  22514. // Remove from meshes
  22515. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22516. var mesh = _a[_i];
  22517. mesh._removeLightSource(toRemove);
  22518. }
  22519. // Remove from the scene if mesh found
  22520. this.lights.splice(index, 1);
  22521. this.sortLightsByPriority();
  22522. }
  22523. this.onLightRemovedObservable.notifyObservers(toRemove);
  22524. return index;
  22525. };
  22526. Scene.prototype.removeCamera = function (toRemove) {
  22527. var index = this.cameras.indexOf(toRemove);
  22528. if (index !== -1) {
  22529. // Remove from the scene if mesh found
  22530. this.cameras.splice(index, 1);
  22531. }
  22532. // Remove from activeCameras
  22533. var index2 = this.activeCameras.indexOf(toRemove);
  22534. if (index2 !== -1) {
  22535. // Remove from the scene if mesh found
  22536. this.activeCameras.splice(index2, 1);
  22537. }
  22538. // Reset the activeCamera
  22539. if (this.activeCamera === toRemove) {
  22540. if (this.cameras.length > 0) {
  22541. this.activeCamera = this.cameras[0];
  22542. }
  22543. else {
  22544. this.activeCamera = null;
  22545. }
  22546. }
  22547. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22548. return index;
  22549. };
  22550. Scene.prototype.removeParticleSystem = function (toRemove) {
  22551. var index = this.particleSystems.indexOf(toRemove);
  22552. if (index !== -1) {
  22553. this.particleSystems.splice(index, 1);
  22554. }
  22555. return index;
  22556. };
  22557. ;
  22558. Scene.prototype.removeAnimation = function (toRemove) {
  22559. var index = this.animations.indexOf(toRemove);
  22560. if (index !== -1) {
  22561. this.animations.splice(index, 1);
  22562. }
  22563. return index;
  22564. };
  22565. ;
  22566. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22567. var index = this.multiMaterials.indexOf(toRemove);
  22568. if (index !== -1) {
  22569. this.multiMaterials.splice(index, 1);
  22570. }
  22571. return index;
  22572. };
  22573. ;
  22574. Scene.prototype.removeMaterial = function (toRemove) {
  22575. var index = this.materials.indexOf(toRemove);
  22576. if (index !== -1) {
  22577. this.materials.splice(index, 1);
  22578. }
  22579. return index;
  22580. };
  22581. ;
  22582. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22583. var index = this.lensFlareSystems.indexOf(toRemove);
  22584. if (index !== -1) {
  22585. this.lensFlareSystems.splice(index, 1);
  22586. }
  22587. return index;
  22588. };
  22589. ;
  22590. Scene.prototype.removeActionManager = function (toRemove) {
  22591. var index = this._actionManagers.indexOf(toRemove);
  22592. if (index !== -1) {
  22593. this._actionManagers.splice(index, 1);
  22594. }
  22595. return index;
  22596. };
  22597. ;
  22598. Scene.prototype.addLight = function (newLight) {
  22599. this.lights.push(newLight);
  22600. this.sortLightsByPriority();
  22601. // Add light to all meshes (To support if the light is removed and then readded)
  22602. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22603. var mesh = _a[_i];
  22604. if (mesh._lightSources.indexOf(newLight) === -1) {
  22605. mesh._lightSources.push(newLight);
  22606. mesh._resyncLightSources();
  22607. }
  22608. }
  22609. this.onNewLightAddedObservable.notifyObservers(newLight);
  22610. };
  22611. Scene.prototype.sortLightsByPriority = function () {
  22612. if (this.requireLightSorting) {
  22613. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22614. }
  22615. };
  22616. Scene.prototype.addCamera = function (newCamera) {
  22617. this.cameras.push(newCamera);
  22618. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22619. };
  22620. Scene.prototype.addSkeleton = function (newSkeleton) {
  22621. this.skeletons.push(newSkeleton);
  22622. };
  22623. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22624. this.particleSystems.push(newParticleSystem);
  22625. };
  22626. Scene.prototype.addAnimation = function (newAnimation) {
  22627. this.animations.push(newAnimation);
  22628. };
  22629. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22630. this.multiMaterials.push(newMultiMaterial);
  22631. };
  22632. Scene.prototype.addMaterial = function (newMaterial) {
  22633. this.materials.push(newMaterial);
  22634. };
  22635. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22636. this.morphTargetManagers.push(newMorphTargetManager);
  22637. };
  22638. Scene.prototype.addGeometry = function (newGeometrie) {
  22639. this._geometries.push(newGeometrie);
  22640. };
  22641. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22642. this.lensFlareSystems.push(newLensFlareSystem);
  22643. };
  22644. Scene.prototype.addActionManager = function (newActionManager) {
  22645. this._actionManagers.push(newActionManager);
  22646. };
  22647. /**
  22648. * Switch active camera
  22649. * @param {Camera} newCamera - new active camera
  22650. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22651. */
  22652. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22653. if (attachControl === void 0) { attachControl = true; }
  22654. var canvas = this._engine.getRenderingCanvas();
  22655. if (!canvas) {
  22656. return;
  22657. }
  22658. if (this.activeCamera) {
  22659. this.activeCamera.detachControl(canvas);
  22660. }
  22661. this.activeCamera = newCamera;
  22662. if (attachControl) {
  22663. newCamera.attachControl(canvas);
  22664. }
  22665. };
  22666. /**
  22667. * sets the active camera of the scene using its ID
  22668. * @param {string} id - the camera's ID
  22669. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22670. * @see activeCamera
  22671. */
  22672. Scene.prototype.setActiveCameraByID = function (id) {
  22673. var camera = this.getCameraByID(id);
  22674. if (camera) {
  22675. this.activeCamera = camera;
  22676. return camera;
  22677. }
  22678. return null;
  22679. };
  22680. /**
  22681. * sets the active camera of the scene using its name
  22682. * @param {string} name - the camera's name
  22683. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22684. * @see activeCamera
  22685. */
  22686. Scene.prototype.setActiveCameraByName = function (name) {
  22687. var camera = this.getCameraByName(name);
  22688. if (camera) {
  22689. this.activeCamera = camera;
  22690. return camera;
  22691. }
  22692. return null;
  22693. };
  22694. /**
  22695. * get an animation group using its name
  22696. * @param {string} the material's name
  22697. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22698. */
  22699. Scene.prototype.getAnimationGroupByName = function (name) {
  22700. for (var index = 0; index < this.animationGroups.length; index++) {
  22701. if (this.animationGroups[index].name === name) {
  22702. return this.animationGroups[index];
  22703. }
  22704. }
  22705. return null;
  22706. };
  22707. /**
  22708. * get a material using its id
  22709. * @param {string} the material's ID
  22710. * @return {BABYLON.Material|null} the material or null if none found.
  22711. */
  22712. Scene.prototype.getMaterialByID = function (id) {
  22713. for (var index = 0; index < this.materials.length; index++) {
  22714. if (this.materials[index].id === id) {
  22715. return this.materials[index];
  22716. }
  22717. }
  22718. return null;
  22719. };
  22720. /**
  22721. * get a material using its name
  22722. * @param {string} the material's name
  22723. * @return {BABYLON.Material|null} the material or null if none found.
  22724. */
  22725. Scene.prototype.getMaterialByName = function (name) {
  22726. for (var index = 0; index < this.materials.length; index++) {
  22727. if (this.materials[index].name === name) {
  22728. return this.materials[index];
  22729. }
  22730. }
  22731. return null;
  22732. };
  22733. Scene.prototype.getLensFlareSystemByName = function (name) {
  22734. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22735. if (this.lensFlareSystems[index].name === name) {
  22736. return this.lensFlareSystems[index];
  22737. }
  22738. }
  22739. return null;
  22740. };
  22741. Scene.prototype.getLensFlareSystemByID = function (id) {
  22742. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22743. if (this.lensFlareSystems[index].id === id) {
  22744. return this.lensFlareSystems[index];
  22745. }
  22746. }
  22747. return null;
  22748. };
  22749. Scene.prototype.getCameraByID = function (id) {
  22750. for (var index = 0; index < this.cameras.length; index++) {
  22751. if (this.cameras[index].id === id) {
  22752. return this.cameras[index];
  22753. }
  22754. }
  22755. return null;
  22756. };
  22757. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22758. for (var index = 0; index < this.cameras.length; index++) {
  22759. if (this.cameras[index].uniqueId === uniqueId) {
  22760. return this.cameras[index];
  22761. }
  22762. }
  22763. return null;
  22764. };
  22765. /**
  22766. * get a camera using its name
  22767. * @param {string} the camera's name
  22768. * @return {BABYLON.Camera|null} the camera or null if none found.
  22769. */
  22770. Scene.prototype.getCameraByName = function (name) {
  22771. for (var index = 0; index < this.cameras.length; index++) {
  22772. if (this.cameras[index].name === name) {
  22773. return this.cameras[index];
  22774. }
  22775. }
  22776. return null;
  22777. };
  22778. /**
  22779. * get a bone using its id
  22780. * @param {string} the bone's id
  22781. * @return {BABYLON.Bone|null} the bone or null if not found
  22782. */
  22783. Scene.prototype.getBoneByID = function (id) {
  22784. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22785. var skeleton = this.skeletons[skeletonIndex];
  22786. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22787. if (skeleton.bones[boneIndex].id === id) {
  22788. return skeleton.bones[boneIndex];
  22789. }
  22790. }
  22791. }
  22792. return null;
  22793. };
  22794. /**
  22795. * get a bone using its id
  22796. * @param {string} the bone's name
  22797. * @return {BABYLON.Bone|null} the bone or null if not found
  22798. */
  22799. Scene.prototype.getBoneByName = function (name) {
  22800. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22801. var skeleton = this.skeletons[skeletonIndex];
  22802. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22803. if (skeleton.bones[boneIndex].name === name) {
  22804. return skeleton.bones[boneIndex];
  22805. }
  22806. }
  22807. }
  22808. return null;
  22809. };
  22810. /**
  22811. * get a light node using its name
  22812. * @param {string} the light's name
  22813. * @return {BABYLON.Light|null} the light or null if none found.
  22814. */
  22815. Scene.prototype.getLightByName = function (name) {
  22816. for (var index = 0; index < this.lights.length; index++) {
  22817. if (this.lights[index].name === name) {
  22818. return this.lights[index];
  22819. }
  22820. }
  22821. return null;
  22822. };
  22823. /**
  22824. * get a light node using its ID
  22825. * @param {string} the light's id
  22826. * @return {BABYLON.Light|null} the light or null if none found.
  22827. */
  22828. Scene.prototype.getLightByID = function (id) {
  22829. for (var index = 0; index < this.lights.length; index++) {
  22830. if (this.lights[index].id === id) {
  22831. return this.lights[index];
  22832. }
  22833. }
  22834. return null;
  22835. };
  22836. /**
  22837. * get a light node using its scene-generated unique ID
  22838. * @param {number} the light's unique id
  22839. * @return {BABYLON.Light|null} the light or null if none found.
  22840. */
  22841. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22842. for (var index = 0; index < this.lights.length; index++) {
  22843. if (this.lights[index].uniqueId === uniqueId) {
  22844. return this.lights[index];
  22845. }
  22846. }
  22847. return null;
  22848. };
  22849. /**
  22850. * get a particle system by id
  22851. * @param id {number} the particle system id
  22852. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22853. */
  22854. Scene.prototype.getParticleSystemByID = function (id) {
  22855. for (var index = 0; index < this.particleSystems.length; index++) {
  22856. if (this.particleSystems[index].id === id) {
  22857. return this.particleSystems[index];
  22858. }
  22859. }
  22860. return null;
  22861. };
  22862. /**
  22863. * get a geometry using its ID
  22864. * @param {string} the geometry's id
  22865. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22866. */
  22867. Scene.prototype.getGeometryByID = function (id) {
  22868. for (var index = 0; index < this._geometries.length; index++) {
  22869. if (this._geometries[index].id === id) {
  22870. return this._geometries[index];
  22871. }
  22872. }
  22873. return null;
  22874. };
  22875. /**
  22876. * add a new geometry to this scene.
  22877. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22878. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22879. * @return {boolean} was the geometry added or not
  22880. */
  22881. Scene.prototype.pushGeometry = function (geometry, force) {
  22882. if (!force && this.getGeometryByID(geometry.id)) {
  22883. return false;
  22884. }
  22885. this._geometries.push(geometry);
  22886. //notify the collision coordinator
  22887. if (this.collisionCoordinator) {
  22888. this.collisionCoordinator.onGeometryAdded(geometry);
  22889. }
  22890. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22891. return true;
  22892. };
  22893. /**
  22894. * Removes an existing geometry
  22895. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22896. * @return {boolean} was the geometry removed or not
  22897. */
  22898. Scene.prototype.removeGeometry = function (geometry) {
  22899. var index = this._geometries.indexOf(geometry);
  22900. if (index > -1) {
  22901. this._geometries.splice(index, 1);
  22902. //notify the collision coordinator
  22903. if (this.collisionCoordinator) {
  22904. this.collisionCoordinator.onGeometryDeleted(geometry);
  22905. }
  22906. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22907. return true;
  22908. }
  22909. return false;
  22910. };
  22911. Scene.prototype.getGeometries = function () {
  22912. return this._geometries;
  22913. };
  22914. /**
  22915. * Get the first added mesh found of a given ID
  22916. * @param {string} id - the id to search for
  22917. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22918. */
  22919. Scene.prototype.getMeshByID = function (id) {
  22920. for (var index = 0; index < this.meshes.length; index++) {
  22921. if (this.meshes[index].id === id) {
  22922. return this.meshes[index];
  22923. }
  22924. }
  22925. return null;
  22926. };
  22927. Scene.prototype.getMeshesByID = function (id) {
  22928. return this.meshes.filter(function (m) {
  22929. return m.id === id;
  22930. });
  22931. };
  22932. /**
  22933. * Get the first added transform node found of a given ID
  22934. * @param {string} id - the id to search for
  22935. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22936. */
  22937. Scene.prototype.getTransformNodeByID = function (id) {
  22938. for (var index = 0; index < this.transformNodes.length; index++) {
  22939. if (this.transformNodes[index].id === id) {
  22940. return this.transformNodes[index];
  22941. }
  22942. }
  22943. return null;
  22944. };
  22945. Scene.prototype.getTransformNodesByID = function (id) {
  22946. return this.transformNodes.filter(function (m) {
  22947. return m.id === id;
  22948. });
  22949. };
  22950. /**
  22951. * Get a mesh with its auto-generated unique id
  22952. * @param {number} uniqueId - the unique id to search for
  22953. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22954. */
  22955. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22956. for (var index = 0; index < this.meshes.length; index++) {
  22957. if (this.meshes[index].uniqueId === uniqueId) {
  22958. return this.meshes[index];
  22959. }
  22960. }
  22961. return null;
  22962. };
  22963. /**
  22964. * Get a the last added mesh found of a given ID
  22965. * @param {string} id - the id to search for
  22966. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22967. */
  22968. Scene.prototype.getLastMeshByID = function (id) {
  22969. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22970. if (this.meshes[index].id === id) {
  22971. return this.meshes[index];
  22972. }
  22973. }
  22974. return null;
  22975. };
  22976. /**
  22977. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22978. * @param {string} id - the id to search for
  22979. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22980. */
  22981. Scene.prototype.getLastEntryByID = function (id) {
  22982. var index;
  22983. for (index = this.meshes.length - 1; index >= 0; index--) {
  22984. if (this.meshes[index].id === id) {
  22985. return this.meshes[index];
  22986. }
  22987. }
  22988. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22989. if (this.transformNodes[index].id === id) {
  22990. return this.transformNodes[index];
  22991. }
  22992. }
  22993. for (index = this.cameras.length - 1; index >= 0; index--) {
  22994. if (this.cameras[index].id === id) {
  22995. return this.cameras[index];
  22996. }
  22997. }
  22998. for (index = this.lights.length - 1; index >= 0; index--) {
  22999. if (this.lights[index].id === id) {
  23000. return this.lights[index];
  23001. }
  23002. }
  23003. return null;
  23004. };
  23005. Scene.prototype.getNodeByID = function (id) {
  23006. var mesh = this.getMeshByID(id);
  23007. if (mesh) {
  23008. return mesh;
  23009. }
  23010. var light = this.getLightByID(id);
  23011. if (light) {
  23012. return light;
  23013. }
  23014. var camera = this.getCameraByID(id);
  23015. if (camera) {
  23016. return camera;
  23017. }
  23018. var bone = this.getBoneByID(id);
  23019. return bone;
  23020. };
  23021. Scene.prototype.getNodeByName = function (name) {
  23022. var mesh = this.getMeshByName(name);
  23023. if (mesh) {
  23024. return mesh;
  23025. }
  23026. var light = this.getLightByName(name);
  23027. if (light) {
  23028. return light;
  23029. }
  23030. var camera = this.getCameraByName(name);
  23031. if (camera) {
  23032. return camera;
  23033. }
  23034. var bone = this.getBoneByName(name);
  23035. return bone;
  23036. };
  23037. Scene.prototype.getMeshByName = function (name) {
  23038. for (var index = 0; index < this.meshes.length; index++) {
  23039. if (this.meshes[index].name === name) {
  23040. return this.meshes[index];
  23041. }
  23042. }
  23043. return null;
  23044. };
  23045. Scene.prototype.getTransformNodeByName = function (name) {
  23046. for (var index = 0; index < this.transformNodes.length; index++) {
  23047. if (this.transformNodes[index].name === name) {
  23048. return this.transformNodes[index];
  23049. }
  23050. }
  23051. return null;
  23052. };
  23053. Scene.prototype.getSoundByName = function (name) {
  23054. var index;
  23055. if (BABYLON.AudioEngine) {
  23056. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23057. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23058. return this.mainSoundTrack.soundCollection[index];
  23059. }
  23060. }
  23061. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23062. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23063. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23064. return this.soundTracks[sdIndex].soundCollection[index];
  23065. }
  23066. }
  23067. }
  23068. }
  23069. return null;
  23070. };
  23071. Scene.prototype.getLastSkeletonByID = function (id) {
  23072. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23073. if (this.skeletons[index].id === id) {
  23074. return this.skeletons[index];
  23075. }
  23076. }
  23077. return null;
  23078. };
  23079. Scene.prototype.getSkeletonById = function (id) {
  23080. for (var index = 0; index < this.skeletons.length; index++) {
  23081. if (this.skeletons[index].id === id) {
  23082. return this.skeletons[index];
  23083. }
  23084. }
  23085. return null;
  23086. };
  23087. Scene.prototype.getSkeletonByName = function (name) {
  23088. for (var index = 0; index < this.skeletons.length; index++) {
  23089. if (this.skeletons[index].name === name) {
  23090. return this.skeletons[index];
  23091. }
  23092. }
  23093. return null;
  23094. };
  23095. Scene.prototype.getMorphTargetManagerById = function (id) {
  23096. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23097. if (this.morphTargetManagers[index].uniqueId === id) {
  23098. return this.morphTargetManagers[index];
  23099. }
  23100. }
  23101. return null;
  23102. };
  23103. Scene.prototype.isActiveMesh = function (mesh) {
  23104. return (this._activeMeshes.indexOf(mesh) !== -1);
  23105. };
  23106. /**
  23107. * Return a the first highlight layer of the scene with a given name.
  23108. * @param name The name of the highlight layer to look for.
  23109. * @return The highlight layer if found otherwise null.
  23110. */
  23111. Scene.prototype.getHighlightLayerByName = function (name) {
  23112. for (var index = 0; index < this.highlightLayers.length; index++) {
  23113. if (this.highlightLayers[index].name === name) {
  23114. return this.highlightLayers[index];
  23115. }
  23116. }
  23117. return null;
  23118. };
  23119. Object.defineProperty(Scene.prototype, "uid", {
  23120. /**
  23121. * Return a unique id as a string which can serve as an identifier for the scene
  23122. */
  23123. get: function () {
  23124. if (!this._uid) {
  23125. this._uid = BABYLON.Tools.RandomId();
  23126. }
  23127. return this._uid;
  23128. },
  23129. enumerable: true,
  23130. configurable: true
  23131. });
  23132. /**
  23133. * Add an externaly attached data from its key.
  23134. * This method call will fail and return false, if such key already exists.
  23135. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23136. * @param key the unique key that identifies the data
  23137. * @param data the data object to associate to the key for this Engine instance
  23138. * @return true if no such key were already present and the data was added successfully, false otherwise
  23139. */
  23140. Scene.prototype.addExternalData = function (key, data) {
  23141. if (!this._externalData) {
  23142. this._externalData = new BABYLON.StringDictionary();
  23143. }
  23144. return this._externalData.add(key, data);
  23145. };
  23146. /**
  23147. * Get an externaly attached data from its key
  23148. * @param key the unique key that identifies the data
  23149. * @return the associated data, if present (can be null), or undefined if not present
  23150. */
  23151. Scene.prototype.getExternalData = function (key) {
  23152. if (!this._externalData) {
  23153. return null;
  23154. }
  23155. return this._externalData.get(key);
  23156. };
  23157. /**
  23158. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23159. * @param key the unique key that identifies the data
  23160. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23161. * @return the associated data, can be null if the factory returned null.
  23162. */
  23163. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23164. if (!this._externalData) {
  23165. this._externalData = new BABYLON.StringDictionary();
  23166. }
  23167. return this._externalData.getOrAddWithFactory(key, factory);
  23168. };
  23169. /**
  23170. * Remove an externaly attached data from the Engine instance
  23171. * @param key the unique key that identifies the data
  23172. * @return true if the data was successfully removed, false if it doesn't exist
  23173. */
  23174. Scene.prototype.removeExternalData = function (key) {
  23175. return this._externalData.remove(key);
  23176. };
  23177. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23178. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23179. if (mesh.showSubMeshesBoundingBox) {
  23180. var boundingInfo = subMesh.getBoundingInfo();
  23181. if (boundingInfo !== null && boundingInfo !== undefined) {
  23182. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23183. }
  23184. }
  23185. var material = subMesh.getMaterial();
  23186. if (material !== null && material !== undefined) {
  23187. // Render targets
  23188. if (material.getRenderTargetTextures !== undefined) {
  23189. if (this._processedMaterials.indexOf(material) === -1) {
  23190. this._processedMaterials.push(material);
  23191. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23192. }
  23193. }
  23194. // Dispatch
  23195. this._activeIndices.addCount(subMesh.indexCount, false);
  23196. this._renderingManager.dispatch(subMesh, mesh, material);
  23197. }
  23198. }
  23199. };
  23200. Scene.prototype._isInIntermediateRendering = function () {
  23201. return this._intermediateRendering;
  23202. };
  23203. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23204. this._activeMeshCandidateProvider = provider;
  23205. };
  23206. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23207. return this._activeMeshCandidateProvider;
  23208. };
  23209. /**
  23210. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23211. */
  23212. Scene.prototype.freezeActiveMeshes = function () {
  23213. this._evaluateActiveMeshes();
  23214. this._activeMeshesFrozen = true;
  23215. return this;
  23216. };
  23217. /**
  23218. * Use this function to restart evaluating active meshes on every frame
  23219. */
  23220. Scene.prototype.unfreezeActiveMeshes = function () {
  23221. this._activeMeshesFrozen = false;
  23222. return this;
  23223. };
  23224. Scene.prototype._evaluateActiveMeshes = function () {
  23225. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23226. return;
  23227. }
  23228. if (!this.activeCamera) {
  23229. return;
  23230. }
  23231. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23232. this.activeCamera._activeMeshes.reset();
  23233. this._activeMeshes.reset();
  23234. this._renderingManager.reset();
  23235. this._processedMaterials.reset();
  23236. this._activeParticleSystems.reset();
  23237. this._activeSkeletons.reset();
  23238. this._softwareSkinnedMeshes.reset();
  23239. if (this._boundingBoxRenderer) {
  23240. this._boundingBoxRenderer.reset();
  23241. }
  23242. // Meshes
  23243. var meshes;
  23244. var len;
  23245. var checkIsEnabled = true;
  23246. // Determine mesh candidates
  23247. if (this._activeMeshCandidateProvider !== undefined) {
  23248. // Use _activeMeshCandidateProvider
  23249. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23250. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23251. if (meshes !== undefined) {
  23252. len = meshes.length;
  23253. }
  23254. else {
  23255. len = 0;
  23256. }
  23257. }
  23258. else if (this._selectionOctree !== undefined) {
  23259. // Octree
  23260. var selection = this._selectionOctree.select(this._frustumPlanes);
  23261. meshes = selection.data;
  23262. len = selection.length;
  23263. }
  23264. else {
  23265. // Full scene traversal
  23266. len = this.meshes.length;
  23267. meshes = this.meshes;
  23268. }
  23269. // Check each mesh
  23270. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23271. mesh = meshes[meshIndex];
  23272. if (mesh.isBlocked) {
  23273. continue;
  23274. }
  23275. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23276. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23277. continue;
  23278. }
  23279. mesh.computeWorldMatrix();
  23280. // Intersections
  23281. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23282. this._meshesForIntersections.pushNoDuplicate(mesh);
  23283. }
  23284. // Switch to current LOD
  23285. meshLOD = mesh.getLOD(this.activeCamera);
  23286. if (meshLOD === undefined || meshLOD === null) {
  23287. continue;
  23288. }
  23289. mesh._preActivate();
  23290. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23291. this._activeMeshes.push(mesh);
  23292. this.activeCamera._activeMeshes.push(mesh);
  23293. mesh._activate(this._renderId);
  23294. if (meshLOD !== mesh) {
  23295. meshLOD._activate(this._renderId);
  23296. }
  23297. this._activeMesh(mesh, meshLOD);
  23298. }
  23299. }
  23300. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23301. // Particle systems
  23302. if (this.particlesEnabled) {
  23303. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23304. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23305. var particleSystem = this.particleSystems[particleIndex];
  23306. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23307. continue;
  23308. }
  23309. var emitter = particleSystem.emitter;
  23310. if (!emitter.position || emitter.isEnabled()) {
  23311. this._activeParticleSystems.push(particleSystem);
  23312. particleSystem.animate();
  23313. this._renderingManager.dispatchParticles(particleSystem);
  23314. }
  23315. }
  23316. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23317. }
  23318. };
  23319. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23320. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23321. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23322. mesh.skeleton.prepare();
  23323. }
  23324. if (!mesh.computeBonesUsingShaders) {
  23325. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23326. }
  23327. }
  23328. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23329. var boundingInfo = sourceMesh.getBoundingInfo();
  23330. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23331. }
  23332. if (mesh !== undefined && mesh !== null
  23333. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23334. // Submeshes Octrees
  23335. var len;
  23336. var subMeshes;
  23337. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23338. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23339. len = intersections.length;
  23340. subMeshes = intersections.data;
  23341. }
  23342. else {
  23343. subMeshes = mesh.subMeshes;
  23344. len = subMeshes.length;
  23345. }
  23346. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23347. subMesh = subMeshes[subIndex];
  23348. this._evaluateSubMesh(subMesh, mesh);
  23349. }
  23350. }
  23351. };
  23352. Scene.prototype.updateTransformMatrix = function (force) {
  23353. if (!this.activeCamera) {
  23354. return;
  23355. }
  23356. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23357. };
  23358. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23359. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23360. };
  23361. Scene.prototype._renderForCamera = function (camera) {
  23362. if (camera && camera._skipRendering) {
  23363. return;
  23364. }
  23365. var engine = this._engine;
  23366. this.activeCamera = camera;
  23367. if (!this.activeCamera)
  23368. throw new Error("Active camera not set");
  23369. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23370. // Viewport
  23371. engine.setViewport(this.activeCamera.viewport);
  23372. // Camera
  23373. this.resetCachedMaterial();
  23374. this._renderId++;
  23375. this.activeCamera.update();
  23376. this.updateTransformMatrix();
  23377. if (camera._alternateCamera) {
  23378. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23379. this._alternateRendering = true;
  23380. }
  23381. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23382. // Meshes
  23383. this._evaluateActiveMeshes();
  23384. // Software skinning
  23385. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23386. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23387. mesh.applySkeleton(mesh.skeleton);
  23388. }
  23389. // Render targets
  23390. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23391. var needsRestoreFrameBuffer = false;
  23392. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23393. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23394. }
  23395. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23396. this._intermediateRendering = true;
  23397. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23398. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23399. var renderTarget = this._renderTargets.data[renderIndex];
  23400. if (renderTarget._shouldRender()) {
  23401. this._renderId++;
  23402. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23403. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23404. }
  23405. }
  23406. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23407. this._intermediateRendering = false;
  23408. this._renderId++;
  23409. needsRestoreFrameBuffer = true; // Restore back buffer
  23410. }
  23411. // Render HighlightLayer Texture
  23412. var stencilState = this._engine.getStencilBuffer();
  23413. var renderhighlights = false;
  23414. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  23415. this._intermediateRendering = true;
  23416. for (var i = 0; i < this.highlightLayers.length; i++) {
  23417. var highlightLayer = this.highlightLayers[i];
  23418. if (highlightLayer.shouldRender() &&
  23419. (!highlightLayer.camera ||
  23420. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  23421. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23422. renderhighlights = true;
  23423. var renderTarget = highlightLayer._mainTexture;
  23424. if (renderTarget._shouldRender()) {
  23425. this._renderId++;
  23426. renderTarget.render(false, false);
  23427. needsRestoreFrameBuffer = true;
  23428. }
  23429. }
  23430. }
  23431. this._intermediateRendering = false;
  23432. this._renderId++;
  23433. }
  23434. if (needsRestoreFrameBuffer) {
  23435. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23436. }
  23437. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23438. // Prepare Frame
  23439. this.postProcessManager._prepareFrame();
  23440. // Backgrounds
  23441. var layerIndex;
  23442. var layer;
  23443. if (this.layers.length) {
  23444. engine.setDepthBuffer(false);
  23445. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23446. layer = this.layers[layerIndex];
  23447. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23448. layer.render();
  23449. }
  23450. }
  23451. engine.setDepthBuffer(true);
  23452. }
  23453. // Activate HighlightLayer stencil
  23454. if (renderhighlights) {
  23455. this._engine.setStencilBuffer(true);
  23456. }
  23457. // Render
  23458. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23459. this._renderingManager.render(null, null, true, true);
  23460. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23461. // Restore HighlightLayer stencil
  23462. if (renderhighlights) {
  23463. this._engine.setStencilBuffer(stencilState);
  23464. }
  23465. // Bounding boxes
  23466. if (this._boundingBoxRenderer) {
  23467. this._boundingBoxRenderer.render();
  23468. }
  23469. // Lens flares
  23470. if (this.lensFlaresEnabled) {
  23471. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23472. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23473. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23474. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23475. lensFlareSystem.render();
  23476. }
  23477. }
  23478. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23479. }
  23480. // Foregrounds
  23481. if (this.layers.length) {
  23482. engine.setDepthBuffer(false);
  23483. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23484. layer = this.layers[layerIndex];
  23485. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23486. layer.render();
  23487. }
  23488. }
  23489. engine.setDepthBuffer(true);
  23490. }
  23491. // Highlight Layer
  23492. if (renderhighlights) {
  23493. engine.setDepthBuffer(false);
  23494. for (var i = 0; i < this.highlightLayers.length; i++) {
  23495. if (this.highlightLayers[i].shouldRender()) {
  23496. this.highlightLayers[i].render();
  23497. }
  23498. }
  23499. engine.setDepthBuffer(true);
  23500. }
  23501. // Finalize frame
  23502. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23503. // Reset some special arrays
  23504. this._renderTargets.reset();
  23505. this._alternateRendering = false;
  23506. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23507. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23508. };
  23509. Scene.prototype._processSubCameras = function (camera) {
  23510. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23511. this._renderForCamera(camera);
  23512. return;
  23513. }
  23514. // Update camera
  23515. if (this.activeCamera) {
  23516. this.activeCamera.update();
  23517. }
  23518. // rig cameras
  23519. for (var index = 0; index < camera._rigCameras.length; index++) {
  23520. this._renderForCamera(camera._rigCameras[index]);
  23521. }
  23522. this.activeCamera = camera;
  23523. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23524. };
  23525. Scene.prototype._checkIntersections = function () {
  23526. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23527. var sourceMesh = this._meshesForIntersections.data[index];
  23528. if (!sourceMesh.actionManager) {
  23529. continue;
  23530. }
  23531. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23532. var action = sourceMesh.actionManager.actions[actionIndex];
  23533. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23534. var parameters = action.getTriggerParameter();
  23535. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23536. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23537. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23538. if (areIntersecting && currentIntersectionInProgress === -1) {
  23539. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23540. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23541. sourceMesh._intersectionsInProgress.push(otherMesh);
  23542. }
  23543. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23544. sourceMesh._intersectionsInProgress.push(otherMesh);
  23545. }
  23546. }
  23547. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23548. //They intersected, and now they don't.
  23549. //is this trigger an exit trigger? execute an event.
  23550. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23551. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23552. }
  23553. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23554. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23555. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23556. }
  23557. }
  23558. }
  23559. }
  23560. }
  23561. };
  23562. Scene.prototype.render = function () {
  23563. if (this.isDisposed) {
  23564. return;
  23565. }
  23566. this._activeParticles.fetchNewFrame();
  23567. this._totalVertices.fetchNewFrame();
  23568. this._activeIndices.fetchNewFrame();
  23569. this._activeBones.fetchNewFrame();
  23570. this._meshesForIntersections.reset();
  23571. this.resetCachedMaterial();
  23572. this.onBeforeAnimationsObservable.notifyObservers(this);
  23573. // Actions
  23574. if (this.actionManager) {
  23575. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23576. }
  23577. //Simplification Queue
  23578. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23579. this.simplificationQueue.executeNext();
  23580. }
  23581. if (this._engine.isDeterministicLockStep()) {
  23582. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23583. var defaultFPS = (60.0 / 1000.0);
  23584. var defaultFrameTime = 1000 / 60; // frame time in MS
  23585. if (this._physicsEngine) {
  23586. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23587. }
  23588. var stepsTaken = 0;
  23589. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23590. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23591. internalSteps = Math.min(internalSteps, maxSubSteps);
  23592. do {
  23593. this.onBeforeStepObservable.notifyObservers(this);
  23594. // Animations
  23595. this._animationRatio = defaultFrameTime * defaultFPS;
  23596. this._animate();
  23597. this.onAfterAnimationsObservable.notifyObservers(this);
  23598. // Physics
  23599. if (this._physicsEngine) {
  23600. this.onBeforePhysicsObservable.notifyObservers(this);
  23601. this._physicsEngine._step(defaultFrameTime / 1000);
  23602. this.onAfterPhysicsObservable.notifyObservers(this);
  23603. }
  23604. this.onAfterStepObservable.notifyObservers(this);
  23605. this._currentStepId++;
  23606. stepsTaken++;
  23607. deltaTime -= defaultFrameTime;
  23608. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23609. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23610. }
  23611. else {
  23612. // Animations
  23613. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23614. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23615. this._animate();
  23616. this.onAfterAnimationsObservable.notifyObservers(this);
  23617. // Physics
  23618. if (this._physicsEngine) {
  23619. this.onBeforePhysicsObservable.notifyObservers(this);
  23620. this._physicsEngine._step(deltaTime / 1000.0);
  23621. this.onAfterPhysicsObservable.notifyObservers(this);
  23622. }
  23623. }
  23624. // update gamepad manager
  23625. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23626. this._gamepadManager._checkGamepadsStatus();
  23627. }
  23628. // Before render
  23629. this.onBeforeRenderObservable.notifyObservers(this);
  23630. // Customs render targets
  23631. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23632. var engine = this.getEngine();
  23633. var currentActiveCamera = this.activeCamera;
  23634. if (this.renderTargetsEnabled) {
  23635. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23636. this._intermediateRendering = true;
  23637. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23638. var renderTarget = this.customRenderTargets[customIndex];
  23639. if (renderTarget._shouldRender()) {
  23640. this._renderId++;
  23641. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23642. if (!this.activeCamera)
  23643. throw new Error("Active camera not set");
  23644. // Viewport
  23645. engine.setViewport(this.activeCamera.viewport);
  23646. // Camera
  23647. this.updateTransformMatrix();
  23648. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23649. }
  23650. }
  23651. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23652. this._intermediateRendering = false;
  23653. this._renderId++;
  23654. }
  23655. // Restore back buffer
  23656. if (this.customRenderTargets.length > 0) {
  23657. engine.restoreDefaultFramebuffer();
  23658. }
  23659. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23660. this.activeCamera = currentActiveCamera;
  23661. // Procedural textures
  23662. if (this.proceduralTexturesEnabled) {
  23663. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23664. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23665. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23666. if (proceduralTexture._shouldRender()) {
  23667. proceduralTexture.render();
  23668. }
  23669. }
  23670. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23671. }
  23672. // Clear
  23673. if (this.autoClearDepthAndStencil || this.autoClear) {
  23674. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23675. }
  23676. // Shadows
  23677. if (this.shadowsEnabled) {
  23678. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23679. var light = this.lights[lightIndex];
  23680. var shadowGenerator = light.getShadowGenerator();
  23681. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23682. var shadowMap = (shadowGenerator.getShadowMap());
  23683. if (this.textures.indexOf(shadowMap) !== -1) {
  23684. this._renderTargets.push(shadowMap);
  23685. }
  23686. }
  23687. }
  23688. }
  23689. // Depth renderer
  23690. if (this._depthRenderer) {
  23691. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23692. }
  23693. // Geometry renderer
  23694. if (this._geometryBufferRenderer) {
  23695. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23696. }
  23697. // RenderPipeline
  23698. if (this._postProcessRenderPipelineManager) {
  23699. this._postProcessRenderPipelineManager.update();
  23700. }
  23701. // Multi-cameras?
  23702. if (this.activeCameras.length > 0) {
  23703. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23704. if (cameraIndex > 0) {
  23705. this._engine.clear(null, false, true, true);
  23706. }
  23707. this._processSubCameras(this.activeCameras[cameraIndex]);
  23708. }
  23709. }
  23710. else {
  23711. if (!this.activeCamera) {
  23712. throw new Error("No camera defined");
  23713. }
  23714. this._processSubCameras(this.activeCamera);
  23715. }
  23716. // Intersection checks
  23717. this._checkIntersections();
  23718. // Update the audio listener attached to the camera
  23719. if (BABYLON.AudioEngine) {
  23720. this._updateAudioParameters();
  23721. }
  23722. // After render
  23723. if (this.afterRender) {
  23724. this.afterRender();
  23725. }
  23726. this.onAfterRenderObservable.notifyObservers(this);
  23727. // Cleaning
  23728. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23729. var data = this._toBeDisposed.data[index];
  23730. if (data) {
  23731. data.dispose();
  23732. }
  23733. this._toBeDisposed[index] = null;
  23734. }
  23735. this._toBeDisposed.reset();
  23736. if (this.dumpNextRenderTargets) {
  23737. this.dumpNextRenderTargets = false;
  23738. }
  23739. this._activeBones.addCount(0, true);
  23740. this._activeIndices.addCount(0, true);
  23741. this._activeParticles.addCount(0, true);
  23742. };
  23743. Scene.prototype._updateAudioParameters = function () {
  23744. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23745. return;
  23746. }
  23747. var listeningCamera;
  23748. var audioEngine = BABYLON.Engine.audioEngine;
  23749. if (this.activeCameras.length > 0) {
  23750. listeningCamera = this.activeCameras[0];
  23751. }
  23752. else {
  23753. listeningCamera = this.activeCamera;
  23754. }
  23755. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23756. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23757. // for VR cameras
  23758. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23759. listeningCamera = listeningCamera.rigCameras[0];
  23760. }
  23761. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23762. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23763. cameraDirection.normalize();
  23764. // To avoid some errors on GearVR
  23765. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23766. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23767. }
  23768. var i;
  23769. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23770. var sound = this.mainSoundTrack.soundCollection[i];
  23771. if (sound.useCustomAttenuation) {
  23772. sound.updateDistanceFromListener();
  23773. }
  23774. }
  23775. for (i = 0; i < this.soundTracks.length; i++) {
  23776. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23777. sound = this.soundTracks[i].soundCollection[j];
  23778. if (sound.useCustomAttenuation) {
  23779. sound.updateDistanceFromListener();
  23780. }
  23781. }
  23782. }
  23783. }
  23784. };
  23785. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23786. // Audio
  23787. get: function () {
  23788. return this._audioEnabled;
  23789. },
  23790. set: function (value) {
  23791. this._audioEnabled = value;
  23792. if (BABYLON.AudioEngine) {
  23793. if (this._audioEnabled) {
  23794. this._enableAudio();
  23795. }
  23796. else {
  23797. this._disableAudio();
  23798. }
  23799. }
  23800. },
  23801. enumerable: true,
  23802. configurable: true
  23803. });
  23804. Scene.prototype._disableAudio = function () {
  23805. var i;
  23806. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23807. this.mainSoundTrack.soundCollection[i].pause();
  23808. }
  23809. for (i = 0; i < this.soundTracks.length; i++) {
  23810. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23811. this.soundTracks[i].soundCollection[j].pause();
  23812. }
  23813. }
  23814. };
  23815. Scene.prototype._enableAudio = function () {
  23816. var i;
  23817. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23818. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23819. this.mainSoundTrack.soundCollection[i].play();
  23820. }
  23821. }
  23822. for (i = 0; i < this.soundTracks.length; i++) {
  23823. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23824. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23825. this.soundTracks[i].soundCollection[j].play();
  23826. }
  23827. }
  23828. }
  23829. };
  23830. Object.defineProperty(Scene.prototype, "headphone", {
  23831. get: function () {
  23832. return this._headphone;
  23833. },
  23834. set: function (value) {
  23835. this._headphone = value;
  23836. if (BABYLON.AudioEngine) {
  23837. if (this._headphone) {
  23838. this._switchAudioModeForHeadphones();
  23839. }
  23840. else {
  23841. this._switchAudioModeForNormalSpeakers();
  23842. }
  23843. }
  23844. },
  23845. enumerable: true,
  23846. configurable: true
  23847. });
  23848. Scene.prototype._switchAudioModeForHeadphones = function () {
  23849. this.mainSoundTrack.switchPanningModelToHRTF();
  23850. for (var i = 0; i < this.soundTracks.length; i++) {
  23851. this.soundTracks[i].switchPanningModelToHRTF();
  23852. }
  23853. };
  23854. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23855. this.mainSoundTrack.switchPanningModelToEqualPower();
  23856. for (var i = 0; i < this.soundTracks.length; i++) {
  23857. this.soundTracks[i].switchPanningModelToEqualPower();
  23858. }
  23859. };
  23860. Scene.prototype.enableDepthRenderer = function () {
  23861. if (this._depthRenderer) {
  23862. return this._depthRenderer;
  23863. }
  23864. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23865. return this._depthRenderer;
  23866. };
  23867. Scene.prototype.disableDepthRenderer = function () {
  23868. if (!this._depthRenderer) {
  23869. return;
  23870. }
  23871. this._depthRenderer.dispose();
  23872. this._depthRenderer = null;
  23873. };
  23874. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23875. if (ratio === void 0) { ratio = 1; }
  23876. if (this._geometryBufferRenderer) {
  23877. return this._geometryBufferRenderer;
  23878. }
  23879. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23880. if (!this._geometryBufferRenderer.isSupported) {
  23881. this._geometryBufferRenderer = null;
  23882. }
  23883. return this._geometryBufferRenderer;
  23884. };
  23885. Scene.prototype.disableGeometryBufferRenderer = function () {
  23886. if (!this._geometryBufferRenderer) {
  23887. return;
  23888. }
  23889. this._geometryBufferRenderer.dispose();
  23890. this._geometryBufferRenderer = null;
  23891. };
  23892. Scene.prototype.freezeMaterials = function () {
  23893. for (var i = 0; i < this.materials.length; i++) {
  23894. this.materials[i].freeze();
  23895. }
  23896. };
  23897. Scene.prototype.unfreezeMaterials = function () {
  23898. for (var i = 0; i < this.materials.length; i++) {
  23899. this.materials[i].unfreeze();
  23900. }
  23901. };
  23902. Scene.prototype.dispose = function () {
  23903. this.beforeRender = null;
  23904. this.afterRender = null;
  23905. this.skeletons = [];
  23906. this.morphTargetManagers = [];
  23907. this.importedMeshesFiles = new Array();
  23908. this.stopAllAnimations();
  23909. this.resetCachedMaterial();
  23910. if (this._depthRenderer) {
  23911. this._depthRenderer.dispose();
  23912. }
  23913. if (this._gamepadManager) {
  23914. this._gamepadManager.dispose();
  23915. this._gamepadManager = null;
  23916. }
  23917. // Smart arrays
  23918. if (this.activeCamera) {
  23919. this.activeCamera._activeMeshes.dispose();
  23920. this.activeCamera = null;
  23921. }
  23922. this._activeMeshes.dispose();
  23923. this._renderingManager.dispose();
  23924. this._processedMaterials.dispose();
  23925. this._activeParticleSystems.dispose();
  23926. this._activeSkeletons.dispose();
  23927. this._softwareSkinnedMeshes.dispose();
  23928. this._renderTargets.dispose();
  23929. if (this._boundingBoxRenderer) {
  23930. this._boundingBoxRenderer.dispose();
  23931. }
  23932. this._meshesForIntersections.dispose();
  23933. this._toBeDisposed.dispose();
  23934. // Abort active requests
  23935. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23936. var request = _a[_i];
  23937. request.abort();
  23938. }
  23939. // Debug layer
  23940. if (this._debugLayer) {
  23941. this._debugLayer.hide();
  23942. }
  23943. // Events
  23944. this.onDisposeObservable.notifyObservers(this);
  23945. this.onDisposeObservable.clear();
  23946. this.onBeforeRenderObservable.clear();
  23947. this.onAfterRenderObservable.clear();
  23948. this.OnBeforeRenderTargetsRenderObservable.clear();
  23949. this.OnAfterRenderTargetsRenderObservable.clear();
  23950. this.onAfterStepObservable.clear();
  23951. this.onBeforeStepObservable.clear();
  23952. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23953. this.onAfterActiveMeshesEvaluationObservable.clear();
  23954. this.onBeforeParticlesRenderingObservable.clear();
  23955. this.onAfterParticlesRenderingObservable.clear();
  23956. this.onBeforeSpritesRenderingObservable.clear();
  23957. this.onAfterSpritesRenderingObservable.clear();
  23958. this.onBeforeDrawPhaseObservable.clear();
  23959. this.onAfterDrawPhaseObservable.clear();
  23960. this.onBeforePhysicsObservable.clear();
  23961. this.onAfterPhysicsObservable.clear();
  23962. this.onBeforeAnimationsObservable.clear();
  23963. this.onAfterAnimationsObservable.clear();
  23964. this.onDataLoadedObservable.clear();
  23965. this.detachControl();
  23966. // Release sounds & sounds tracks
  23967. if (BABYLON.AudioEngine) {
  23968. this.disposeSounds();
  23969. }
  23970. // VR Helper
  23971. if (this.VRHelper) {
  23972. this.VRHelper.dispose();
  23973. }
  23974. // Detach cameras
  23975. var canvas = this._engine.getRenderingCanvas();
  23976. if (canvas) {
  23977. var index;
  23978. for (index = 0; index < this.cameras.length; index++) {
  23979. this.cameras[index].detachControl(canvas);
  23980. }
  23981. }
  23982. // Release animation groups
  23983. while (this.animationGroups.length) {
  23984. this.animationGroups[0].dispose();
  23985. }
  23986. // Release lights
  23987. while (this.lights.length) {
  23988. this.lights[0].dispose();
  23989. }
  23990. // Release meshes
  23991. while (this.meshes.length) {
  23992. this.meshes[0].dispose(true);
  23993. }
  23994. while (this.transformNodes.length) {
  23995. this.removeTransformNode(this.transformNodes[0]);
  23996. }
  23997. // Release cameras
  23998. while (this.cameras.length) {
  23999. this.cameras[0].dispose();
  24000. }
  24001. // Release materials
  24002. if (this.defaultMaterial) {
  24003. this.defaultMaterial.dispose();
  24004. }
  24005. while (this.multiMaterials.length) {
  24006. this.multiMaterials[0].dispose();
  24007. }
  24008. while (this.materials.length) {
  24009. this.materials[0].dispose();
  24010. }
  24011. // Release particles
  24012. while (this.particleSystems.length) {
  24013. this.particleSystems[0].dispose();
  24014. }
  24015. // Release sprites
  24016. while (this.spriteManagers.length) {
  24017. this.spriteManagers[0].dispose();
  24018. }
  24019. // Release postProcesses
  24020. while (this.postProcesses.length) {
  24021. this.postProcesses[0].dispose();
  24022. }
  24023. // Release layers
  24024. while (this.layers.length) {
  24025. this.layers[0].dispose();
  24026. }
  24027. while (this.highlightLayers.length) {
  24028. this.highlightLayers[0].dispose();
  24029. }
  24030. // Release textures
  24031. while (this.textures.length) {
  24032. this.textures[0].dispose();
  24033. }
  24034. // Release UBO
  24035. this._sceneUbo.dispose();
  24036. if (this._alternateSceneUbo) {
  24037. this._alternateSceneUbo.dispose();
  24038. }
  24039. // Post-processes
  24040. this.postProcessManager.dispose();
  24041. if (this._postProcessRenderPipelineManager) {
  24042. this._postProcessRenderPipelineManager.dispose();
  24043. }
  24044. // Physics
  24045. if (this._physicsEngine) {
  24046. this.disablePhysicsEngine();
  24047. }
  24048. // Remove from engine
  24049. index = this._engine.scenes.indexOf(this);
  24050. if (index > -1) {
  24051. this._engine.scenes.splice(index, 1);
  24052. }
  24053. this._engine.wipeCaches(true);
  24054. this._isDisposed = true;
  24055. };
  24056. Object.defineProperty(Scene.prototype, "isDisposed", {
  24057. get: function () {
  24058. return this._isDisposed;
  24059. },
  24060. enumerable: true,
  24061. configurable: true
  24062. });
  24063. // Release sounds & sounds tracks
  24064. Scene.prototype.disposeSounds = function () {
  24065. if (!this._mainSoundTrack) {
  24066. return;
  24067. }
  24068. this.mainSoundTrack.dispose();
  24069. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24070. this.soundTracks[scIndex].dispose();
  24071. }
  24072. };
  24073. // Octrees
  24074. Scene.prototype.getWorldExtends = function () {
  24075. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24076. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24077. for (var index = 0; index < this.meshes.length; index++) {
  24078. var mesh = this.meshes[index];
  24079. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24080. continue;
  24081. }
  24082. mesh.computeWorldMatrix(true);
  24083. var boundingInfo = mesh.getBoundingInfo();
  24084. var minBox = boundingInfo.boundingBox.minimumWorld;
  24085. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24086. BABYLON.Tools.CheckExtends(minBox, min, max);
  24087. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24088. }
  24089. return {
  24090. min: min,
  24091. max: max
  24092. };
  24093. };
  24094. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24095. if (maxCapacity === void 0) { maxCapacity = 64; }
  24096. if (maxDepth === void 0) { maxDepth = 2; }
  24097. if (!this._selectionOctree) {
  24098. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24099. }
  24100. var worldExtends = this.getWorldExtends();
  24101. // Update octree
  24102. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24103. return this._selectionOctree;
  24104. };
  24105. // Picking
  24106. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24107. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24108. var result = BABYLON.Ray.Zero();
  24109. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24110. return result;
  24111. };
  24112. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24113. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24114. var engine = this._engine;
  24115. if (!camera) {
  24116. if (!this.activeCamera)
  24117. throw new Error("Active camera not set");
  24118. camera = this.activeCamera;
  24119. }
  24120. var cameraViewport = camera.viewport;
  24121. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24122. // Moving coordinates to local viewport world
  24123. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24124. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24125. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24126. return this;
  24127. };
  24128. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24129. var result = BABYLON.Ray.Zero();
  24130. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24131. return result;
  24132. };
  24133. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24134. if (!BABYLON.PickingInfo) {
  24135. return this;
  24136. }
  24137. var engine = this._engine;
  24138. if (!camera) {
  24139. if (!this.activeCamera)
  24140. throw new Error("Active camera not set");
  24141. camera = this.activeCamera;
  24142. }
  24143. var cameraViewport = camera.viewport;
  24144. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24145. var identity = BABYLON.Matrix.Identity();
  24146. // Moving coordinates to local viewport world
  24147. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24148. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24149. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24150. return this;
  24151. };
  24152. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24153. if (!BABYLON.PickingInfo) {
  24154. return null;
  24155. }
  24156. var pickingInfo = null;
  24157. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24158. var mesh = this.meshes[meshIndex];
  24159. if (predicate) {
  24160. if (!predicate(mesh)) {
  24161. continue;
  24162. }
  24163. }
  24164. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24165. continue;
  24166. }
  24167. var world = mesh.getWorldMatrix();
  24168. var ray = rayFunction(world);
  24169. var result = mesh.intersects(ray, fastCheck);
  24170. if (!result || !result.hit)
  24171. continue;
  24172. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24173. continue;
  24174. pickingInfo = result;
  24175. if (fastCheck) {
  24176. break;
  24177. }
  24178. }
  24179. return pickingInfo || new BABYLON.PickingInfo();
  24180. };
  24181. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24182. if (!BABYLON.PickingInfo) {
  24183. return null;
  24184. }
  24185. var pickingInfos = new Array();
  24186. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24187. var mesh = this.meshes[meshIndex];
  24188. if (predicate) {
  24189. if (!predicate(mesh)) {
  24190. continue;
  24191. }
  24192. }
  24193. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24194. continue;
  24195. }
  24196. var world = mesh.getWorldMatrix();
  24197. var ray = rayFunction(world);
  24198. var result = mesh.intersects(ray, false);
  24199. if (!result || !result.hit)
  24200. continue;
  24201. pickingInfos.push(result);
  24202. }
  24203. return pickingInfos;
  24204. };
  24205. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24206. if (!BABYLON.PickingInfo) {
  24207. return null;
  24208. }
  24209. var pickingInfo = null;
  24210. if (!camera) {
  24211. if (!this.activeCamera) {
  24212. return null;
  24213. }
  24214. camera = this.activeCamera;
  24215. }
  24216. if (this.spriteManagers.length > 0) {
  24217. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24218. var spriteManager = this.spriteManagers[spriteIndex];
  24219. if (!spriteManager.isPickable) {
  24220. continue;
  24221. }
  24222. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24223. if (!result || !result.hit)
  24224. continue;
  24225. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24226. continue;
  24227. pickingInfo = result;
  24228. if (fastCheck) {
  24229. break;
  24230. }
  24231. }
  24232. }
  24233. return pickingInfo || new BABYLON.PickingInfo();
  24234. };
  24235. /** Launch a ray to try to pick a mesh in the scene
  24236. * @param x position on screen
  24237. * @param y position on screen
  24238. * @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
  24239. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24240. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24241. */
  24242. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24243. var _this = this;
  24244. if (!BABYLON.PickingInfo) {
  24245. return null;
  24246. }
  24247. return this._internalPick(function (world) {
  24248. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24249. return _this._tempPickingRay;
  24250. }, predicate, fastCheck);
  24251. };
  24252. /** Launch a ray to try to pick a sprite in the scene
  24253. * @param x position on screen
  24254. * @param y position on screen
  24255. * @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
  24256. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24257. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24258. */
  24259. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24260. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24261. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24262. };
  24263. /** Use the given ray to pick a mesh in the scene
  24264. * @param ray The ray to use to pick meshes
  24265. * @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
  24266. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24267. */
  24268. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24269. var _this = this;
  24270. return this._internalPick(function (world) {
  24271. if (!_this._pickWithRayInverseMatrix) {
  24272. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24273. }
  24274. world.invertToRef(_this._pickWithRayInverseMatrix);
  24275. if (!_this._cachedRayForTransform) {
  24276. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24277. }
  24278. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24279. return _this._cachedRayForTransform;
  24280. }, predicate, fastCheck);
  24281. };
  24282. /**
  24283. * Launch a ray to try to pick a mesh in the scene
  24284. * @param x X position on screen
  24285. * @param y Y position on screen
  24286. * @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
  24287. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24288. */
  24289. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24290. var _this = this;
  24291. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24292. };
  24293. /**
  24294. * Launch a ray to try to pick a mesh in the scene
  24295. * @param ray Ray to use
  24296. * @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
  24297. */
  24298. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24299. var _this = this;
  24300. return this._internalMultiPick(function (world) {
  24301. if (!_this._pickWithRayInverseMatrix) {
  24302. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24303. }
  24304. world.invertToRef(_this._pickWithRayInverseMatrix);
  24305. if (!_this._cachedRayForTransform) {
  24306. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24307. }
  24308. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24309. return _this._cachedRayForTransform;
  24310. }, predicate);
  24311. };
  24312. Scene.prototype.setPointerOverMesh = function (mesh) {
  24313. if (this._pointerOverMesh === mesh) {
  24314. return;
  24315. }
  24316. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24317. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24318. }
  24319. this._pointerOverMesh = mesh;
  24320. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24321. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24322. }
  24323. };
  24324. Scene.prototype.getPointerOverMesh = function () {
  24325. return this._pointerOverMesh;
  24326. };
  24327. Scene.prototype.setPointerOverSprite = function (sprite) {
  24328. if (this._pointerOverSprite === sprite) {
  24329. return;
  24330. }
  24331. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24332. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24333. }
  24334. this._pointerOverSprite = sprite;
  24335. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24336. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24337. }
  24338. };
  24339. Scene.prototype.getPointerOverSprite = function () {
  24340. return this._pointerOverSprite;
  24341. };
  24342. // Physics
  24343. Scene.prototype.getPhysicsEngine = function () {
  24344. return this._physicsEngine;
  24345. };
  24346. /**
  24347. * Enables physics to the current scene
  24348. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24349. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24350. * @return {boolean} was the physics engine initialized
  24351. */
  24352. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24353. if (gravity === void 0) { gravity = null; }
  24354. if (this._physicsEngine) {
  24355. return true;
  24356. }
  24357. try {
  24358. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24359. return true;
  24360. }
  24361. catch (e) {
  24362. BABYLON.Tools.Error(e.message);
  24363. return false;
  24364. }
  24365. };
  24366. Scene.prototype.disablePhysicsEngine = function () {
  24367. if (!this._physicsEngine) {
  24368. return;
  24369. }
  24370. this._physicsEngine.dispose();
  24371. this._physicsEngine = null;
  24372. };
  24373. Scene.prototype.isPhysicsEnabled = function () {
  24374. return this._physicsEngine !== undefined;
  24375. };
  24376. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24377. var mesh = compound.parts[0].mesh;
  24378. if (mesh.physicsImpostor) {
  24379. mesh.physicsImpostor.dispose();
  24380. mesh.physicsImpostor = null;
  24381. }
  24382. };
  24383. // Misc.
  24384. Scene.prototype._rebuildGeometries = function () {
  24385. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24386. var geometry = _a[_i];
  24387. geometry._rebuild();
  24388. }
  24389. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24390. var mesh = _c[_b];
  24391. mesh._rebuild();
  24392. }
  24393. if (this.postProcessManager) {
  24394. this.postProcessManager._rebuild();
  24395. }
  24396. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24397. var layer = _e[_d];
  24398. layer._rebuild();
  24399. }
  24400. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  24401. var highlightLayer = _g[_f];
  24402. highlightLayer._rebuild();
  24403. }
  24404. if (this._boundingBoxRenderer) {
  24405. this._boundingBoxRenderer._rebuild();
  24406. }
  24407. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24408. var system = _j[_h];
  24409. system.rebuild();
  24410. }
  24411. if (this._postProcessRenderPipelineManager) {
  24412. this._postProcessRenderPipelineManager._rebuild();
  24413. }
  24414. };
  24415. Scene.prototype._rebuildTextures = function () {
  24416. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24417. var texture = _a[_i];
  24418. texture._rebuild();
  24419. }
  24420. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24421. };
  24422. /**
  24423. * Creates a default light for the scene.
  24424. * @param replace Whether to replace the existing lights in the scene.
  24425. */
  24426. Scene.prototype.createDefaultLight = function (replace) {
  24427. if (replace === void 0) { replace = false; }
  24428. // Dispose existing light in replace mode.
  24429. if (replace) {
  24430. if (this.lights) {
  24431. for (var i = 0; i < this.lights.length; i++) {
  24432. this.lights[i].dispose();
  24433. }
  24434. }
  24435. }
  24436. // Light
  24437. if (this.lights.length === 0) {
  24438. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24439. }
  24440. };
  24441. /**
  24442. * Creates a default camera for the scene.
  24443. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24444. * @param replace Whether to replace the existing active camera in the scene.
  24445. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24446. */
  24447. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24448. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24449. if (replace === void 0) { replace = false; }
  24450. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24451. // Dispose existing camera in replace mode.
  24452. if (replace) {
  24453. if (this.activeCamera) {
  24454. this.activeCamera.dispose();
  24455. this.activeCamera = null;
  24456. }
  24457. }
  24458. // Camera
  24459. if (!this.activeCamera) {
  24460. var worldExtends = this.getWorldExtends();
  24461. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24462. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24463. var camera;
  24464. var radius = worldSize.length() * 1.5;
  24465. if (createArcRotateCamera) {
  24466. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24467. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24468. arcRotateCamera.wheelPrecision = 100 / radius;
  24469. camera = arcRotateCamera;
  24470. }
  24471. else {
  24472. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24473. freeCamera.setTarget(worldCenter);
  24474. camera = freeCamera;
  24475. }
  24476. camera.minZ = radius * 0.01;
  24477. camera.maxZ = radius * 1000;
  24478. camera.speed = radius * 0.2;
  24479. this.activeCamera = camera;
  24480. var canvas = this.getEngine().getRenderingCanvas();
  24481. if (attachCameraControls && canvas) {
  24482. camera.attachControl(canvas);
  24483. }
  24484. }
  24485. };
  24486. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24487. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24488. if (replace === void 0) { replace = false; }
  24489. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24490. this.createDefaultLight(replace);
  24491. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24492. };
  24493. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24494. if (pbr === void 0) { pbr = false; }
  24495. if (scale === void 0) { scale = 1000; }
  24496. if (blur === void 0) { blur = 0; }
  24497. if (environmentTexture) {
  24498. this.environmentTexture = environmentTexture;
  24499. }
  24500. if (!this.environmentTexture) {
  24501. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24502. return null;
  24503. }
  24504. // Skybox
  24505. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24506. if (pbr) {
  24507. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24508. hdrSkyboxMaterial.backFaceCulling = false;
  24509. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24510. if (hdrSkyboxMaterial.reflectionTexture) {
  24511. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24512. }
  24513. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24514. hdrSkyboxMaterial.disableLighting = true;
  24515. hdrSkyboxMaterial.twoSidedLighting = true;
  24516. hdrSkybox.infiniteDistance = true;
  24517. hdrSkybox.material = hdrSkyboxMaterial;
  24518. }
  24519. else {
  24520. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24521. skyboxMaterial.backFaceCulling = false;
  24522. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24523. if (skyboxMaterial.reflectionTexture) {
  24524. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24525. }
  24526. skyboxMaterial.disableLighting = true;
  24527. hdrSkybox.infiniteDistance = true;
  24528. hdrSkybox.material = skyboxMaterial;
  24529. }
  24530. return hdrSkybox;
  24531. };
  24532. Scene.prototype.createDefaultEnvironment = function (options) {
  24533. if (BABYLON.EnvironmentHelper) {
  24534. return new BABYLON.EnvironmentHelper(options, this);
  24535. }
  24536. return null;
  24537. };
  24538. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24539. if (webVROptions === void 0) { webVROptions = {}; }
  24540. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24541. };
  24542. // Tags
  24543. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24544. if (tagsQuery === undefined) {
  24545. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24546. return list;
  24547. }
  24548. var listByTags = [];
  24549. forEach = forEach || (function (item) { return; });
  24550. for (var i in list) {
  24551. var item = list[i];
  24552. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24553. listByTags.push(item);
  24554. forEach(item);
  24555. }
  24556. }
  24557. return listByTags;
  24558. };
  24559. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24560. return this._getByTags(this.meshes, tagsQuery, forEach);
  24561. };
  24562. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24563. return this._getByTags(this.cameras, tagsQuery, forEach);
  24564. };
  24565. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24566. return this._getByTags(this.lights, tagsQuery, forEach);
  24567. };
  24568. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24569. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24570. };
  24571. /**
  24572. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24573. * This allowed control for front to back rendering or reversly depending of the special needs.
  24574. *
  24575. * @param renderingGroupId The rendering group id corresponding to its index
  24576. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24577. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24578. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24579. */
  24580. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24581. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24582. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24583. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24584. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24585. };
  24586. /**
  24587. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24588. *
  24589. * @param renderingGroupId The rendering group id corresponding to its index
  24590. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24591. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24592. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24593. */
  24594. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24595. if (depth === void 0) { depth = true; }
  24596. if (stencil === void 0) { stencil = true; }
  24597. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24598. };
  24599. /**
  24600. * Will flag all materials as dirty to trigger new shader compilation
  24601. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24602. */
  24603. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24604. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24605. var material = _a[_i];
  24606. if (predicate && !predicate(material)) {
  24607. continue;
  24608. }
  24609. material.markAsDirty(flag);
  24610. }
  24611. };
  24612. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24613. var _this = this;
  24614. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24615. this._activeRequests.push(request);
  24616. request.onCompleteObservable.add(function (request) {
  24617. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24618. });
  24619. return request;
  24620. };
  24621. /** @ignore */
  24622. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24623. var _this = this;
  24624. return new Promise(function (resolve, reject) {
  24625. _this._loadFile(url, function (data) {
  24626. resolve(data);
  24627. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24628. reject(exception);
  24629. });
  24630. });
  24631. };
  24632. // Statics
  24633. Scene._FOGMODE_NONE = 0;
  24634. Scene._FOGMODE_EXP = 1;
  24635. Scene._FOGMODE_EXP2 = 2;
  24636. Scene._FOGMODE_LINEAR = 3;
  24637. Scene._uniqueIdCounter = 0;
  24638. Scene.MinDeltaTime = 1.0;
  24639. Scene.MaxDeltaTime = 1000.0;
  24640. /** The distance in pixel that you have to move to prevent some events */
  24641. Scene.DragMovementThreshold = 10; // in pixels
  24642. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24643. Scene.LongPressDelay = 500; // in milliseconds
  24644. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24645. Scene.DoubleClickDelay = 300; // in milliseconds
  24646. /** If you need to check double click without raising a single click at first click, enable this flag */
  24647. Scene.ExclusiveDoubleClickMode = false;
  24648. return Scene;
  24649. }());
  24650. BABYLON.Scene = Scene;
  24651. })(BABYLON || (BABYLON = {}));
  24652. //# sourceMappingURL=babylon.scene.js.map
  24653. var BABYLON;
  24654. (function (BABYLON) {
  24655. /**
  24656. * Set of assets to keep when moving a scene into an asset container.
  24657. */
  24658. var KeepAssets = /** @class */ (function () {
  24659. function KeepAssets() {
  24660. /**
  24661. * Cameras to keep.
  24662. */
  24663. this.cameras = new Array();
  24664. /**
  24665. * Lights to keep.
  24666. */
  24667. this.lights = new Array();
  24668. /**
  24669. * Meshes to keep.
  24670. */
  24671. this.meshes = new Array();
  24672. /**
  24673. * Skeletons to keep.
  24674. */
  24675. this.skeletons = new Array();
  24676. /**
  24677. * ParticleSystems to keep.
  24678. */
  24679. this.particleSystems = new Array();
  24680. /**
  24681. * Animations to keep.
  24682. */
  24683. this.animations = new Array();
  24684. /**
  24685. * MultiMaterials to keep.
  24686. */
  24687. this.multiMaterials = new Array();
  24688. /**
  24689. * Materials to keep.
  24690. */
  24691. this.materials = new Array();
  24692. /**
  24693. * MorphTargetManagers to keep.
  24694. */
  24695. this.morphTargetManagers = new Array();
  24696. /**
  24697. * Geometries to keep.
  24698. */
  24699. this.geometries = new Array();
  24700. /**
  24701. * TransformNodes to keep.
  24702. */
  24703. this.transformNodes = new Array();
  24704. /**
  24705. * LensFlareSystems to keep.
  24706. */
  24707. this.lensFlareSystems = new Array();
  24708. /**
  24709. * ShadowGenerators to keep.
  24710. */
  24711. this.shadowGenerators = new Array();
  24712. /**
  24713. * ActionManagers to keep.
  24714. */
  24715. this.actionManagers = new Array();
  24716. /**
  24717. * Sounds to keep.
  24718. */
  24719. this.sounds = new Array();
  24720. }
  24721. return KeepAssets;
  24722. }());
  24723. BABYLON.KeepAssets = KeepAssets;
  24724. /**
  24725. * Container with a set of assets that can be added or removed from a scene.
  24726. */
  24727. var AssetContainer = /** @class */ (function () {
  24728. /**
  24729. * Instantiates an AssetContainer.
  24730. * @param scene The scene the AssetContainer belongs to.
  24731. */
  24732. function AssetContainer(scene) {
  24733. // Objects
  24734. /**
  24735. * Cameras populated in the container.
  24736. */
  24737. this.cameras = new Array();
  24738. /**
  24739. * Lights populated in the container.
  24740. */
  24741. this.lights = new Array();
  24742. /**
  24743. * Meshes populated in the container.
  24744. */
  24745. this.meshes = new Array();
  24746. /**
  24747. * Skeletons populated in the container.
  24748. */
  24749. this.skeletons = new Array();
  24750. /**
  24751. * ParticleSystems populated in the container.
  24752. */
  24753. this.particleSystems = new Array();
  24754. /**
  24755. * Animations populated in the container.
  24756. */
  24757. this.animations = new Array();
  24758. /**
  24759. * MultiMaterials populated in the container.
  24760. */
  24761. this.multiMaterials = new Array();
  24762. /**
  24763. * Materials populated in the container.
  24764. */
  24765. this.materials = new Array();
  24766. /**
  24767. * MorphTargetManagers populated in the container.
  24768. */
  24769. this.morphTargetManagers = new Array();
  24770. /**
  24771. * Geometries populated in the container.
  24772. */
  24773. this.geometries = new Array();
  24774. /**
  24775. * TransformNodes populated in the container.
  24776. */
  24777. this.transformNodes = new Array();
  24778. /**
  24779. * LensFlareSystems populated in the container.
  24780. */
  24781. this.lensFlareSystems = new Array();
  24782. /**
  24783. * ShadowGenerators populated in the container.
  24784. */
  24785. this.shadowGenerators = new Array();
  24786. /**
  24787. * ActionManagers populated in the container.
  24788. */
  24789. this.actionManagers = new Array();
  24790. /**
  24791. * Sounds populated in the container.
  24792. */
  24793. this.sounds = new Array();
  24794. this.scene = scene;
  24795. }
  24796. /**
  24797. * Adds all the assets from the container to the scene.
  24798. */
  24799. AssetContainer.prototype.addAllToScene = function () {
  24800. var _this = this;
  24801. this.cameras.forEach(function (o) {
  24802. _this.scene.addCamera(o);
  24803. });
  24804. this.lights.forEach(function (o) {
  24805. _this.scene.addLight(o);
  24806. });
  24807. this.meshes.forEach(function (o) {
  24808. _this.scene.addMesh(o);
  24809. });
  24810. this.skeletons.forEach(function (o) {
  24811. _this.scene.addSkeleton(o);
  24812. });
  24813. this.particleSystems.forEach(function (o) {
  24814. _this.scene.addParticleSystem(o);
  24815. });
  24816. this.animations.forEach(function (o) {
  24817. _this.scene.addAnimation(o);
  24818. });
  24819. this.multiMaterials.forEach(function (o) {
  24820. _this.scene.addMultiMaterial(o);
  24821. });
  24822. this.materials.forEach(function (o) {
  24823. _this.scene.addMaterial(o);
  24824. });
  24825. this.morphTargetManagers.forEach(function (o) {
  24826. _this.scene.addMorphTargetManager(o);
  24827. });
  24828. this.geometries.forEach(function (o) {
  24829. _this.scene.addGeometry(o);
  24830. });
  24831. this.transformNodes.forEach(function (o) {
  24832. _this.scene.addTransformNode(o);
  24833. });
  24834. this.lensFlareSystems.forEach(function (o) {
  24835. _this.scene.addLensFlareSystem(o);
  24836. });
  24837. this.actionManagers.forEach(function (o) {
  24838. _this.scene.addActionManager(o);
  24839. });
  24840. this.sounds.forEach(function (o) {
  24841. o.play();
  24842. o.autoplay = true;
  24843. _this.scene.mainSoundTrack.AddSound(o);
  24844. });
  24845. };
  24846. /**
  24847. * Removes all the assets in the container from the scene
  24848. */
  24849. AssetContainer.prototype.removeAllFromScene = function () {
  24850. var _this = this;
  24851. this.cameras.forEach(function (o) {
  24852. _this.scene.removeCamera(o);
  24853. });
  24854. this.lights.forEach(function (o) {
  24855. _this.scene.removeLight(o);
  24856. });
  24857. this.meshes.forEach(function (o) {
  24858. _this.scene.removeMesh(o);
  24859. });
  24860. this.skeletons.forEach(function (o) {
  24861. _this.scene.removeSkeleton(o);
  24862. });
  24863. this.particleSystems.forEach(function (o) {
  24864. _this.scene.removeParticleSystem(o);
  24865. });
  24866. this.animations.forEach(function (o) {
  24867. _this.scene.removeAnimation(o);
  24868. });
  24869. this.multiMaterials.forEach(function (o) {
  24870. _this.scene.removeMultiMaterial(o);
  24871. });
  24872. this.materials.forEach(function (o) {
  24873. _this.scene.removeMaterial(o);
  24874. });
  24875. this.morphTargetManagers.forEach(function (o) {
  24876. _this.scene.removeMorphTargetManager(o);
  24877. });
  24878. this.geometries.forEach(function (o) {
  24879. _this.scene.removeGeometry(o);
  24880. });
  24881. this.transformNodes.forEach(function (o) {
  24882. _this.scene.removeTransformNode(o);
  24883. });
  24884. this.lensFlareSystems.forEach(function (o) {
  24885. _this.scene.removeLensFlareSystem(o);
  24886. });
  24887. this.actionManagers.forEach(function (o) {
  24888. _this.scene.removeActionManager(o);
  24889. });
  24890. this.sounds.forEach(function (o) {
  24891. o.stop();
  24892. o.autoplay = false;
  24893. _this.scene.mainSoundTrack.RemoveSound(o);
  24894. });
  24895. };
  24896. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24897. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24898. var asset = sourceAssets_1[_i];
  24899. var move = true;
  24900. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24901. var keepAsset = keepAssets_1[_a];
  24902. if (asset === keepAsset) {
  24903. move = false;
  24904. break;
  24905. }
  24906. }
  24907. if (move) {
  24908. targetAssets.push(asset);
  24909. }
  24910. }
  24911. };
  24912. /**
  24913. * Removes all the assets contained in the scene and adds them to the container.
  24914. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24915. */
  24916. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24917. if (keepAssets === undefined) {
  24918. keepAssets = new KeepAssets();
  24919. }
  24920. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24921. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24922. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24923. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24924. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  24925. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  24926. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  24927. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  24928. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  24929. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  24930. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  24931. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  24932. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  24933. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  24934. this.removeAllFromScene();
  24935. };
  24936. return AssetContainer;
  24937. }());
  24938. BABYLON.AssetContainer = AssetContainer;
  24939. })(BABYLON || (BABYLON = {}));
  24940. //# sourceMappingURL=babylon.assetContainer.js.map
  24941. var BABYLON;
  24942. (function (BABYLON) {
  24943. var Buffer = /** @class */ (function () {
  24944. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24945. if (instanced === void 0) { instanced = false; }
  24946. if (engine instanceof BABYLON.Mesh) {
  24947. this._engine = engine.getScene().getEngine();
  24948. }
  24949. else {
  24950. this._engine = engine;
  24951. }
  24952. this._updatable = updatable;
  24953. this._data = data;
  24954. this._strideSize = stride;
  24955. if (!postponeInternalCreation) {
  24956. this.create();
  24957. }
  24958. this._instanced = instanced;
  24959. this._instanceDivisor = instanced ? 1 : 0;
  24960. }
  24961. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24962. // a lot of these parameters are ignored as they are overriden by the buffer
  24963. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24964. };
  24965. // Properties
  24966. Buffer.prototype.isUpdatable = function () {
  24967. return this._updatable;
  24968. };
  24969. Buffer.prototype.getData = function () {
  24970. return this._data;
  24971. };
  24972. Buffer.prototype.getBuffer = function () {
  24973. return this._buffer;
  24974. };
  24975. Buffer.prototype.getStrideSize = function () {
  24976. return this._strideSize;
  24977. };
  24978. Buffer.prototype.getIsInstanced = function () {
  24979. return this._instanced;
  24980. };
  24981. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24982. get: function () {
  24983. return this._instanceDivisor;
  24984. },
  24985. set: function (value) {
  24986. this._instanceDivisor = value;
  24987. if (value == 0) {
  24988. this._instanced = false;
  24989. }
  24990. else {
  24991. this._instanced = true;
  24992. }
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. // Methods
  24998. Buffer.prototype.create = function (data) {
  24999. if (data === void 0) { data = null; }
  25000. if (!data && this._buffer) {
  25001. return; // nothing to do
  25002. }
  25003. data = data || this._data;
  25004. if (!data) {
  25005. return;
  25006. }
  25007. if (!this._buffer) {
  25008. if (this._updatable) {
  25009. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25010. this._data = data;
  25011. }
  25012. else {
  25013. this._buffer = this._engine.createVertexBuffer(data);
  25014. }
  25015. }
  25016. else if (this._updatable) {
  25017. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25018. this._data = data;
  25019. }
  25020. };
  25021. Buffer.prototype._rebuild = function () {
  25022. this._buffer = null;
  25023. this.create(this._data);
  25024. };
  25025. Buffer.prototype.update = function (data) {
  25026. this.create(data);
  25027. };
  25028. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25029. if (!this._buffer) {
  25030. return;
  25031. }
  25032. if (this._updatable) {
  25033. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25034. this._data = null;
  25035. }
  25036. };
  25037. Buffer.prototype.dispose = function () {
  25038. if (!this._buffer) {
  25039. return;
  25040. }
  25041. if (this._engine._releaseBuffer(this._buffer)) {
  25042. this._buffer = null;
  25043. }
  25044. };
  25045. return Buffer;
  25046. }());
  25047. BABYLON.Buffer = Buffer;
  25048. })(BABYLON || (BABYLON = {}));
  25049. //# sourceMappingURL=babylon.buffer.js.map
  25050. var BABYLON;
  25051. (function (BABYLON) {
  25052. var VertexBuffer = /** @class */ (function () {
  25053. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25054. if (!stride) {
  25055. // Deduce stride from kind
  25056. switch (kind) {
  25057. case VertexBuffer.PositionKind:
  25058. stride = 3;
  25059. break;
  25060. case VertexBuffer.NormalKind:
  25061. stride = 3;
  25062. break;
  25063. case VertexBuffer.UVKind:
  25064. case VertexBuffer.UV2Kind:
  25065. case VertexBuffer.UV3Kind:
  25066. case VertexBuffer.UV4Kind:
  25067. case VertexBuffer.UV5Kind:
  25068. case VertexBuffer.UV6Kind:
  25069. stride = 2;
  25070. break;
  25071. case VertexBuffer.TangentKind:
  25072. case VertexBuffer.ColorKind:
  25073. stride = 4;
  25074. break;
  25075. case VertexBuffer.MatricesIndicesKind:
  25076. case VertexBuffer.MatricesIndicesExtraKind:
  25077. stride = 4;
  25078. break;
  25079. case VertexBuffer.MatricesWeightsKind:
  25080. case VertexBuffer.MatricesWeightsExtraKind:
  25081. default:
  25082. stride = 4;
  25083. break;
  25084. }
  25085. }
  25086. if (data instanceof BABYLON.Buffer) {
  25087. if (!stride) {
  25088. stride = data.getStrideSize();
  25089. }
  25090. this._buffer = data;
  25091. this._ownsBuffer = false;
  25092. }
  25093. else {
  25094. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25095. this._ownsBuffer = true;
  25096. }
  25097. this._stride = stride;
  25098. this._offset = offset ? offset : 0;
  25099. this._size = size ? size : stride;
  25100. this._kind = kind;
  25101. }
  25102. VertexBuffer.prototype._rebuild = function () {
  25103. if (!this._buffer) {
  25104. return;
  25105. }
  25106. this._buffer._rebuild();
  25107. };
  25108. /**
  25109. * Returns the kind of the VertexBuffer (string).
  25110. */
  25111. VertexBuffer.prototype.getKind = function () {
  25112. return this._kind;
  25113. };
  25114. // Properties
  25115. /**
  25116. * Boolean : is the VertexBuffer updatable ?
  25117. */
  25118. VertexBuffer.prototype.isUpdatable = function () {
  25119. return this._buffer.isUpdatable();
  25120. };
  25121. /**
  25122. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25123. */
  25124. VertexBuffer.prototype.getData = function () {
  25125. return this._buffer.getData();
  25126. };
  25127. /**
  25128. * Returns the WebGLBuffer associated to the VertexBuffer.
  25129. */
  25130. VertexBuffer.prototype.getBuffer = function () {
  25131. return this._buffer.getBuffer();
  25132. };
  25133. /**
  25134. * Returns the stride of the VertexBuffer (integer).
  25135. */
  25136. VertexBuffer.prototype.getStrideSize = function () {
  25137. return this._stride;
  25138. };
  25139. /**
  25140. * Returns the offset (integer).
  25141. */
  25142. VertexBuffer.prototype.getOffset = function () {
  25143. return this._offset;
  25144. };
  25145. /**
  25146. * Returns the VertexBuffer total size (integer).
  25147. */
  25148. VertexBuffer.prototype.getSize = function () {
  25149. return this._size;
  25150. };
  25151. /**
  25152. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25153. */
  25154. VertexBuffer.prototype.getIsInstanced = function () {
  25155. return this._buffer.getIsInstanced();
  25156. };
  25157. /**
  25158. * Returns the instancing divisor, zero for non-instanced (integer).
  25159. */
  25160. VertexBuffer.prototype.getInstanceDivisor = function () {
  25161. return this._buffer.instanceDivisor;
  25162. };
  25163. // Methods
  25164. /**
  25165. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25166. * Returns the created WebGLBuffer.
  25167. */
  25168. VertexBuffer.prototype.create = function (data) {
  25169. return this._buffer.create(data);
  25170. };
  25171. /**
  25172. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25173. * This function will create a new buffer if the current one is not updatable
  25174. * Returns the updated WebGLBuffer.
  25175. */
  25176. VertexBuffer.prototype.update = function (data) {
  25177. return this._buffer.update(data);
  25178. };
  25179. /**
  25180. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25181. * Returns the directly updated WebGLBuffer.
  25182. */
  25183. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25184. return this._buffer.updateDirectly(data, offset);
  25185. };
  25186. /**
  25187. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25188. */
  25189. VertexBuffer.prototype.dispose = function () {
  25190. if (this._ownsBuffer) {
  25191. this._buffer.dispose();
  25192. }
  25193. };
  25194. Object.defineProperty(VertexBuffer, "PositionKind", {
  25195. get: function () {
  25196. return VertexBuffer._PositionKind;
  25197. },
  25198. enumerable: true,
  25199. configurable: true
  25200. });
  25201. Object.defineProperty(VertexBuffer, "NormalKind", {
  25202. get: function () {
  25203. return VertexBuffer._NormalKind;
  25204. },
  25205. enumerable: true,
  25206. configurable: true
  25207. });
  25208. Object.defineProperty(VertexBuffer, "TangentKind", {
  25209. get: function () {
  25210. return VertexBuffer._TangentKind;
  25211. },
  25212. enumerable: true,
  25213. configurable: true
  25214. });
  25215. Object.defineProperty(VertexBuffer, "UVKind", {
  25216. get: function () {
  25217. return VertexBuffer._UVKind;
  25218. },
  25219. enumerable: true,
  25220. configurable: true
  25221. });
  25222. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25223. get: function () {
  25224. return VertexBuffer._UV2Kind;
  25225. },
  25226. enumerable: true,
  25227. configurable: true
  25228. });
  25229. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25230. get: function () {
  25231. return VertexBuffer._UV3Kind;
  25232. },
  25233. enumerable: true,
  25234. configurable: true
  25235. });
  25236. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25237. get: function () {
  25238. return VertexBuffer._UV4Kind;
  25239. },
  25240. enumerable: true,
  25241. configurable: true
  25242. });
  25243. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25244. get: function () {
  25245. return VertexBuffer._UV5Kind;
  25246. },
  25247. enumerable: true,
  25248. configurable: true
  25249. });
  25250. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25251. get: function () {
  25252. return VertexBuffer._UV6Kind;
  25253. },
  25254. enumerable: true,
  25255. configurable: true
  25256. });
  25257. Object.defineProperty(VertexBuffer, "ColorKind", {
  25258. get: function () {
  25259. return VertexBuffer._ColorKind;
  25260. },
  25261. enumerable: true,
  25262. configurable: true
  25263. });
  25264. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25265. get: function () {
  25266. return VertexBuffer._MatricesIndicesKind;
  25267. },
  25268. enumerable: true,
  25269. configurable: true
  25270. });
  25271. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25272. get: function () {
  25273. return VertexBuffer._MatricesWeightsKind;
  25274. },
  25275. enumerable: true,
  25276. configurable: true
  25277. });
  25278. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25279. get: function () {
  25280. return VertexBuffer._MatricesIndicesExtraKind;
  25281. },
  25282. enumerable: true,
  25283. configurable: true
  25284. });
  25285. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25286. get: function () {
  25287. return VertexBuffer._MatricesWeightsExtraKind;
  25288. },
  25289. enumerable: true,
  25290. configurable: true
  25291. });
  25292. // Enums
  25293. VertexBuffer._PositionKind = "position";
  25294. VertexBuffer._NormalKind = "normal";
  25295. VertexBuffer._TangentKind = "tangent";
  25296. VertexBuffer._UVKind = "uv";
  25297. VertexBuffer._UV2Kind = "uv2";
  25298. VertexBuffer._UV3Kind = "uv3";
  25299. VertexBuffer._UV4Kind = "uv4";
  25300. VertexBuffer._UV5Kind = "uv5";
  25301. VertexBuffer._UV6Kind = "uv6";
  25302. VertexBuffer._ColorKind = "color";
  25303. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25304. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25305. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25306. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25307. return VertexBuffer;
  25308. }());
  25309. BABYLON.VertexBuffer = VertexBuffer;
  25310. })(BABYLON || (BABYLON = {}));
  25311. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25312. var BABYLON;
  25313. (function (BABYLON) {
  25314. /**
  25315. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25316. */
  25317. var DummyInternalTextureTracker = /** @class */ (function () {
  25318. function DummyInternalTextureTracker() {
  25319. /**
  25320. * Gets or set the previous tracker in the list
  25321. */
  25322. this.previous = null;
  25323. /**
  25324. * Gets or set the next tracker in the list
  25325. */
  25326. this.next = null;
  25327. }
  25328. return DummyInternalTextureTracker;
  25329. }());
  25330. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25331. })(BABYLON || (BABYLON = {}));
  25332. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25333. var BABYLON;
  25334. (function (BABYLON) {
  25335. /**
  25336. * Class used to store data associated with WebGL texture data for the engine
  25337. * This class should not be used directly
  25338. */
  25339. var InternalTexture = /** @class */ (function () {
  25340. /**
  25341. * Creates a new InternalTexture
  25342. * @param engine defines the engine to use
  25343. * @param dataSource defines the type of data that will be used
  25344. */
  25345. function InternalTexture(engine, dataSource) {
  25346. /**
  25347. * Observable called when the texture is loaded
  25348. */
  25349. this.onLoadedObservable = new BABYLON.Observable();
  25350. /**
  25351. * Gets or set the previous tracker in the list
  25352. */
  25353. this.previous = null;
  25354. /**
  25355. * Gets or set the next tracker in the list
  25356. */
  25357. this.next = null;
  25358. // Private
  25359. /** @ignore */
  25360. this._initialSlot = -1;
  25361. /** @ignore */
  25362. this._designatedSlot = -1;
  25363. /** @ignore */
  25364. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25365. /** @ignore */
  25366. this._references = 1;
  25367. this._engine = engine;
  25368. this._dataSource = dataSource;
  25369. this._webGLTexture = engine._createTexture();
  25370. }
  25371. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25372. /**
  25373. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25374. */
  25375. get: function () {
  25376. return this._dataSource;
  25377. },
  25378. enumerable: true,
  25379. configurable: true
  25380. });
  25381. /**
  25382. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25383. */
  25384. InternalTexture.prototype.incrementReferences = function () {
  25385. this._references++;
  25386. };
  25387. /**
  25388. * Change the size of the texture (not the size of the content)
  25389. * @param width defines the new width
  25390. * @param height defines the new height
  25391. * @param depth defines the new depth (1 by default)
  25392. */
  25393. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25394. if (depth === void 0) { depth = 1; }
  25395. this.width = width;
  25396. this.height = height;
  25397. this.depth = depth;
  25398. this.baseWidth = width;
  25399. this.baseHeight = height;
  25400. this.baseDepth = depth;
  25401. this._size = width * height * depth;
  25402. };
  25403. /** @ignore */
  25404. InternalTexture.prototype._rebuild = function () {
  25405. var _this = this;
  25406. var proxy;
  25407. this.isReady = false;
  25408. this._cachedCoordinatesMode = null;
  25409. this._cachedWrapU = null;
  25410. this._cachedWrapV = null;
  25411. this._cachedAnisotropicFilteringLevel = null;
  25412. switch (this._dataSource) {
  25413. case InternalTexture.DATASOURCE_TEMP:
  25414. return;
  25415. case InternalTexture.DATASOURCE_URL:
  25416. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25417. _this.isReady = true;
  25418. }, null, this._buffer, undefined, this.format);
  25419. proxy._swapAndDie(this);
  25420. return;
  25421. case InternalTexture.DATASOURCE_RAW:
  25422. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25423. proxy._swapAndDie(this);
  25424. this.isReady = true;
  25425. return;
  25426. case InternalTexture.DATASOURCE_RAW3D:
  25427. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25428. proxy._swapAndDie(this);
  25429. this.isReady = true;
  25430. return;
  25431. case InternalTexture.DATASOURCE_DYNAMIC:
  25432. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25433. proxy._swapAndDie(this);
  25434. // The engine will make sure to update content so no need to flag it as isReady = true
  25435. return;
  25436. case InternalTexture.DATASOURCE_RENDERTARGET:
  25437. var options = new BABYLON.RenderTargetCreationOptions();
  25438. options.generateDepthBuffer = this._generateDepthBuffer;
  25439. options.generateMipMaps = this.generateMipMaps;
  25440. options.generateStencilBuffer = this._generateStencilBuffer;
  25441. options.samplingMode = this.samplingMode;
  25442. options.type = this.type;
  25443. if (this.isCube) {
  25444. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25445. }
  25446. else {
  25447. var size = {
  25448. width: this.width,
  25449. height: this.height
  25450. };
  25451. proxy = this._engine.createRenderTargetTexture(size, options);
  25452. }
  25453. proxy._swapAndDie(this);
  25454. this.isReady = true;
  25455. return;
  25456. case InternalTexture.DATASOURCE_CUBE:
  25457. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25458. _this.isReady = true;
  25459. }, null, this.format, this._extension);
  25460. proxy._swapAndDie(this);
  25461. return;
  25462. case InternalTexture.DATASOURCE_CUBERAW:
  25463. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25464. proxy._swapAndDie(this);
  25465. this.isReady = true;
  25466. return;
  25467. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25468. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25469. if (proxy) {
  25470. proxy._swapAndDie(_this);
  25471. }
  25472. _this.isReady = true;
  25473. }, null, this.format, this._extension);
  25474. return;
  25475. }
  25476. };
  25477. InternalTexture.prototype._swapAndDie = function (target) {
  25478. target._webGLTexture = this._webGLTexture;
  25479. if (this._framebuffer) {
  25480. target._framebuffer = this._framebuffer;
  25481. }
  25482. if (this._depthStencilBuffer) {
  25483. target._depthStencilBuffer = this._depthStencilBuffer;
  25484. }
  25485. if (this._lodTextureHigh) {
  25486. if (target._lodTextureHigh) {
  25487. target._lodTextureHigh.dispose();
  25488. }
  25489. target._lodTextureHigh = this._lodTextureHigh;
  25490. }
  25491. if (this._lodTextureMid) {
  25492. if (target._lodTextureMid) {
  25493. target._lodTextureMid.dispose();
  25494. }
  25495. target._lodTextureMid = this._lodTextureMid;
  25496. }
  25497. if (this._lodTextureLow) {
  25498. if (target._lodTextureLow) {
  25499. target._lodTextureLow.dispose();
  25500. }
  25501. target._lodTextureLow = this._lodTextureLow;
  25502. }
  25503. var cache = this._engine.getLoadedTexturesCache();
  25504. var index = cache.indexOf(this);
  25505. if (index !== -1) {
  25506. cache.splice(index, 1);
  25507. }
  25508. };
  25509. /**
  25510. * Dispose the current allocated resources
  25511. */
  25512. InternalTexture.prototype.dispose = function () {
  25513. if (!this._webGLTexture) {
  25514. return;
  25515. }
  25516. this._references--;
  25517. if (this._references === 0) {
  25518. this._engine._releaseTexture(this);
  25519. this._webGLTexture = null;
  25520. this.previous = null;
  25521. this.next = null;
  25522. }
  25523. };
  25524. /**
  25525. * The source of the texture data is unknown
  25526. */
  25527. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25528. /**
  25529. * Texture data comes from an URL
  25530. */
  25531. InternalTexture.DATASOURCE_URL = 1;
  25532. /**
  25533. * Texture data is only used for temporary storage
  25534. */
  25535. InternalTexture.DATASOURCE_TEMP = 2;
  25536. /**
  25537. * Texture data comes from raw data (ArrayBuffer)
  25538. */
  25539. InternalTexture.DATASOURCE_RAW = 3;
  25540. /**
  25541. * Texture content is dynamic (video or dynamic texture)
  25542. */
  25543. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25544. /**
  25545. * Texture content is generated by rendering to it
  25546. */
  25547. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25548. /**
  25549. * Texture content is part of a multi render target process
  25550. */
  25551. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25552. /**
  25553. * Texture data comes from a cube data file
  25554. */
  25555. InternalTexture.DATASOURCE_CUBE = 7;
  25556. /**
  25557. * Texture data comes from a raw cube data
  25558. */
  25559. InternalTexture.DATASOURCE_CUBERAW = 8;
  25560. /**
  25561. * Texture data come from a prefiltered cube data file
  25562. */
  25563. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25564. /**
  25565. * Texture content is raw 3D data
  25566. */
  25567. InternalTexture.DATASOURCE_RAW3D = 10;
  25568. return InternalTexture;
  25569. }());
  25570. BABYLON.InternalTexture = InternalTexture;
  25571. })(BABYLON || (BABYLON = {}));
  25572. //# sourceMappingURL=babylon.internalTexture.js.map
  25573. var BABYLON;
  25574. (function (BABYLON) {
  25575. var BaseTexture = /** @class */ (function () {
  25576. function BaseTexture(scene) {
  25577. this._hasAlpha = false;
  25578. this.getAlphaFromRGB = false;
  25579. this.level = 1;
  25580. this.coordinatesIndex = 0;
  25581. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25582. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25583. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25584. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25585. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25586. this.isCube = false;
  25587. this.is3D = false;
  25588. this.gammaSpace = true;
  25589. this.invertZ = false;
  25590. this.lodLevelInAlpha = false;
  25591. this.lodGenerationOffset = 0.0;
  25592. this.lodGenerationScale = 0.8;
  25593. this.isRenderTarget = false;
  25594. this.animations = new Array();
  25595. /**
  25596. * An event triggered when the texture is disposed.
  25597. * @type {BABYLON.Observable}
  25598. */
  25599. this.onDisposeObservable = new BABYLON.Observable();
  25600. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25601. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25602. if (this._scene) {
  25603. this._scene.textures.push(this);
  25604. }
  25605. this._uid = null;
  25606. }
  25607. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25608. get: function () {
  25609. return this._hasAlpha;
  25610. },
  25611. set: function (value) {
  25612. if (this._hasAlpha === value) {
  25613. return;
  25614. }
  25615. this._hasAlpha = value;
  25616. if (this._scene) {
  25617. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25618. }
  25619. },
  25620. enumerable: true,
  25621. configurable: true
  25622. });
  25623. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25624. get: function () {
  25625. return this._coordinatesMode;
  25626. },
  25627. set: function (value) {
  25628. if (this._coordinatesMode === value) {
  25629. return;
  25630. }
  25631. this._coordinatesMode = value;
  25632. if (this._scene) {
  25633. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25634. }
  25635. },
  25636. enumerable: true,
  25637. configurable: true
  25638. });
  25639. Object.defineProperty(BaseTexture.prototype, "uid", {
  25640. get: function () {
  25641. if (!this._uid) {
  25642. this._uid = BABYLON.Tools.RandomId();
  25643. }
  25644. return this._uid;
  25645. },
  25646. enumerable: true,
  25647. configurable: true
  25648. });
  25649. BaseTexture.prototype.toString = function () {
  25650. return this.name;
  25651. };
  25652. BaseTexture.prototype.getClassName = function () {
  25653. return "BaseTexture";
  25654. };
  25655. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25656. set: function (callback) {
  25657. if (this._onDisposeObserver) {
  25658. this.onDisposeObservable.remove(this._onDisposeObserver);
  25659. }
  25660. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25661. },
  25662. enumerable: true,
  25663. configurable: true
  25664. });
  25665. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25666. get: function () {
  25667. return true;
  25668. },
  25669. enumerable: true,
  25670. configurable: true
  25671. });
  25672. BaseTexture.prototype.getScene = function () {
  25673. return this._scene;
  25674. };
  25675. BaseTexture.prototype.getTextureMatrix = function () {
  25676. return BABYLON.Matrix.IdentityReadOnly;
  25677. };
  25678. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25679. return BABYLON.Matrix.IdentityReadOnly;
  25680. };
  25681. BaseTexture.prototype.getInternalTexture = function () {
  25682. return this._texture;
  25683. };
  25684. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25685. return !this.isBlocking || this.isReady();
  25686. };
  25687. BaseTexture.prototype.isReady = function () {
  25688. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25689. this.delayLoad();
  25690. return false;
  25691. }
  25692. if (this._texture) {
  25693. return this._texture.isReady;
  25694. }
  25695. return false;
  25696. };
  25697. BaseTexture.prototype.getSize = function () {
  25698. if (this._texture && this._texture.width) {
  25699. return new BABYLON.Size(this._texture.width, this._texture.height);
  25700. }
  25701. if (this._texture && this._texture._size) {
  25702. return new BABYLON.Size(this._texture._size, this._texture._size);
  25703. }
  25704. return BABYLON.Size.Zero();
  25705. };
  25706. BaseTexture.prototype.getBaseSize = function () {
  25707. if (!this.isReady() || !this._texture)
  25708. return BABYLON.Size.Zero();
  25709. if (this._texture._size) {
  25710. return new BABYLON.Size(this._texture._size, this._texture._size);
  25711. }
  25712. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25713. };
  25714. BaseTexture.prototype.scale = function (ratio) {
  25715. };
  25716. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25717. get: function () {
  25718. return false;
  25719. },
  25720. enumerable: true,
  25721. configurable: true
  25722. });
  25723. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25724. if (!this._scene) {
  25725. return null;
  25726. }
  25727. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25728. for (var index = 0; index < texturesCache.length; index++) {
  25729. var texturesCacheEntry = texturesCache[index];
  25730. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25731. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25732. texturesCacheEntry.incrementReferences();
  25733. return texturesCacheEntry;
  25734. }
  25735. }
  25736. }
  25737. return null;
  25738. };
  25739. BaseTexture.prototype._rebuild = function () {
  25740. };
  25741. BaseTexture.prototype.delayLoad = function () {
  25742. };
  25743. BaseTexture.prototype.clone = function () {
  25744. return null;
  25745. };
  25746. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25747. get: function () {
  25748. if (!this._texture) {
  25749. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25750. }
  25751. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25752. },
  25753. enumerable: true,
  25754. configurable: true
  25755. });
  25756. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25757. get: function () {
  25758. if (!this._texture) {
  25759. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25760. }
  25761. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25762. },
  25763. enumerable: true,
  25764. configurable: true
  25765. });
  25766. BaseTexture.prototype.readPixels = function (faceIndex) {
  25767. if (faceIndex === void 0) { faceIndex = 0; }
  25768. if (!this._texture) {
  25769. return null;
  25770. }
  25771. var size = this.getSize();
  25772. var scene = this.getScene();
  25773. if (!scene) {
  25774. return null;
  25775. }
  25776. var engine = scene.getEngine();
  25777. if (this._texture.isCube) {
  25778. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25779. }
  25780. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25781. };
  25782. BaseTexture.prototype.releaseInternalTexture = function () {
  25783. if (this._texture) {
  25784. this._texture.dispose();
  25785. this._texture = null;
  25786. }
  25787. };
  25788. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25789. get: function () {
  25790. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25791. return null;
  25792. }
  25793. if (!this._texture._sphericalPolynomial) {
  25794. this._texture._sphericalPolynomial =
  25795. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25796. }
  25797. return this._texture._sphericalPolynomial;
  25798. },
  25799. set: function (value) {
  25800. if (this._texture) {
  25801. this._texture._sphericalPolynomial = value;
  25802. }
  25803. },
  25804. enumerable: true,
  25805. configurable: true
  25806. });
  25807. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25808. get: function () {
  25809. if (this._texture) {
  25810. return this._texture._lodTextureHigh;
  25811. }
  25812. return null;
  25813. },
  25814. enumerable: true,
  25815. configurable: true
  25816. });
  25817. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25818. get: function () {
  25819. if (this._texture) {
  25820. return this._texture._lodTextureMid;
  25821. }
  25822. return null;
  25823. },
  25824. enumerable: true,
  25825. configurable: true
  25826. });
  25827. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25828. get: function () {
  25829. if (this._texture) {
  25830. return this._texture._lodTextureLow;
  25831. }
  25832. return null;
  25833. },
  25834. enumerable: true,
  25835. configurable: true
  25836. });
  25837. BaseTexture.prototype.dispose = function () {
  25838. if (!this._scene) {
  25839. return;
  25840. }
  25841. // Animations
  25842. this._scene.stopAnimation(this);
  25843. // Remove from scene
  25844. this._scene._removePendingData(this);
  25845. var index = this._scene.textures.indexOf(this);
  25846. if (index >= 0) {
  25847. this._scene.textures.splice(index, 1);
  25848. }
  25849. if (this._texture === undefined) {
  25850. return;
  25851. }
  25852. // Release
  25853. this.releaseInternalTexture();
  25854. // Callback
  25855. this.onDisposeObservable.notifyObservers(this);
  25856. this.onDisposeObservable.clear();
  25857. };
  25858. BaseTexture.prototype.serialize = function () {
  25859. if (!this.name) {
  25860. return null;
  25861. }
  25862. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25863. // Animations
  25864. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25865. return serializationObject;
  25866. };
  25867. BaseTexture.WhenAllReady = function (textures, callback) {
  25868. var numRemaining = textures.length;
  25869. if (numRemaining === 0) {
  25870. callback();
  25871. return;
  25872. }
  25873. var _loop_1 = function () {
  25874. texture = textures[i];
  25875. if (texture.isReady()) {
  25876. if (--numRemaining === 0) {
  25877. callback();
  25878. }
  25879. }
  25880. else {
  25881. onLoadObservable = texture.onLoadObservable;
  25882. var onLoadCallback_1 = function () {
  25883. onLoadObservable.removeCallback(onLoadCallback_1);
  25884. if (--numRemaining === 0) {
  25885. callback();
  25886. }
  25887. };
  25888. onLoadObservable.add(onLoadCallback_1);
  25889. }
  25890. };
  25891. var texture, onLoadObservable;
  25892. for (var i = 0; i < textures.length; i++) {
  25893. _loop_1();
  25894. }
  25895. };
  25896. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25897. __decorate([
  25898. BABYLON.serialize()
  25899. ], BaseTexture.prototype, "name", void 0);
  25900. __decorate([
  25901. BABYLON.serialize("hasAlpha")
  25902. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25903. __decorate([
  25904. BABYLON.serialize()
  25905. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25906. __decorate([
  25907. BABYLON.serialize()
  25908. ], BaseTexture.prototype, "level", void 0);
  25909. __decorate([
  25910. BABYLON.serialize()
  25911. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25912. __decorate([
  25913. BABYLON.serialize("coordinatesMode")
  25914. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25915. __decorate([
  25916. BABYLON.serialize()
  25917. ], BaseTexture.prototype, "wrapU", void 0);
  25918. __decorate([
  25919. BABYLON.serialize()
  25920. ], BaseTexture.prototype, "wrapV", void 0);
  25921. __decorate([
  25922. BABYLON.serialize()
  25923. ], BaseTexture.prototype, "wrapR", void 0);
  25924. __decorate([
  25925. BABYLON.serialize()
  25926. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25927. __decorate([
  25928. BABYLON.serialize()
  25929. ], BaseTexture.prototype, "isCube", void 0);
  25930. __decorate([
  25931. BABYLON.serialize()
  25932. ], BaseTexture.prototype, "is3D", void 0);
  25933. __decorate([
  25934. BABYLON.serialize()
  25935. ], BaseTexture.prototype, "gammaSpace", void 0);
  25936. __decorate([
  25937. BABYLON.serialize()
  25938. ], BaseTexture.prototype, "invertZ", void 0);
  25939. __decorate([
  25940. BABYLON.serialize()
  25941. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25942. __decorate([
  25943. BABYLON.serialize()
  25944. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25945. __decorate([
  25946. BABYLON.serialize()
  25947. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25948. __decorate([
  25949. BABYLON.serialize()
  25950. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25951. return BaseTexture;
  25952. }());
  25953. BABYLON.BaseTexture = BaseTexture;
  25954. })(BABYLON || (BABYLON = {}));
  25955. //# sourceMappingURL=babylon.baseTexture.js.map
  25956. var BABYLON;
  25957. (function (BABYLON) {
  25958. var Texture = /** @class */ (function (_super) {
  25959. __extends(Texture, _super);
  25960. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25961. if (noMipmap === void 0) { noMipmap = false; }
  25962. if (invertY === void 0) { invertY = true; }
  25963. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25964. if (onLoad === void 0) { onLoad = null; }
  25965. if (onError === void 0) { onError = null; }
  25966. if (buffer === void 0) { buffer = null; }
  25967. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25968. var _this = _super.call(this, scene) || this;
  25969. _this.uOffset = 0;
  25970. _this.vOffset = 0;
  25971. _this.uScale = 1.0;
  25972. _this.vScale = 1.0;
  25973. _this.uAng = 0;
  25974. _this.vAng = 0;
  25975. _this.wAng = 0;
  25976. _this._isBlocking = true;
  25977. _this.name = url || "";
  25978. _this.url = url;
  25979. _this._noMipmap = noMipmap;
  25980. _this._invertY = invertY;
  25981. _this._samplingMode = samplingMode;
  25982. _this._buffer = buffer;
  25983. _this._deleteBuffer = deleteBuffer;
  25984. if (format) {
  25985. _this._format = format;
  25986. }
  25987. scene = _this.getScene();
  25988. if (!scene) {
  25989. return _this;
  25990. }
  25991. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25992. var load = function () {
  25993. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25994. _this.onLoadObservable.notifyObservers(_this);
  25995. }
  25996. if (onLoad) {
  25997. onLoad();
  25998. }
  25999. if (!_this.isBlocking && scene) {
  26000. scene.resetCachedMaterial();
  26001. }
  26002. };
  26003. if (!_this.url) {
  26004. _this._delayedOnLoad = load;
  26005. _this._delayedOnError = onError;
  26006. return _this;
  26007. }
  26008. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26009. if (!_this._texture) {
  26010. if (!scene.useDelayedTextureLoading) {
  26011. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26012. if (deleteBuffer) {
  26013. delete _this._buffer;
  26014. }
  26015. }
  26016. else {
  26017. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26018. _this._delayedOnLoad = load;
  26019. _this._delayedOnError = onError;
  26020. }
  26021. }
  26022. else {
  26023. if (_this._texture.isReady) {
  26024. BABYLON.Tools.SetImmediate(function () { return load(); });
  26025. }
  26026. else {
  26027. _this._texture.onLoadedObservable.add(load);
  26028. }
  26029. }
  26030. return _this;
  26031. }
  26032. Object.defineProperty(Texture.prototype, "noMipmap", {
  26033. get: function () {
  26034. return this._noMipmap;
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. Object.defineProperty(Texture.prototype, "isBlocking", {
  26040. get: function () {
  26041. return this._isBlocking;
  26042. },
  26043. set: function (value) {
  26044. this._isBlocking = value;
  26045. },
  26046. enumerable: true,
  26047. configurable: true
  26048. });
  26049. Object.defineProperty(Texture.prototype, "samplingMode", {
  26050. get: function () {
  26051. return this._samplingMode;
  26052. },
  26053. enumerable: true,
  26054. configurable: true
  26055. });
  26056. Texture.prototype.updateURL = function (url) {
  26057. this.url = url;
  26058. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26059. this.delayLoad();
  26060. };
  26061. Texture.prototype.delayLoad = function () {
  26062. var _this = this;
  26063. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26064. return;
  26065. }
  26066. var scene = this.getScene();
  26067. if (!scene) {
  26068. return;
  26069. }
  26070. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26071. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26072. if (!this._texture) {
  26073. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26074. if (this._deleteBuffer) {
  26075. delete this._buffer;
  26076. }
  26077. }
  26078. else {
  26079. if (this._texture.isReady) {
  26080. BABYLON.Tools.SetImmediate(function () {
  26081. if (!_this._delayedOnLoad) {
  26082. return;
  26083. }
  26084. _this._delayedOnLoad();
  26085. });
  26086. }
  26087. else {
  26088. if (this._delayedOnLoad) {
  26089. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26090. }
  26091. }
  26092. }
  26093. };
  26094. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26095. if (!this._texture) {
  26096. return;
  26097. }
  26098. var scene = this.getScene();
  26099. if (!scene) {
  26100. return;
  26101. }
  26102. this._samplingMode = samplingMode;
  26103. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26104. };
  26105. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26106. x *= this.uScale;
  26107. y *= this.vScale;
  26108. x -= 0.5 * this.uScale;
  26109. y -= 0.5 * this.vScale;
  26110. z -= 0.5;
  26111. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26112. t.x += 0.5 * this.uScale + this.uOffset;
  26113. t.y += 0.5 * this.vScale + this.vOffset;
  26114. t.z += 0.5;
  26115. };
  26116. Texture.prototype.getTextureMatrix = function () {
  26117. var _this = this;
  26118. if (this.uOffset === this._cachedUOffset &&
  26119. this.vOffset === this._cachedVOffset &&
  26120. this.uScale === this._cachedUScale &&
  26121. this.vScale === this._cachedVScale &&
  26122. this.uAng === this._cachedUAng &&
  26123. this.vAng === this._cachedVAng &&
  26124. this.wAng === this._cachedWAng) {
  26125. return this._cachedTextureMatrix;
  26126. }
  26127. this._cachedUOffset = this.uOffset;
  26128. this._cachedVOffset = this.vOffset;
  26129. this._cachedUScale = this.uScale;
  26130. this._cachedVScale = this.vScale;
  26131. this._cachedUAng = this.uAng;
  26132. this._cachedVAng = this.vAng;
  26133. this._cachedWAng = this.wAng;
  26134. if (!this._cachedTextureMatrix) {
  26135. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26136. this._rowGenerationMatrix = new BABYLON.Matrix();
  26137. this._t0 = BABYLON.Vector3.Zero();
  26138. this._t1 = BABYLON.Vector3.Zero();
  26139. this._t2 = BABYLON.Vector3.Zero();
  26140. }
  26141. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26142. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26143. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26144. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26145. this._t1.subtractInPlace(this._t0);
  26146. this._t2.subtractInPlace(this._t0);
  26147. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26148. this._cachedTextureMatrix.m[0] = this._t1.x;
  26149. this._cachedTextureMatrix.m[1] = this._t1.y;
  26150. this._cachedTextureMatrix.m[2] = this._t1.z;
  26151. this._cachedTextureMatrix.m[4] = this._t2.x;
  26152. this._cachedTextureMatrix.m[5] = this._t2.y;
  26153. this._cachedTextureMatrix.m[6] = this._t2.z;
  26154. this._cachedTextureMatrix.m[8] = this._t0.x;
  26155. this._cachedTextureMatrix.m[9] = this._t0.y;
  26156. this._cachedTextureMatrix.m[10] = this._t0.z;
  26157. var scene = this.getScene();
  26158. if (!scene) {
  26159. return this._cachedTextureMatrix;
  26160. }
  26161. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26162. return mat.hasTexture(_this);
  26163. });
  26164. return this._cachedTextureMatrix;
  26165. };
  26166. Texture.prototype.getReflectionTextureMatrix = function () {
  26167. var _this = this;
  26168. var scene = this.getScene();
  26169. if (!scene) {
  26170. return this._cachedTextureMatrix;
  26171. }
  26172. if (this.uOffset === this._cachedUOffset &&
  26173. this.vOffset === this._cachedVOffset &&
  26174. this.uScale === this._cachedUScale &&
  26175. this.vScale === this._cachedVScale &&
  26176. this.coordinatesMode === this._cachedCoordinatesMode) {
  26177. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26178. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26179. return this._cachedTextureMatrix;
  26180. }
  26181. }
  26182. else {
  26183. return this._cachedTextureMatrix;
  26184. }
  26185. }
  26186. if (!this._cachedTextureMatrix) {
  26187. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26188. }
  26189. if (!this._projectionModeMatrix) {
  26190. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26191. }
  26192. this._cachedUOffset = this.uOffset;
  26193. this._cachedVOffset = this.vOffset;
  26194. this._cachedUScale = this.uScale;
  26195. this._cachedVScale = this.vScale;
  26196. this._cachedCoordinatesMode = this.coordinatesMode;
  26197. switch (this.coordinatesMode) {
  26198. case Texture.PLANAR_MODE:
  26199. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26200. this._cachedTextureMatrix[0] = this.uScale;
  26201. this._cachedTextureMatrix[5] = this.vScale;
  26202. this._cachedTextureMatrix[12] = this.uOffset;
  26203. this._cachedTextureMatrix[13] = this.vOffset;
  26204. break;
  26205. case Texture.PROJECTION_MODE:
  26206. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26207. this._projectionModeMatrix.m[0] = 0.5;
  26208. this._projectionModeMatrix.m[5] = -0.5;
  26209. this._projectionModeMatrix.m[10] = 0.0;
  26210. this._projectionModeMatrix.m[12] = 0.5;
  26211. this._projectionModeMatrix.m[13] = 0.5;
  26212. this._projectionModeMatrix.m[14] = 1.0;
  26213. this._projectionModeMatrix.m[15] = 1.0;
  26214. var projectionMatrix = scene.getProjectionMatrix();
  26215. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26216. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26217. break;
  26218. default:
  26219. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26220. break;
  26221. }
  26222. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26223. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26224. });
  26225. return this._cachedTextureMatrix;
  26226. };
  26227. Texture.prototype.clone = function () {
  26228. var _this = this;
  26229. return BABYLON.SerializationHelper.Clone(function () {
  26230. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26231. }, this);
  26232. };
  26233. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26234. get: function () {
  26235. if (!this._onLoadObservable) {
  26236. this._onLoadObservable = new BABYLON.Observable();
  26237. }
  26238. return this._onLoadObservable;
  26239. },
  26240. enumerable: true,
  26241. configurable: true
  26242. });
  26243. Texture.prototype.serialize = function () {
  26244. var serializationObject = _super.prototype.serialize.call(this);
  26245. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26246. serializationObject.base64String = this._buffer;
  26247. serializationObject.name = serializationObject.name.replace("data:", "");
  26248. }
  26249. return serializationObject;
  26250. };
  26251. Texture.prototype.getClassName = function () {
  26252. return "Texture";
  26253. };
  26254. Texture.prototype.dispose = function () {
  26255. _super.prototype.dispose.call(this);
  26256. if (this.onLoadObservable) {
  26257. this.onLoadObservable.clear();
  26258. this._onLoadObservable = null;
  26259. }
  26260. this._delayedOnLoad = null;
  26261. this._delayedOnError = null;
  26262. };
  26263. // Statics
  26264. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26265. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26266. if (onLoad === void 0) { onLoad = null; }
  26267. if (onError === void 0) { onError = null; }
  26268. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26269. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26270. };
  26271. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26272. if (parsedTexture.customType) {
  26273. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26274. // Update Sampling Mode
  26275. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26276. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26277. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26278. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26279. }
  26280. }
  26281. return parsedCustomTexture;
  26282. }
  26283. if (parsedTexture.isCube) {
  26284. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26285. }
  26286. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26287. return null;
  26288. }
  26289. var texture = BABYLON.SerializationHelper.Parse(function () {
  26290. var generateMipMaps = true;
  26291. if (parsedTexture.noMipmap) {
  26292. generateMipMaps = false;
  26293. }
  26294. if (parsedTexture.mirrorPlane) {
  26295. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26296. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26297. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26298. return mirrorTexture;
  26299. }
  26300. else if (parsedTexture.isRenderTarget) {
  26301. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26302. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26303. return renderTargetTexture;
  26304. }
  26305. else {
  26306. var texture;
  26307. if (parsedTexture.base64String) {
  26308. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26309. }
  26310. else {
  26311. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26312. }
  26313. return texture;
  26314. }
  26315. }, parsedTexture, scene);
  26316. // Update Sampling Mode
  26317. if (parsedTexture.samplingMode) {
  26318. var sampling = parsedTexture.samplingMode;
  26319. if (texture._samplingMode !== sampling) {
  26320. texture.updateSamplingMode(sampling);
  26321. }
  26322. }
  26323. // Animations
  26324. if (parsedTexture.animations) {
  26325. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26326. var parsedAnimation = parsedTexture.animations[animationIndex];
  26327. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26328. }
  26329. }
  26330. return texture;
  26331. };
  26332. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26333. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26334. if (noMipmap === void 0) { noMipmap = false; }
  26335. if (invertY === void 0) { invertY = true; }
  26336. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26337. if (onLoad === void 0) { onLoad = null; }
  26338. if (onError === void 0) { onError = null; }
  26339. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26340. if (name.substr(0, 5) !== "data:") {
  26341. name = "data:" + name;
  26342. }
  26343. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26344. };
  26345. // Constants
  26346. Texture.NEAREST_SAMPLINGMODE = 1;
  26347. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26348. Texture.BILINEAR_SAMPLINGMODE = 2;
  26349. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26350. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26351. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26352. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26353. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26354. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26355. Texture.NEAREST_LINEAR = 7;
  26356. Texture.NEAREST_NEAREST = 8;
  26357. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26358. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26359. Texture.LINEAR_LINEAR = 11;
  26360. Texture.LINEAR_NEAREST = 12;
  26361. Texture.EXPLICIT_MODE = 0;
  26362. Texture.SPHERICAL_MODE = 1;
  26363. Texture.PLANAR_MODE = 2;
  26364. Texture.CUBIC_MODE = 3;
  26365. Texture.PROJECTION_MODE = 4;
  26366. Texture.SKYBOX_MODE = 5;
  26367. Texture.INVCUBIC_MODE = 6;
  26368. Texture.EQUIRECTANGULAR_MODE = 7;
  26369. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26370. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26371. Texture.CLAMP_ADDRESSMODE = 0;
  26372. Texture.WRAP_ADDRESSMODE = 1;
  26373. Texture.MIRROR_ADDRESSMODE = 2;
  26374. __decorate([
  26375. BABYLON.serialize()
  26376. ], Texture.prototype, "url", void 0);
  26377. __decorate([
  26378. BABYLON.serialize()
  26379. ], Texture.prototype, "uOffset", void 0);
  26380. __decorate([
  26381. BABYLON.serialize()
  26382. ], Texture.prototype, "vOffset", void 0);
  26383. __decorate([
  26384. BABYLON.serialize()
  26385. ], Texture.prototype, "uScale", void 0);
  26386. __decorate([
  26387. BABYLON.serialize()
  26388. ], Texture.prototype, "vScale", void 0);
  26389. __decorate([
  26390. BABYLON.serialize()
  26391. ], Texture.prototype, "uAng", void 0);
  26392. __decorate([
  26393. BABYLON.serialize()
  26394. ], Texture.prototype, "vAng", void 0);
  26395. __decorate([
  26396. BABYLON.serialize()
  26397. ], Texture.prototype, "wAng", void 0);
  26398. __decorate([
  26399. BABYLON.serialize()
  26400. ], Texture.prototype, "isBlocking", null);
  26401. return Texture;
  26402. }(BABYLON.BaseTexture));
  26403. BABYLON.Texture = Texture;
  26404. })(BABYLON || (BABYLON = {}));
  26405. //# sourceMappingURL=babylon.texture.js.map
  26406. var BABYLON;
  26407. (function (BABYLON) {
  26408. var _InstancesBatch = /** @class */ (function () {
  26409. function _InstancesBatch() {
  26410. this.mustReturn = false;
  26411. this.visibleInstances = new Array();
  26412. this.renderSelf = new Array();
  26413. }
  26414. return _InstancesBatch;
  26415. }());
  26416. BABYLON._InstancesBatch = _InstancesBatch;
  26417. var Mesh = /** @class */ (function (_super) {
  26418. __extends(Mesh, _super);
  26419. /**
  26420. * @constructor
  26421. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26422. * @param {Scene} scene The scene to add this mesh to.
  26423. * @param {Node} parent The parent of this mesh, if it has one
  26424. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26425. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26426. * When false, achieved by calling a clone(), also passing False.
  26427. * This will make creation of children, recursive.
  26428. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26429. */
  26430. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26431. if (scene === void 0) { scene = null; }
  26432. if (parent === void 0) { parent = null; }
  26433. if (source === void 0) { source = null; }
  26434. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26435. var _this = _super.call(this, name, scene) || this;
  26436. // Events
  26437. /**
  26438. * An event triggered before rendering the mesh
  26439. * @type {BABYLON.Observable}
  26440. */
  26441. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26442. /**
  26443. * An event triggered after rendering the mesh
  26444. * @type {BABYLON.Observable}
  26445. */
  26446. _this.onAfterRenderObservable = new BABYLON.Observable();
  26447. /**
  26448. * An event triggered before drawing the mesh
  26449. * @type {BABYLON.Observable}
  26450. */
  26451. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26452. // Members
  26453. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26454. _this.instances = new Array();
  26455. _this._LODLevels = new Array();
  26456. _this._visibleInstances = {};
  26457. _this._renderIdForInstances = new Array();
  26458. _this._batchCache = new _InstancesBatch();
  26459. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26460. // Use by builder only to know what orientation were the mesh build in.
  26461. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26462. _this.overrideMaterialSideOrientation = null;
  26463. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26464. // Will be used to save a source mesh reference, If any
  26465. _this._source = null;
  26466. scene = _this.getScene();
  26467. if (source) {
  26468. // Source mesh
  26469. _this._source = source;
  26470. // Geometry
  26471. if (source._geometry) {
  26472. source._geometry.applyToMesh(_this);
  26473. }
  26474. // Deep copy
  26475. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26476. // Metadata
  26477. if (source.metadata && source.metadata.clone) {
  26478. _this.metadata = source.metadata.clone();
  26479. }
  26480. else {
  26481. _this.metadata = source.metadata;
  26482. }
  26483. // Tags
  26484. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26485. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26486. }
  26487. // Parent
  26488. _this.parent = source.parent;
  26489. // Pivot
  26490. _this.setPivotMatrix(source.getPivotMatrix());
  26491. _this.id = name + "." + source.id;
  26492. // Material
  26493. _this.material = source.material;
  26494. var index;
  26495. if (!doNotCloneChildren) {
  26496. // Children
  26497. var directDescendants = source.getDescendants(true);
  26498. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26499. var child = directDescendants[index_1];
  26500. if (child.clone) {
  26501. child.clone(name + "." + child.name, _this);
  26502. }
  26503. }
  26504. }
  26505. // Physics clone
  26506. var physicsEngine = _this.getScene().getPhysicsEngine();
  26507. if (clonePhysicsImpostor && physicsEngine) {
  26508. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26509. if (impostor) {
  26510. _this.physicsImpostor = impostor.clone(_this);
  26511. }
  26512. }
  26513. // Particles
  26514. for (index = 0; index < scene.particleSystems.length; index++) {
  26515. var system = scene.particleSystems[index];
  26516. if (system.emitter === source) {
  26517. system.clone(system.name, _this);
  26518. }
  26519. }
  26520. _this.computeWorldMatrix(true);
  26521. }
  26522. // Parent
  26523. if (parent !== null) {
  26524. _this.parent = parent;
  26525. }
  26526. return _this;
  26527. }
  26528. Object.defineProperty(Mesh, "FRONTSIDE", {
  26529. /**
  26530. * Mesh side orientation : usually the external or front surface
  26531. */
  26532. get: function () {
  26533. return Mesh._FRONTSIDE;
  26534. },
  26535. enumerable: true,
  26536. configurable: true
  26537. });
  26538. Object.defineProperty(Mesh, "BACKSIDE", {
  26539. /**
  26540. * Mesh side orientation : usually the internal or back surface
  26541. */
  26542. get: function () {
  26543. return Mesh._BACKSIDE;
  26544. },
  26545. enumerable: true,
  26546. configurable: true
  26547. });
  26548. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26549. /**
  26550. * Mesh side orientation : both internal and external or front and back surfaces
  26551. */
  26552. get: function () {
  26553. return Mesh._DOUBLESIDE;
  26554. },
  26555. enumerable: true,
  26556. configurable: true
  26557. });
  26558. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26559. /**
  26560. * Mesh side orientation : by default, `FRONTSIDE`
  26561. */
  26562. get: function () {
  26563. return Mesh._DEFAULTSIDE;
  26564. },
  26565. enumerable: true,
  26566. configurable: true
  26567. });
  26568. Object.defineProperty(Mesh, "NO_CAP", {
  26569. /**
  26570. * Mesh cap setting : no cap
  26571. */
  26572. get: function () {
  26573. return Mesh._NO_CAP;
  26574. },
  26575. enumerable: true,
  26576. configurable: true
  26577. });
  26578. Object.defineProperty(Mesh, "CAP_START", {
  26579. /**
  26580. * Mesh cap setting : one cap at the beginning of the mesh
  26581. */
  26582. get: function () {
  26583. return Mesh._CAP_START;
  26584. },
  26585. enumerable: true,
  26586. configurable: true
  26587. });
  26588. Object.defineProperty(Mesh, "CAP_END", {
  26589. /**
  26590. * Mesh cap setting : one cap at the end of the mesh
  26591. */
  26592. get: function () {
  26593. return Mesh._CAP_END;
  26594. },
  26595. enumerable: true,
  26596. configurable: true
  26597. });
  26598. Object.defineProperty(Mesh, "CAP_ALL", {
  26599. /**
  26600. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26601. */
  26602. get: function () {
  26603. return Mesh._CAP_ALL;
  26604. },
  26605. enumerable: true,
  26606. configurable: true
  26607. });
  26608. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26609. set: function (callback) {
  26610. if (this._onBeforeDrawObserver) {
  26611. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26612. }
  26613. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26614. },
  26615. enumerable: true,
  26616. configurable: true
  26617. });
  26618. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26619. get: function () {
  26620. return this._morphTargetManager;
  26621. },
  26622. set: function (value) {
  26623. if (this._morphTargetManager === value) {
  26624. return;
  26625. }
  26626. this._morphTargetManager = value;
  26627. this._syncGeometryWithMorphTargetManager();
  26628. },
  26629. enumerable: true,
  26630. configurable: true
  26631. });
  26632. Object.defineProperty(Mesh.prototype, "source", {
  26633. get: function () {
  26634. return this._source;
  26635. },
  26636. enumerable: true,
  26637. configurable: true
  26638. });
  26639. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26640. get: function () {
  26641. return this._unIndexed;
  26642. },
  26643. set: function (value) {
  26644. if (this._unIndexed !== value) {
  26645. this._unIndexed = value;
  26646. this._markSubMeshesAsAttributesDirty();
  26647. }
  26648. },
  26649. enumerable: true,
  26650. configurable: true
  26651. });
  26652. // Methods
  26653. /**
  26654. * Returns the string "Mesh".
  26655. */
  26656. Mesh.prototype.getClassName = function () {
  26657. return "Mesh";
  26658. };
  26659. /**
  26660. * Returns a string.
  26661. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26662. */
  26663. Mesh.prototype.toString = function (fullDetails) {
  26664. var ret = _super.prototype.toString.call(this, fullDetails);
  26665. ret += ", n vertices: " + this.getTotalVertices();
  26666. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26667. if (this.animations) {
  26668. for (var i = 0; i < this.animations.length; i++) {
  26669. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26670. }
  26671. }
  26672. if (fullDetails) {
  26673. if (this._geometry) {
  26674. var ib = this.getIndices();
  26675. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26676. if (vb && ib) {
  26677. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26678. }
  26679. }
  26680. else {
  26681. ret += ", flat shading: UNKNOWN";
  26682. }
  26683. }
  26684. return ret;
  26685. };
  26686. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26687. /**
  26688. * True if the mesh has some Levels Of Details (LOD).
  26689. * Returns a boolean.
  26690. */
  26691. get: function () {
  26692. return this._LODLevels.length > 0;
  26693. },
  26694. enumerable: true,
  26695. configurable: true
  26696. });
  26697. /**
  26698. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26699. * @returns an array of {BABYLON.MeshLODLevel}
  26700. */
  26701. Mesh.prototype.getLODLevels = function () {
  26702. return this._LODLevels;
  26703. };
  26704. Mesh.prototype._sortLODLevels = function () {
  26705. this._LODLevels.sort(function (a, b) {
  26706. if (a.distance < b.distance) {
  26707. return 1;
  26708. }
  26709. if (a.distance > b.distance) {
  26710. return -1;
  26711. }
  26712. return 0;
  26713. });
  26714. };
  26715. /**
  26716. * Add a mesh as LOD level triggered at the given distance.
  26717. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26718. * @param {number} distance The distance from the center of the object to show this level
  26719. * @param {Mesh} mesh The mesh to be added as LOD level
  26720. * @return {Mesh} This mesh (for chaining)
  26721. */
  26722. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26723. if (mesh && mesh._masterMesh) {
  26724. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26725. return this;
  26726. }
  26727. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26728. this._LODLevels.push(level);
  26729. if (mesh) {
  26730. mesh._masterMesh = this;
  26731. }
  26732. this._sortLODLevels();
  26733. return this;
  26734. };
  26735. /**
  26736. * Returns the LOD level mesh at the passed distance or null if not found.
  26737. * It is related to the method `addLODLevel(distance, mesh)`.
  26738. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26739. * Returns an object Mesh or `null`.
  26740. */
  26741. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26742. for (var index = 0; index < this._LODLevels.length; index++) {
  26743. var level = this._LODLevels[index];
  26744. if (level.distance === distance) {
  26745. return level.mesh;
  26746. }
  26747. }
  26748. return null;
  26749. };
  26750. /**
  26751. * Remove a mesh from the LOD array
  26752. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26753. * @param {Mesh} mesh The mesh to be removed.
  26754. * @return {Mesh} This mesh (for chaining)
  26755. */
  26756. Mesh.prototype.removeLODLevel = function (mesh) {
  26757. for (var index = 0; index < this._LODLevels.length; index++) {
  26758. if (this._LODLevels[index].mesh === mesh) {
  26759. this._LODLevels.splice(index, 1);
  26760. if (mesh) {
  26761. mesh._masterMesh = null;
  26762. }
  26763. }
  26764. }
  26765. this._sortLODLevels();
  26766. return this;
  26767. };
  26768. /**
  26769. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26770. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26771. */
  26772. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26773. if (!this._LODLevels || this._LODLevels.length === 0) {
  26774. return this;
  26775. }
  26776. var bSphere;
  26777. if (boundingSphere) {
  26778. bSphere = boundingSphere;
  26779. }
  26780. else {
  26781. var boundingInfo = this.getBoundingInfo();
  26782. bSphere = boundingInfo.boundingSphere;
  26783. }
  26784. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26785. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26786. if (this.onLODLevelSelection) {
  26787. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26788. }
  26789. return this;
  26790. }
  26791. for (var index = 0; index < this._LODLevels.length; index++) {
  26792. var level = this._LODLevels[index];
  26793. if (level.distance < distanceToCamera) {
  26794. if (level.mesh) {
  26795. level.mesh._preActivate();
  26796. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26797. }
  26798. if (this.onLODLevelSelection) {
  26799. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26800. }
  26801. return level.mesh;
  26802. }
  26803. }
  26804. if (this.onLODLevelSelection) {
  26805. this.onLODLevelSelection(distanceToCamera, this, this);
  26806. }
  26807. return this;
  26808. };
  26809. Object.defineProperty(Mesh.prototype, "geometry", {
  26810. /**
  26811. * Returns the mesh internal Geometry object.
  26812. */
  26813. get: function () {
  26814. return this._geometry;
  26815. },
  26816. enumerable: true,
  26817. configurable: true
  26818. });
  26819. /**
  26820. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26821. */
  26822. Mesh.prototype.getTotalVertices = function () {
  26823. if (this._geometry === null || this._geometry === undefined) {
  26824. return 0;
  26825. }
  26826. return this._geometry.getTotalVertices();
  26827. };
  26828. /**
  26829. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26830. * 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.
  26831. * You can force the copy with forceCopy === true
  26832. * Returns null if the mesh has no geometry or no vertex buffer.
  26833. * Possible `kind` values :
  26834. * - BABYLON.VertexBuffer.PositionKind
  26835. * - BABYLON.VertexBuffer.UVKind
  26836. * - BABYLON.VertexBuffer.UV2Kind
  26837. * - BABYLON.VertexBuffer.UV3Kind
  26838. * - BABYLON.VertexBuffer.UV4Kind
  26839. * - BABYLON.VertexBuffer.UV5Kind
  26840. * - BABYLON.VertexBuffer.UV6Kind
  26841. * - BABYLON.VertexBuffer.ColorKind
  26842. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26843. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26844. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26845. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26846. */
  26847. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26848. if (!this._geometry) {
  26849. return null;
  26850. }
  26851. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26852. };
  26853. /**
  26854. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26855. * Returns `null` if the mesh has no geometry.
  26856. * Possible `kind` values :
  26857. * - BABYLON.VertexBuffer.PositionKind
  26858. * - BABYLON.VertexBuffer.UVKind
  26859. * - BABYLON.VertexBuffer.UV2Kind
  26860. * - BABYLON.VertexBuffer.UV3Kind
  26861. * - BABYLON.VertexBuffer.UV4Kind
  26862. * - BABYLON.VertexBuffer.UV5Kind
  26863. * - BABYLON.VertexBuffer.UV6Kind
  26864. * - BABYLON.VertexBuffer.ColorKind
  26865. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26866. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26867. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26868. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26869. */
  26870. Mesh.prototype.getVertexBuffer = function (kind) {
  26871. if (!this._geometry) {
  26872. return null;
  26873. }
  26874. return this._geometry.getVertexBuffer(kind);
  26875. };
  26876. /**
  26877. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26878. * Possible `kind` values :
  26879. * - BABYLON.VertexBuffer.PositionKind
  26880. * - BABYLON.VertexBuffer.UVKind
  26881. * - BABYLON.VertexBuffer.UV2Kind
  26882. * - BABYLON.VertexBuffer.UV3Kind
  26883. * - BABYLON.VertexBuffer.UV4Kind
  26884. * - BABYLON.VertexBuffer.UV5Kind
  26885. * - BABYLON.VertexBuffer.UV6Kind
  26886. * - BABYLON.VertexBuffer.ColorKind
  26887. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26888. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26889. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26890. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26891. */
  26892. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26893. if (!this._geometry) {
  26894. if (this._delayInfo) {
  26895. return this._delayInfo.indexOf(kind) !== -1;
  26896. }
  26897. return false;
  26898. }
  26899. return this._geometry.isVerticesDataPresent(kind);
  26900. };
  26901. /**
  26902. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26903. * Possible `kind` values :
  26904. * - BABYLON.VertexBuffer.PositionKind
  26905. * - BABYLON.VertexBuffer.UVKind
  26906. * - BABYLON.VertexBuffer.UV2Kind
  26907. * - BABYLON.VertexBuffer.UV3Kind
  26908. * - BABYLON.VertexBuffer.UV4Kind
  26909. * - BABYLON.VertexBuffer.UV5Kind
  26910. * - BABYLON.VertexBuffer.UV6Kind
  26911. * - BABYLON.VertexBuffer.ColorKind
  26912. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26913. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26914. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26915. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26916. */
  26917. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26918. if (!this._geometry) {
  26919. if (this._delayInfo) {
  26920. return this._delayInfo.indexOf(kind) !== -1;
  26921. }
  26922. return false;
  26923. }
  26924. return this._geometry.isVertexBufferUpdatable(kind);
  26925. };
  26926. /**
  26927. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26928. * Possible `kind` values :
  26929. * - BABYLON.VertexBuffer.PositionKind
  26930. * - BABYLON.VertexBuffer.UVKind
  26931. * - BABYLON.VertexBuffer.UV2Kind
  26932. * - BABYLON.VertexBuffer.UV3Kind
  26933. * - BABYLON.VertexBuffer.UV4Kind
  26934. * - BABYLON.VertexBuffer.UV5Kind
  26935. * - BABYLON.VertexBuffer.UV6Kind
  26936. * - BABYLON.VertexBuffer.ColorKind
  26937. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26938. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26939. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26940. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26941. */
  26942. Mesh.prototype.getVerticesDataKinds = function () {
  26943. if (!this._geometry) {
  26944. var result = new Array();
  26945. if (this._delayInfo) {
  26946. this._delayInfo.forEach(function (kind, index, array) {
  26947. result.push(kind);
  26948. });
  26949. }
  26950. return result;
  26951. }
  26952. return this._geometry.getVerticesDataKinds();
  26953. };
  26954. /**
  26955. * Returns a positive integer : the total number of indices in this mesh geometry.
  26956. * Returns zero if the mesh has no geometry.
  26957. */
  26958. Mesh.prototype.getTotalIndices = function () {
  26959. if (!this._geometry) {
  26960. return 0;
  26961. }
  26962. return this._geometry.getTotalIndices();
  26963. };
  26964. /**
  26965. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26966. * 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.
  26967. * Returns an empty array if the mesh has no geometry.
  26968. */
  26969. Mesh.prototype.getIndices = function (copyWhenShared) {
  26970. if (!this._geometry) {
  26971. return [];
  26972. }
  26973. return this._geometry.getIndices(copyWhenShared);
  26974. };
  26975. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26976. get: function () {
  26977. return this._masterMesh !== null && this._masterMesh !== undefined;
  26978. },
  26979. enumerable: true,
  26980. configurable: true
  26981. });
  26982. /**
  26983. * Determine if the current mesh is ready to be rendered
  26984. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26985. * @returns true if all associated assets are ready (material, textures, shaders)
  26986. */
  26987. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26988. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26989. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26990. return false;
  26991. }
  26992. if (!_super.prototype.isReady.call(this)) {
  26993. return false;
  26994. }
  26995. if (!this.subMeshes || this.subMeshes.length === 0) {
  26996. return true;
  26997. }
  26998. var engine = this.getEngine();
  26999. var scene = this.getScene();
  27000. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27001. this.computeWorldMatrix();
  27002. var mat = this.material || scene.defaultMaterial;
  27003. if (mat) {
  27004. if (mat.storeEffectOnSubMeshes) {
  27005. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27006. var subMesh = _a[_i];
  27007. var effectiveMaterial = subMesh.getMaterial();
  27008. if (effectiveMaterial) {
  27009. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27010. return false;
  27011. }
  27012. }
  27013. }
  27014. }
  27015. else {
  27016. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27017. return false;
  27018. }
  27019. }
  27020. }
  27021. // Shadows
  27022. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27023. var light = _c[_b];
  27024. var generator = light.getShadowGenerator();
  27025. if (generator) {
  27026. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27027. var subMesh = _e[_d];
  27028. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27029. return false;
  27030. }
  27031. }
  27032. }
  27033. }
  27034. // LOD
  27035. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27036. var lod = _g[_f];
  27037. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27038. return false;
  27039. }
  27040. }
  27041. return true;
  27042. };
  27043. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27044. /**
  27045. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27046. * This property is pertinent only for updatable parametric shapes.
  27047. */
  27048. get: function () {
  27049. return this._areNormalsFrozen;
  27050. },
  27051. enumerable: true,
  27052. configurable: true
  27053. });
  27054. /**
  27055. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27056. * It has no effect at all on other shapes.
  27057. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27058. * Returns the Mesh.
  27059. */
  27060. Mesh.prototype.freezeNormals = function () {
  27061. this._areNormalsFrozen = true;
  27062. return this;
  27063. };
  27064. /**
  27065. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27066. * It has no effect at all on other shapes.
  27067. * It reactivates the mesh normals computation if it was previously frozen.
  27068. * Returns the Mesh.
  27069. */
  27070. Mesh.prototype.unfreezeNormals = function () {
  27071. this._areNormalsFrozen = false;
  27072. return this;
  27073. };
  27074. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27075. /**
  27076. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27077. */
  27078. set: function (count) {
  27079. this._overridenInstanceCount = count;
  27080. },
  27081. enumerable: true,
  27082. configurable: true
  27083. });
  27084. // Methods
  27085. Mesh.prototype._preActivate = function () {
  27086. var sceneRenderId = this.getScene().getRenderId();
  27087. if (this._preActivateId === sceneRenderId) {
  27088. return this;
  27089. }
  27090. this._preActivateId = sceneRenderId;
  27091. this._visibleInstances = null;
  27092. return this;
  27093. };
  27094. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27095. if (this._visibleInstances) {
  27096. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27097. }
  27098. return this;
  27099. };
  27100. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27101. if (!this._visibleInstances) {
  27102. this._visibleInstances = {};
  27103. this._visibleInstances.defaultRenderId = renderId;
  27104. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27105. }
  27106. if (!this._visibleInstances[renderId]) {
  27107. this._visibleInstances[renderId] = new Array();
  27108. }
  27109. this._visibleInstances[renderId].push(instance);
  27110. return this;
  27111. };
  27112. /**
  27113. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27114. * This means the mesh underlying bounding box and sphere are recomputed.
  27115. * Returns the Mesh.
  27116. */
  27117. Mesh.prototype.refreshBoundingInfo = function () {
  27118. return this._refreshBoundingInfo(false);
  27119. };
  27120. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27121. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27122. return this;
  27123. }
  27124. var data = this._getPositionData(applySkeleton);
  27125. if (data) {
  27126. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27127. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27128. }
  27129. if (this.subMeshes) {
  27130. for (var index = 0; index < this.subMeshes.length; index++) {
  27131. this.subMeshes[index].refreshBoundingInfo();
  27132. }
  27133. }
  27134. this._updateBoundingInfo();
  27135. return this;
  27136. };
  27137. Mesh.prototype._getPositionData = function (applySkeleton) {
  27138. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27139. if (data && applySkeleton && this.skeleton) {
  27140. data = BABYLON.Tools.Slice(data);
  27141. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27142. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27143. if (matricesWeightsData && matricesIndicesData) {
  27144. var needExtras = this.numBoneInfluencers > 4;
  27145. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27146. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27147. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27148. var tempVector = BABYLON.Tmp.Vector3[0];
  27149. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27150. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27151. var matWeightIdx = 0;
  27152. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27153. finalMatrix.reset();
  27154. var inf;
  27155. var weight;
  27156. for (inf = 0; inf < 4; inf++) {
  27157. weight = matricesWeightsData[matWeightIdx + inf];
  27158. if (weight <= 0)
  27159. break;
  27160. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27161. finalMatrix.addToSelf(tempMatrix);
  27162. }
  27163. if (needExtras) {
  27164. for (inf = 0; inf < 4; inf++) {
  27165. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27166. if (weight <= 0)
  27167. break;
  27168. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27169. finalMatrix.addToSelf(tempMatrix);
  27170. }
  27171. }
  27172. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27173. tempVector.toArray(data, index);
  27174. }
  27175. }
  27176. }
  27177. return data;
  27178. };
  27179. Mesh.prototype._createGlobalSubMesh = function (force) {
  27180. var totalVertices = this.getTotalVertices();
  27181. if (!totalVertices || !this.getIndices()) {
  27182. return null;
  27183. }
  27184. // Check if we need to recreate the submeshes
  27185. if (this.subMeshes && this.subMeshes.length > 0) {
  27186. var ib = this.getIndices();
  27187. if (!ib) {
  27188. return null;
  27189. }
  27190. var totalIndices = ib.length;
  27191. var needToRecreate = false;
  27192. if (force) {
  27193. needToRecreate = true;
  27194. }
  27195. else {
  27196. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27197. var submesh = _a[_i];
  27198. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27199. needToRecreate = true;
  27200. break;
  27201. }
  27202. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27203. needToRecreate = true;
  27204. break;
  27205. }
  27206. }
  27207. }
  27208. if (!needToRecreate) {
  27209. return this.subMeshes[0];
  27210. }
  27211. }
  27212. this.releaseSubMeshes();
  27213. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27214. };
  27215. Mesh.prototype.subdivide = function (count) {
  27216. if (count < 1) {
  27217. return;
  27218. }
  27219. var totalIndices = this.getTotalIndices();
  27220. var subdivisionSize = (totalIndices / count) | 0;
  27221. var offset = 0;
  27222. // Ensure that subdivisionSize is a multiple of 3
  27223. while (subdivisionSize % 3 !== 0) {
  27224. subdivisionSize++;
  27225. }
  27226. this.releaseSubMeshes();
  27227. for (var index = 0; index < count; index++) {
  27228. if (offset >= totalIndices) {
  27229. break;
  27230. }
  27231. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27232. offset += subdivisionSize;
  27233. }
  27234. this.synchronizeInstances();
  27235. };
  27236. /**
  27237. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27238. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27239. * The `data` are either a numeric array either a Float32Array.
  27240. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27241. * 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).
  27242. * Note that a new underlying VertexBuffer object is created each call.
  27243. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27244. *
  27245. * Possible `kind` values :
  27246. * - BABYLON.VertexBuffer.PositionKind
  27247. * - BABYLON.VertexBuffer.UVKind
  27248. * - BABYLON.VertexBuffer.UV2Kind
  27249. * - BABYLON.VertexBuffer.UV3Kind
  27250. * - BABYLON.VertexBuffer.UV4Kind
  27251. * - BABYLON.VertexBuffer.UV5Kind
  27252. * - BABYLON.VertexBuffer.UV6Kind
  27253. * - BABYLON.VertexBuffer.ColorKind
  27254. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27255. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27256. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27257. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27258. *
  27259. * Returns the Mesh.
  27260. */
  27261. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27262. if (updatable === void 0) { updatable = false; }
  27263. if (!this._geometry) {
  27264. var vertexData = new BABYLON.VertexData();
  27265. vertexData.set(data, kind);
  27266. var scene = this.getScene();
  27267. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27268. }
  27269. else {
  27270. this._geometry.setVerticesData(kind, data, updatable, stride);
  27271. }
  27272. return this;
  27273. };
  27274. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27275. if (updatable === void 0) { updatable = true; }
  27276. var vb = this.getVertexBuffer(kind);
  27277. if (!vb || vb.isUpdatable() === updatable) {
  27278. return;
  27279. }
  27280. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27281. };
  27282. /**
  27283. * Sets the mesh VertexBuffer.
  27284. * Returns the Mesh.
  27285. */
  27286. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27287. if (!this._geometry) {
  27288. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27289. }
  27290. this._geometry.setVerticesBuffer(buffer);
  27291. return this;
  27292. };
  27293. /**
  27294. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27295. * If the mesh has no geometry, it is simply returned as it is.
  27296. * The `data` are either a numeric array either a Float32Array.
  27297. * No new underlying VertexBuffer object is created.
  27298. * 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.
  27299. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27300. *
  27301. * Possible `kind` values :
  27302. * - BABYLON.VertexBuffer.PositionKind
  27303. * - BABYLON.VertexBuffer.UVKind
  27304. * - BABYLON.VertexBuffer.UV2Kind
  27305. * - BABYLON.VertexBuffer.UV3Kind
  27306. * - BABYLON.VertexBuffer.UV4Kind
  27307. * - BABYLON.VertexBuffer.UV5Kind
  27308. * - BABYLON.VertexBuffer.UV6Kind
  27309. * - BABYLON.VertexBuffer.ColorKind
  27310. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27311. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27312. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27313. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27314. *
  27315. * Returns the Mesh.
  27316. */
  27317. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27318. if (!this._geometry) {
  27319. return this;
  27320. }
  27321. if (!makeItUnique) {
  27322. this._geometry.updateVerticesData(kind, data, updateExtends);
  27323. }
  27324. else {
  27325. this.makeGeometryUnique();
  27326. this.updateVerticesData(kind, data, updateExtends, false);
  27327. }
  27328. return this;
  27329. };
  27330. /**
  27331. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27332. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27333. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27334. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27335. * Returns the Mesh.
  27336. */
  27337. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27338. if (computeNormals === void 0) { computeNormals = true; }
  27339. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27340. if (!positions) {
  27341. return this;
  27342. }
  27343. positionFunction(positions);
  27344. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27345. if (computeNormals) {
  27346. var indices = this.getIndices();
  27347. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27348. if (!normals) {
  27349. return this;
  27350. }
  27351. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27352. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27353. }
  27354. return this;
  27355. };
  27356. /**
  27357. * Creates a un-shared specific occurence of the geometry for the mesh.
  27358. * Returns the Mesh.
  27359. */
  27360. Mesh.prototype.makeGeometryUnique = function () {
  27361. if (!this._geometry) {
  27362. return this;
  27363. }
  27364. var oldGeometry = this._geometry;
  27365. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27366. oldGeometry.releaseForMesh(this, true);
  27367. geometry.applyToMesh(this);
  27368. return this;
  27369. };
  27370. /**
  27371. * Sets the mesh indices.
  27372. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27373. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27374. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27375. * This method creates a new index buffer each call.
  27376. * Returns the Mesh.
  27377. */
  27378. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27379. if (totalVertices === void 0) { totalVertices = null; }
  27380. if (updatable === void 0) { updatable = false; }
  27381. if (!this._geometry) {
  27382. var vertexData = new BABYLON.VertexData();
  27383. vertexData.indices = indices;
  27384. var scene = this.getScene();
  27385. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27386. }
  27387. else {
  27388. this._geometry.setIndices(indices, totalVertices, updatable);
  27389. }
  27390. return this;
  27391. };
  27392. /**
  27393. * Update the current index buffer
  27394. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27395. * Returns the Mesh.
  27396. */
  27397. Mesh.prototype.updateIndices = function (indices, offset) {
  27398. if (!this._geometry) {
  27399. return this;
  27400. }
  27401. this._geometry.updateIndices(indices, offset);
  27402. return this;
  27403. };
  27404. /**
  27405. * Invert the geometry to move from a right handed system to a left handed one.
  27406. * Returns the Mesh.
  27407. */
  27408. Mesh.prototype.toLeftHanded = function () {
  27409. if (!this._geometry) {
  27410. return this;
  27411. }
  27412. this._geometry.toLeftHanded();
  27413. return this;
  27414. };
  27415. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27416. if (!this._geometry) {
  27417. return this;
  27418. }
  27419. var engine = this.getScene().getEngine();
  27420. // Wireframe
  27421. var indexToBind;
  27422. if (this._unIndexed) {
  27423. indexToBind = null;
  27424. }
  27425. else {
  27426. switch (fillMode) {
  27427. case BABYLON.Material.PointFillMode:
  27428. indexToBind = null;
  27429. break;
  27430. case BABYLON.Material.WireFrameFillMode:
  27431. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27432. break;
  27433. default:
  27434. case BABYLON.Material.TriangleFillMode:
  27435. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27436. break;
  27437. }
  27438. }
  27439. // VBOs
  27440. this._geometry._bind(effect, indexToBind);
  27441. return this;
  27442. };
  27443. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27444. if (alternate === void 0) { alternate = false; }
  27445. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27446. return this;
  27447. }
  27448. this.onBeforeDrawObservable.notifyObservers(this);
  27449. var scene = this.getScene();
  27450. var engine = scene.getEngine();
  27451. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27452. // or triangles as points
  27453. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27454. }
  27455. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27456. // Triangles as wireframe
  27457. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27458. }
  27459. else {
  27460. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27461. }
  27462. if (scene._isAlternateRenderingEnabled && !alternate) {
  27463. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27464. if (!effect || !scene.activeCamera) {
  27465. return this;
  27466. }
  27467. scene._switchToAlternateCameraConfiguration(true);
  27468. this._effectiveMaterial.bindView(effect);
  27469. this._effectiveMaterial.bindViewProjection(effect);
  27470. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27471. this._draw(subMesh, fillMode, instancesCount, true);
  27472. engine.setViewport(scene.activeCamera.viewport);
  27473. scene._switchToAlternateCameraConfiguration(false);
  27474. this._effectiveMaterial.bindView(effect);
  27475. this._effectiveMaterial.bindViewProjection(effect);
  27476. }
  27477. return this;
  27478. };
  27479. /**
  27480. * Registers for this mesh a javascript function called just before the rendering process.
  27481. * This function is passed the current mesh.
  27482. * Return the Mesh.
  27483. */
  27484. Mesh.prototype.registerBeforeRender = function (func) {
  27485. this.onBeforeRenderObservable.add(func);
  27486. return this;
  27487. };
  27488. /**
  27489. * Disposes a previously registered javascript function called before the rendering.
  27490. * This function is passed the current mesh.
  27491. * Returns the Mesh.
  27492. */
  27493. Mesh.prototype.unregisterBeforeRender = function (func) {
  27494. this.onBeforeRenderObservable.removeCallback(func);
  27495. return this;
  27496. };
  27497. /**
  27498. * Registers for this mesh a javascript function called just after the rendering is complete.
  27499. * This function is passed the current mesh.
  27500. * Returns the Mesh.
  27501. */
  27502. Mesh.prototype.registerAfterRender = function (func) {
  27503. this.onAfterRenderObservable.add(func);
  27504. return this;
  27505. };
  27506. /**
  27507. * Disposes a previously registered javascript function called after the rendering.
  27508. * This function is passed the current mesh.
  27509. * Return the Mesh.
  27510. */
  27511. Mesh.prototype.unregisterAfterRender = function (func) {
  27512. this.onAfterRenderObservable.removeCallback(func);
  27513. return this;
  27514. };
  27515. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27516. var scene = this.getScene();
  27517. this._batchCache.mustReturn = false;
  27518. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27519. this._batchCache.visibleInstances[subMeshId] = null;
  27520. if (this._visibleInstances) {
  27521. var currentRenderId = scene.getRenderId();
  27522. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27523. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27524. var selfRenderId = this._renderId;
  27525. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27526. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27527. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27528. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27529. }
  27530. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27531. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27532. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27533. this._batchCache.mustReturn = true;
  27534. return this._batchCache;
  27535. }
  27536. if (currentRenderId !== selfRenderId) {
  27537. this._batchCache.renderSelf[subMeshId] = false;
  27538. }
  27539. }
  27540. this._renderIdForInstances[subMeshId] = currentRenderId;
  27541. }
  27542. return this._batchCache;
  27543. };
  27544. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27545. var visibleInstances = batch.visibleInstances[subMesh._id];
  27546. if (!visibleInstances) {
  27547. return this;
  27548. }
  27549. var matricesCount = visibleInstances.length + 1;
  27550. var bufferSize = matricesCount * 16 * 4;
  27551. var currentInstancesBufferSize = this._instancesBufferSize;
  27552. var instancesBuffer = this._instancesBuffer;
  27553. while (this._instancesBufferSize < bufferSize) {
  27554. this._instancesBufferSize *= 2;
  27555. }
  27556. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27557. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27558. }
  27559. var offset = 0;
  27560. var instancesCount = 0;
  27561. var world = this.getWorldMatrix();
  27562. if (batch.renderSelf[subMesh._id]) {
  27563. world.copyToArray(this._instancesData, offset);
  27564. offset += 16;
  27565. instancesCount++;
  27566. }
  27567. if (visibleInstances) {
  27568. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27569. var instance = visibleInstances[instanceIndex];
  27570. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27571. offset += 16;
  27572. instancesCount++;
  27573. }
  27574. }
  27575. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27576. if (instancesBuffer) {
  27577. instancesBuffer.dispose();
  27578. }
  27579. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27580. this._instancesBuffer = instancesBuffer;
  27581. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27582. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27583. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27584. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27585. }
  27586. else {
  27587. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27588. }
  27589. this._bind(subMesh, effect, fillMode);
  27590. this._draw(subMesh, fillMode, instancesCount);
  27591. engine.unbindInstanceAttributes();
  27592. return this;
  27593. };
  27594. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27595. var scene = this.getScene();
  27596. var engine = scene.getEngine();
  27597. if (hardwareInstancedRendering) {
  27598. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27599. }
  27600. else {
  27601. if (batch.renderSelf[subMesh._id]) {
  27602. // Draw
  27603. if (onBeforeDraw) {
  27604. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27605. }
  27606. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27607. }
  27608. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27609. if (visibleInstancesForSubMesh) {
  27610. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27611. var instance = visibleInstancesForSubMesh[instanceIndex];
  27612. // World
  27613. var world = instance.getWorldMatrix();
  27614. if (onBeforeDraw) {
  27615. onBeforeDraw(true, world, effectiveMaterial);
  27616. }
  27617. // Draw
  27618. this._draw(subMesh, fillMode);
  27619. }
  27620. }
  27621. }
  27622. return this;
  27623. };
  27624. /**
  27625. * Triggers the draw call for the mesh.
  27626. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27627. * Returns the Mesh.
  27628. */
  27629. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27630. this.checkOcclusionQuery();
  27631. if (this._isOccluded) {
  27632. return this;
  27633. }
  27634. var scene = this.getScene();
  27635. // Managing instances
  27636. var batch = this._getInstancesRenderList(subMesh._id);
  27637. if (batch.mustReturn) {
  27638. return this;
  27639. }
  27640. // Checking geometry state
  27641. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27642. return this;
  27643. }
  27644. this.onBeforeRenderObservable.notifyObservers(this);
  27645. var engine = scene.getEngine();
  27646. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27647. // Material
  27648. var material = subMesh.getMaterial();
  27649. if (!material) {
  27650. return this;
  27651. }
  27652. this._effectiveMaterial = material;
  27653. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27654. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27655. return this;
  27656. }
  27657. }
  27658. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27659. return this;
  27660. }
  27661. // Alpha mode
  27662. if (enableAlphaMode) {
  27663. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27664. }
  27665. // Outline - step 1
  27666. var savedDepthWrite = engine.getDepthWrite();
  27667. if (this.renderOutline) {
  27668. engine.setDepthWrite(false);
  27669. scene.getOutlineRenderer().render(subMesh, batch);
  27670. engine.setDepthWrite(savedDepthWrite);
  27671. }
  27672. var effect;
  27673. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27674. effect = subMesh.effect;
  27675. }
  27676. else {
  27677. effect = this._effectiveMaterial.getEffect();
  27678. }
  27679. if (!effect) {
  27680. return this;
  27681. }
  27682. var sideOrientation = this.overrideMaterialSideOrientation;
  27683. if (sideOrientation == null) {
  27684. sideOrientation = this._effectiveMaterial.sideOrientation;
  27685. if (this._getWorldMatrixDeterminant() < 0) {
  27686. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27687. }
  27688. }
  27689. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27690. if (this._effectiveMaterial.forceDepthWrite) {
  27691. engine.setDepthWrite(true);
  27692. }
  27693. // Bind
  27694. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27695. if (!hardwareInstancedRendering) {
  27696. this._bind(subMesh, effect, fillMode);
  27697. }
  27698. var world = this.getWorldMatrix();
  27699. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27700. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27701. }
  27702. else {
  27703. this._effectiveMaterial.bind(world, this);
  27704. }
  27705. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27706. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27707. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27708. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27709. }
  27710. // Draw
  27711. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27712. // Unbind
  27713. this._effectiveMaterial.unbind();
  27714. // Outline - step 2
  27715. if (this.renderOutline && savedDepthWrite) {
  27716. engine.setDepthWrite(true);
  27717. engine.setColorWrite(false);
  27718. scene.getOutlineRenderer().render(subMesh, batch);
  27719. engine.setColorWrite(true);
  27720. }
  27721. // Overlay
  27722. if (this.renderOverlay) {
  27723. var currentMode = engine.getAlphaMode();
  27724. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27725. scene.getOutlineRenderer().render(subMesh, batch, true);
  27726. engine.setAlphaMode(currentMode);
  27727. }
  27728. this.onAfterRenderObservable.notifyObservers(this);
  27729. return this;
  27730. };
  27731. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27732. if (isInstance && effectiveMaterial) {
  27733. effectiveMaterial.bindOnlyWorldMatrix(world);
  27734. }
  27735. };
  27736. /**
  27737. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27738. */
  27739. Mesh.prototype.getEmittedParticleSystems = function () {
  27740. var results = new Array();
  27741. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27742. var particleSystem = this.getScene().particleSystems[index];
  27743. if (particleSystem.emitter === this) {
  27744. results.push(particleSystem);
  27745. }
  27746. }
  27747. return results;
  27748. };
  27749. /**
  27750. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27751. */
  27752. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27753. var results = new Array();
  27754. var descendants = this.getDescendants();
  27755. descendants.push(this);
  27756. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27757. var particleSystem = this.getScene().particleSystems[index];
  27758. var emitter = particleSystem.emitter;
  27759. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27760. results.push(particleSystem);
  27761. }
  27762. }
  27763. return results;
  27764. };
  27765. Mesh.prototype._checkDelayState = function () {
  27766. var scene = this.getScene();
  27767. if (this._geometry) {
  27768. this._geometry.load(scene);
  27769. }
  27770. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27771. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27772. this._queueLoad(scene);
  27773. }
  27774. return this;
  27775. };
  27776. Mesh.prototype._queueLoad = function (scene) {
  27777. var _this = this;
  27778. scene._addPendingData(this);
  27779. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27780. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27781. if (data instanceof ArrayBuffer) {
  27782. _this._delayLoadingFunction(data, _this);
  27783. }
  27784. else {
  27785. _this._delayLoadingFunction(JSON.parse(data), _this);
  27786. }
  27787. _this.instances.forEach(function (instance) {
  27788. instance._syncSubMeshes();
  27789. });
  27790. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27791. scene._removePendingData(_this);
  27792. }, function () { }, scene.database, getBinaryData);
  27793. return this;
  27794. };
  27795. /**
  27796. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27797. */
  27798. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27799. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27800. return false;
  27801. }
  27802. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27803. return false;
  27804. }
  27805. this._checkDelayState();
  27806. return true;
  27807. };
  27808. /**
  27809. * Sets the mesh material by the material or multiMaterial `id` property.
  27810. * The material `id` is a string identifying the material or the multiMaterial.
  27811. * This method returns the Mesh.
  27812. */
  27813. Mesh.prototype.setMaterialByID = function (id) {
  27814. var materials = this.getScene().materials;
  27815. var index;
  27816. for (index = materials.length - 1; index > -1; index--) {
  27817. if (materials[index].id === id) {
  27818. this.material = materials[index];
  27819. return this;
  27820. }
  27821. }
  27822. // Multi
  27823. var multiMaterials = this.getScene().multiMaterials;
  27824. for (index = multiMaterials.length - 1; index > -1; index--) {
  27825. if (multiMaterials[index].id === id) {
  27826. this.material = multiMaterials[index];
  27827. return this;
  27828. }
  27829. }
  27830. return this;
  27831. };
  27832. /**
  27833. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27834. */
  27835. Mesh.prototype.getAnimatables = function () {
  27836. var results = new Array();
  27837. if (this.material) {
  27838. results.push(this.material);
  27839. }
  27840. if (this.skeleton) {
  27841. results.push(this.skeleton);
  27842. }
  27843. return results;
  27844. };
  27845. /**
  27846. * Modifies the mesh geometry according to the passed transformation matrix.
  27847. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27848. * The mesh normals are modified accordingly the same transformation.
  27849. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27850. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27851. * Returns the Mesh.
  27852. */
  27853. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27854. // Position
  27855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27856. return this;
  27857. }
  27858. var submeshes = this.subMeshes.splice(0);
  27859. this._resetPointsArrayCache();
  27860. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27861. var temp = new Array();
  27862. var index;
  27863. for (index = 0; index < data.length; index += 3) {
  27864. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27865. }
  27866. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27867. // Normals
  27868. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27869. return this;
  27870. }
  27871. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27872. temp = [];
  27873. for (index = 0; index < data.length; index += 3) {
  27874. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27875. }
  27876. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27877. // flip faces?
  27878. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27879. this.flipFaces();
  27880. }
  27881. // Restore submeshes
  27882. this.releaseSubMeshes();
  27883. this.subMeshes = submeshes;
  27884. return this;
  27885. };
  27886. /**
  27887. * Modifies the mesh geometry according to its own current World Matrix.
  27888. * The mesh World Matrix is then reset.
  27889. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27890. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27891. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27892. * Returns the Mesh.
  27893. */
  27894. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27895. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27896. this.scaling.copyFromFloats(1, 1, 1);
  27897. this.position.copyFromFloats(0, 0, 0);
  27898. this.rotation.copyFromFloats(0, 0, 0);
  27899. //only if quaternion is already set
  27900. if (this.rotationQuaternion) {
  27901. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27902. }
  27903. this._worldMatrix = BABYLON.Matrix.Identity();
  27904. return this;
  27905. };
  27906. Object.defineProperty(Mesh.prototype, "_positions", {
  27907. // Cache
  27908. get: function () {
  27909. if (this._geometry) {
  27910. return this._geometry._positions;
  27911. }
  27912. return null;
  27913. },
  27914. enumerable: true,
  27915. configurable: true
  27916. });
  27917. Mesh.prototype._resetPointsArrayCache = function () {
  27918. if (this._geometry) {
  27919. this._geometry._resetPointsArrayCache();
  27920. }
  27921. return this;
  27922. };
  27923. Mesh.prototype._generatePointsArray = function () {
  27924. if (this._geometry) {
  27925. return this._geometry._generatePointsArray();
  27926. }
  27927. return false;
  27928. };
  27929. /**
  27930. * Returns a new Mesh object generated from the current mesh properties.
  27931. * This method must not get confused with createInstance().
  27932. * The parameter `name` is a string, the name given to the new mesh.
  27933. * The optional parameter `newParent` can be any Node object (default `null`).
  27934. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27935. * 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.
  27936. */
  27937. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27938. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27939. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27940. };
  27941. /**
  27942. * Disposes the Mesh.
  27943. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27944. * Returns nothing.
  27945. */
  27946. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27947. var _this = this;
  27948. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27949. this.morphTargetManager = null;
  27950. if (this._geometry) {
  27951. this._geometry.releaseForMesh(this, true);
  27952. }
  27953. // Sources
  27954. var meshes = this.getScene().meshes;
  27955. meshes.forEach(function (abstractMesh) {
  27956. var mesh = abstractMesh;
  27957. if (mesh._source && mesh._source === _this) {
  27958. mesh._source = null;
  27959. }
  27960. });
  27961. this._source = null;
  27962. // Instances
  27963. if (this._instancesBuffer) {
  27964. this._instancesBuffer.dispose();
  27965. this._instancesBuffer = null;
  27966. }
  27967. while (this.instances.length) {
  27968. this.instances[0].dispose();
  27969. }
  27970. // Highlight layers.
  27971. var highlightLayers = this.getScene().highlightLayers;
  27972. for (var i = 0; i < highlightLayers.length; i++) {
  27973. var highlightLayer = highlightLayers[i];
  27974. if (highlightLayer) {
  27975. highlightLayer.removeMesh(this);
  27976. highlightLayer.removeExcludedMesh(this);
  27977. }
  27978. }
  27979. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27980. };
  27981. /**
  27982. * Modifies the mesh geometry according to a displacement map.
  27983. * 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.
  27984. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27985. * This method returns nothing.
  27986. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27987. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27988. * 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.
  27989. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27990. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27991. *
  27992. * Returns the Mesh.
  27993. */
  27994. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27995. var _this = this;
  27996. var scene = this.getScene();
  27997. var onload = function (img) {
  27998. // Getting height map data
  27999. var canvas = document.createElement("canvas");
  28000. var context = canvas.getContext("2d");
  28001. var heightMapWidth = img.width;
  28002. var heightMapHeight = img.height;
  28003. canvas.width = heightMapWidth;
  28004. canvas.height = heightMapHeight;
  28005. context.drawImage(img, 0, 0);
  28006. // Create VertexData from map data
  28007. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28008. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28009. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28010. //execute success callback, if set
  28011. if (onSuccess) {
  28012. onSuccess(_this);
  28013. }
  28014. };
  28015. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28016. return this;
  28017. };
  28018. /**
  28019. * Modifies the mesh geometry according to a displacementMap buffer.
  28020. * 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.
  28021. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28022. * This method returns nothing.
  28023. * 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.
  28024. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28025. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28026. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28027. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28028. *
  28029. * Returns the Mesh.
  28030. */
  28031. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28032. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28033. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28034. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28035. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28036. return this;
  28037. }
  28038. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28039. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28040. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28041. var position = BABYLON.Vector3.Zero();
  28042. var normal = BABYLON.Vector3.Zero();
  28043. var uv = BABYLON.Vector2.Zero();
  28044. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28045. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28046. for (var index = 0; index < positions.length; index += 3) {
  28047. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28048. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28049. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28050. // Compute height
  28051. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28052. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28053. var pos = (u + v * heightMapWidth) * 4;
  28054. var r = buffer[pos] / 255.0;
  28055. var g = buffer[pos + 1] / 255.0;
  28056. var b = buffer[pos + 2] / 255.0;
  28057. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28058. normal.normalize();
  28059. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28060. position = position.add(normal);
  28061. position.toArray(positions, index);
  28062. }
  28063. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28064. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28065. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28066. return this;
  28067. };
  28068. /**
  28069. * Modify the mesh to get a flat shading rendering.
  28070. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28071. * This method returns the Mesh.
  28072. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28073. */
  28074. Mesh.prototype.convertToFlatShadedMesh = function () {
  28075. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28076. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28077. var kinds = this.getVerticesDataKinds();
  28078. var vbs = {};
  28079. var data = {};
  28080. var newdata = {};
  28081. var updatableNormals = false;
  28082. var kindIndex;
  28083. var kind;
  28084. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28085. kind = kinds[kindIndex];
  28086. var vertexBuffer = this.getVertexBuffer(kind);
  28087. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28088. updatableNormals = vertexBuffer.isUpdatable();
  28089. kinds.splice(kindIndex, 1);
  28090. kindIndex--;
  28091. continue;
  28092. }
  28093. vbs[kind] = vertexBuffer;
  28094. data[kind] = vbs[kind].getData();
  28095. newdata[kind] = [];
  28096. }
  28097. // Save previous submeshes
  28098. var previousSubmeshes = this.subMeshes.slice(0);
  28099. var indices = this.getIndices();
  28100. var totalIndices = this.getTotalIndices();
  28101. // Generating unique vertices per face
  28102. var index;
  28103. for (index = 0; index < totalIndices; index++) {
  28104. var vertexIndex = indices[index];
  28105. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28106. kind = kinds[kindIndex];
  28107. var stride = vbs[kind].getStrideSize();
  28108. for (var offset = 0; offset < stride; offset++) {
  28109. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28110. }
  28111. }
  28112. }
  28113. // Updating faces & normal
  28114. var normals = [];
  28115. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28116. for (index = 0; index < totalIndices; index += 3) {
  28117. indices[index] = index;
  28118. indices[index + 1] = index + 1;
  28119. indices[index + 2] = index + 2;
  28120. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28121. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28122. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28123. var p1p2 = p1.subtract(p2);
  28124. var p3p2 = p3.subtract(p2);
  28125. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28126. // Store same normals for every vertex
  28127. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28128. normals.push(normal.x);
  28129. normals.push(normal.y);
  28130. normals.push(normal.z);
  28131. }
  28132. }
  28133. this.setIndices(indices);
  28134. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28135. // Updating vertex buffers
  28136. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28137. kind = kinds[kindIndex];
  28138. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28139. }
  28140. // Updating submeshes
  28141. this.releaseSubMeshes();
  28142. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28143. var previousOne = previousSubmeshes[submeshIndex];
  28144. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28145. }
  28146. this.synchronizeInstances();
  28147. return this;
  28148. };
  28149. /**
  28150. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28151. * In other words, more vertices, no more indices and a single bigger VBO.
  28152. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28153. * Returns the Mesh.
  28154. */
  28155. Mesh.prototype.convertToUnIndexedMesh = function () {
  28156. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28157. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28158. var kinds = this.getVerticesDataKinds();
  28159. var vbs = {};
  28160. var data = {};
  28161. var newdata = {};
  28162. var kindIndex;
  28163. var kind;
  28164. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28165. kind = kinds[kindIndex];
  28166. var vertexBuffer = this.getVertexBuffer(kind);
  28167. vbs[kind] = vertexBuffer;
  28168. data[kind] = vbs[kind].getData();
  28169. newdata[kind] = [];
  28170. }
  28171. // Save previous submeshes
  28172. var previousSubmeshes = this.subMeshes.slice(0);
  28173. var indices = this.getIndices();
  28174. var totalIndices = this.getTotalIndices();
  28175. // Generating unique vertices per face
  28176. var index;
  28177. for (index = 0; index < totalIndices; index++) {
  28178. var vertexIndex = indices[index];
  28179. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28180. kind = kinds[kindIndex];
  28181. var stride = vbs[kind].getStrideSize();
  28182. for (var offset = 0; offset < stride; offset++) {
  28183. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28184. }
  28185. }
  28186. }
  28187. // Updating indices
  28188. for (index = 0; index < totalIndices; index += 3) {
  28189. indices[index] = index;
  28190. indices[index + 1] = index + 1;
  28191. indices[index + 2] = index + 2;
  28192. }
  28193. this.setIndices(indices);
  28194. // Updating vertex buffers
  28195. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28196. kind = kinds[kindIndex];
  28197. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28198. }
  28199. // Updating submeshes
  28200. this.releaseSubMeshes();
  28201. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28202. var previousOne = previousSubmeshes[submeshIndex];
  28203. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28204. }
  28205. this._unIndexed = true;
  28206. this.synchronizeInstances();
  28207. return this;
  28208. };
  28209. /**
  28210. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28211. * This method returns the Mesh.
  28212. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28213. */
  28214. Mesh.prototype.flipFaces = function (flipNormals) {
  28215. if (flipNormals === void 0) { flipNormals = false; }
  28216. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28217. var i;
  28218. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28219. for (i = 0; i < vertex_data.normals.length; i++) {
  28220. vertex_data.normals[i] *= -1;
  28221. }
  28222. }
  28223. if (vertex_data.indices) {
  28224. var temp;
  28225. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28226. // reassign indices
  28227. temp = vertex_data.indices[i + 1];
  28228. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28229. vertex_data.indices[i + 2] = temp;
  28230. }
  28231. }
  28232. vertex_data.applyToMesh(this);
  28233. return this;
  28234. };
  28235. // Instances
  28236. /**
  28237. * Creates a new InstancedMesh object from the mesh model.
  28238. * An instance shares the same properties and the same material than its model.
  28239. * Only these properties of each instance can then be set individually :
  28240. * - position
  28241. * - rotation
  28242. * - rotationQuaternion
  28243. * - setPivotMatrix
  28244. * - scaling
  28245. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28246. * Warning : this method is not supported for Line mesh and LineSystem
  28247. */
  28248. Mesh.prototype.createInstance = function (name) {
  28249. return new BABYLON.InstancedMesh(name, this);
  28250. };
  28251. /**
  28252. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28253. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28254. * This method returns the Mesh.
  28255. */
  28256. Mesh.prototype.synchronizeInstances = function () {
  28257. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28258. var instance = this.instances[instanceIndex];
  28259. instance._syncSubMeshes();
  28260. }
  28261. return this;
  28262. };
  28263. /**
  28264. * Simplify the mesh according to the given array of settings.
  28265. * Function will return immediately and will simplify async. It returns the Mesh.
  28266. * @param settings a collection of simplification settings.
  28267. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28268. * @param type the type of simplification to run.
  28269. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28270. */
  28271. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28272. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28273. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28274. this.getScene().simplificationQueue.addTask({
  28275. settings: settings,
  28276. parallelProcessing: parallelProcessing,
  28277. mesh: this,
  28278. simplificationType: simplificationType,
  28279. successCallback: successCallback
  28280. });
  28281. return this;
  28282. };
  28283. /**
  28284. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28285. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28286. * This should be used together with the simplification to avoid disappearing triangles.
  28287. * Returns the Mesh.
  28288. * @param successCallback an optional success callback to be called after the optimization finished.
  28289. */
  28290. Mesh.prototype.optimizeIndices = function (successCallback) {
  28291. var _this = this;
  28292. var indices = this.getIndices();
  28293. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28294. if (!positions || !indices) {
  28295. return this;
  28296. }
  28297. var vectorPositions = new Array();
  28298. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28299. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28300. }
  28301. var dupes = new Array();
  28302. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28303. var realPos = vectorPositions.length - 1 - iteration;
  28304. var testedPosition = vectorPositions[realPos];
  28305. for (var j = 0; j < realPos; ++j) {
  28306. var againstPosition = vectorPositions[j];
  28307. if (testedPosition.equals(againstPosition)) {
  28308. dupes[realPos] = j;
  28309. break;
  28310. }
  28311. }
  28312. }, function () {
  28313. for (var i = 0; i < indices.length; ++i) {
  28314. indices[i] = dupes[indices[i]] || indices[i];
  28315. }
  28316. //indices are now reordered
  28317. var originalSubMeshes = _this.subMeshes.slice(0);
  28318. _this.setIndices(indices);
  28319. _this.subMeshes = originalSubMeshes;
  28320. if (successCallback) {
  28321. successCallback(_this);
  28322. }
  28323. });
  28324. return this;
  28325. };
  28326. Mesh.prototype.serialize = function (serializationObject) {
  28327. serializationObject.name = this.name;
  28328. serializationObject.id = this.id;
  28329. serializationObject.type = this.getClassName();
  28330. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28331. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28332. }
  28333. serializationObject.position = this.position.asArray();
  28334. if (this.rotationQuaternion) {
  28335. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28336. }
  28337. else if (this.rotation) {
  28338. serializationObject.rotation = this.rotation.asArray();
  28339. }
  28340. serializationObject.scaling = this.scaling.asArray();
  28341. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28342. serializationObject.isEnabled = this.isEnabled(false);
  28343. serializationObject.isVisible = this.isVisible;
  28344. serializationObject.infiniteDistance = this.infiniteDistance;
  28345. serializationObject.pickable = this.isPickable;
  28346. serializationObject.receiveShadows = this.receiveShadows;
  28347. serializationObject.billboardMode = this.billboardMode;
  28348. serializationObject.visibility = this.visibility;
  28349. serializationObject.checkCollisions = this.checkCollisions;
  28350. serializationObject.isBlocker = this.isBlocker;
  28351. // Parent
  28352. if (this.parent) {
  28353. serializationObject.parentId = this.parent.id;
  28354. }
  28355. // Geometry
  28356. serializationObject.isUnIndexed = this.isUnIndexed;
  28357. var geometry = this._geometry;
  28358. if (geometry) {
  28359. var geometryId = geometry.id;
  28360. serializationObject.geometryId = geometryId;
  28361. // SubMeshes
  28362. serializationObject.subMeshes = [];
  28363. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28364. var subMesh = this.subMeshes[subIndex];
  28365. serializationObject.subMeshes.push({
  28366. materialIndex: subMesh.materialIndex,
  28367. verticesStart: subMesh.verticesStart,
  28368. verticesCount: subMesh.verticesCount,
  28369. indexStart: subMesh.indexStart,
  28370. indexCount: subMesh.indexCount
  28371. });
  28372. }
  28373. }
  28374. // Material
  28375. if (this.material) {
  28376. serializationObject.materialId = this.material.id;
  28377. }
  28378. else {
  28379. this.material = null;
  28380. }
  28381. // Morph targets
  28382. if (this.morphTargetManager) {
  28383. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28384. }
  28385. // Skeleton
  28386. if (this.skeleton) {
  28387. serializationObject.skeletonId = this.skeleton.id;
  28388. }
  28389. // Physics
  28390. //TODO implement correct serialization for physics impostors.
  28391. var impostor = this.getPhysicsImpostor();
  28392. if (impostor) {
  28393. serializationObject.physicsMass = impostor.getParam("mass");
  28394. serializationObject.physicsFriction = impostor.getParam("friction");
  28395. serializationObject.physicsRestitution = impostor.getParam("mass");
  28396. serializationObject.physicsImpostor = impostor.type;
  28397. }
  28398. // Metadata
  28399. if (this.metadata) {
  28400. serializationObject.metadata = this.metadata;
  28401. }
  28402. // Instances
  28403. serializationObject.instances = [];
  28404. for (var index = 0; index < this.instances.length; index++) {
  28405. var instance = this.instances[index];
  28406. var serializationInstance = {
  28407. name: instance.name,
  28408. id: instance.id,
  28409. position: instance.position.asArray(),
  28410. scaling: instance.scaling.asArray()
  28411. };
  28412. if (instance.rotationQuaternion) {
  28413. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28414. }
  28415. else if (instance.rotation) {
  28416. serializationInstance.rotation = instance.rotation.asArray();
  28417. }
  28418. serializationObject.instances.push(serializationInstance);
  28419. // Animations
  28420. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28421. serializationInstance.ranges = instance.serializeAnimationRanges();
  28422. }
  28423. //
  28424. // Animations
  28425. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28426. serializationObject.ranges = this.serializeAnimationRanges();
  28427. // Layer mask
  28428. serializationObject.layerMask = this.layerMask;
  28429. // Alpha
  28430. serializationObject.alphaIndex = this.alphaIndex;
  28431. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28432. // Overlay
  28433. serializationObject.overlayAlpha = this.overlayAlpha;
  28434. serializationObject.overlayColor = this.overlayColor.asArray();
  28435. serializationObject.renderOverlay = this.renderOverlay;
  28436. // Fog
  28437. serializationObject.applyFog = this.applyFog;
  28438. // Action Manager
  28439. if (this.actionManager) {
  28440. serializationObject.actions = this.actionManager.serialize(this.name);
  28441. }
  28442. };
  28443. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28444. if (!this.geometry) {
  28445. return;
  28446. }
  28447. this._markSubMeshesAsAttributesDirty();
  28448. var morphTargetManager = this._morphTargetManager;
  28449. if (morphTargetManager && morphTargetManager.vertexCount) {
  28450. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28451. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28452. this.morphTargetManager = null;
  28453. return;
  28454. }
  28455. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28456. var morphTarget = morphTargetManager.getActiveTarget(index);
  28457. var positions = morphTarget.getPositions();
  28458. if (!positions) {
  28459. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28460. return;
  28461. }
  28462. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28463. var normals = morphTarget.getNormals();
  28464. if (normals) {
  28465. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28466. }
  28467. var tangents = morphTarget.getTangents();
  28468. if (tangents) {
  28469. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28470. }
  28471. }
  28472. }
  28473. else {
  28474. var index = 0;
  28475. // Positions
  28476. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28477. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28478. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28479. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28480. }
  28481. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28482. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28483. }
  28484. index++;
  28485. }
  28486. }
  28487. };
  28488. // Statics
  28489. /**
  28490. * Returns a new Mesh object parsed from the source provided.
  28491. * The parameter `parsedMesh` is the source.
  28492. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28493. */
  28494. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28495. var mesh;
  28496. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28497. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28498. }
  28499. else {
  28500. mesh = new Mesh(parsedMesh.name, scene);
  28501. }
  28502. mesh.id = parsedMesh.id;
  28503. if (BABYLON.Tags) {
  28504. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28505. }
  28506. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28507. if (parsedMesh.metadata !== undefined) {
  28508. mesh.metadata = parsedMesh.metadata;
  28509. }
  28510. if (parsedMesh.rotationQuaternion) {
  28511. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28512. }
  28513. else if (parsedMesh.rotation) {
  28514. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28515. }
  28516. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28517. if (parsedMesh.localMatrix) {
  28518. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28519. }
  28520. else if (parsedMesh.pivotMatrix) {
  28521. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28522. }
  28523. mesh.setEnabled(parsedMesh.isEnabled);
  28524. mesh.isVisible = parsedMesh.isVisible;
  28525. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28526. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28527. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28528. if (parsedMesh.applyFog !== undefined) {
  28529. mesh.applyFog = parsedMesh.applyFog;
  28530. }
  28531. if (parsedMesh.pickable !== undefined) {
  28532. mesh.isPickable = parsedMesh.pickable;
  28533. }
  28534. if (parsedMesh.alphaIndex !== undefined) {
  28535. mesh.alphaIndex = parsedMesh.alphaIndex;
  28536. }
  28537. mesh.receiveShadows = parsedMesh.receiveShadows;
  28538. mesh.billboardMode = parsedMesh.billboardMode;
  28539. if (parsedMesh.visibility !== undefined) {
  28540. mesh.visibility = parsedMesh.visibility;
  28541. }
  28542. mesh.checkCollisions = parsedMesh.checkCollisions;
  28543. if (parsedMesh.isBlocker !== undefined) {
  28544. mesh.isBlocker = parsedMesh.isBlocker;
  28545. }
  28546. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28547. // freezeWorldMatrix
  28548. if (parsedMesh.freezeWorldMatrix) {
  28549. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28550. }
  28551. // Parent
  28552. if (parsedMesh.parentId) {
  28553. mesh._waitingParentId = parsedMesh.parentId;
  28554. }
  28555. // Actions
  28556. if (parsedMesh.actions !== undefined) {
  28557. mesh._waitingActions = parsedMesh.actions;
  28558. }
  28559. // Overlay
  28560. if (parsedMesh.overlayAlpha !== undefined) {
  28561. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28562. }
  28563. if (parsedMesh.overlayColor !== undefined) {
  28564. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28565. }
  28566. if (parsedMesh.renderOverlay !== undefined) {
  28567. mesh.renderOverlay = parsedMesh.renderOverlay;
  28568. }
  28569. // Geometry
  28570. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28571. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28572. if (parsedMesh.delayLoadingFile) {
  28573. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28574. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28575. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28576. if (parsedMesh._binaryInfo) {
  28577. mesh._binaryInfo = parsedMesh._binaryInfo;
  28578. }
  28579. mesh._delayInfo = [];
  28580. if (parsedMesh.hasUVs) {
  28581. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28582. }
  28583. if (parsedMesh.hasUVs2) {
  28584. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28585. }
  28586. if (parsedMesh.hasUVs3) {
  28587. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28588. }
  28589. if (parsedMesh.hasUVs4) {
  28590. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28591. }
  28592. if (parsedMesh.hasUVs5) {
  28593. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28594. }
  28595. if (parsedMesh.hasUVs6) {
  28596. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28597. }
  28598. if (parsedMesh.hasColors) {
  28599. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28600. }
  28601. if (parsedMesh.hasMatricesIndices) {
  28602. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28603. }
  28604. if (parsedMesh.hasMatricesWeights) {
  28605. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28606. }
  28607. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28608. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28609. mesh._checkDelayState();
  28610. }
  28611. }
  28612. else {
  28613. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28614. }
  28615. // Material
  28616. if (parsedMesh.materialId) {
  28617. mesh.setMaterialByID(parsedMesh.materialId);
  28618. }
  28619. else {
  28620. mesh.material = null;
  28621. }
  28622. // Morph targets
  28623. if (parsedMesh.morphTargetManagerId > -1) {
  28624. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28625. }
  28626. // Skeleton
  28627. if (parsedMesh.skeletonId > -1) {
  28628. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28629. if (parsedMesh.numBoneInfluencers) {
  28630. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28631. }
  28632. }
  28633. // Animations
  28634. if (parsedMesh.animations) {
  28635. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28636. var parsedAnimation = parsedMesh.animations[animationIndex];
  28637. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28638. }
  28639. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28640. }
  28641. if (parsedMesh.autoAnimate) {
  28642. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28643. }
  28644. // Layer Mask
  28645. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28646. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28647. }
  28648. else {
  28649. mesh.layerMask = 0x0FFFFFFF;
  28650. }
  28651. // Physics
  28652. if (parsedMesh.physicsImpostor) {
  28653. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28654. mass: parsedMesh.physicsMass,
  28655. friction: parsedMesh.physicsFriction,
  28656. restitution: parsedMesh.physicsRestitution
  28657. }, scene);
  28658. }
  28659. // Instances
  28660. if (parsedMesh.instances) {
  28661. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28662. var parsedInstance = parsedMesh.instances[index];
  28663. var instance = mesh.createInstance(parsedInstance.name);
  28664. if (parsedInstance.id) {
  28665. instance.id = parsedInstance.id;
  28666. }
  28667. if (BABYLON.Tags) {
  28668. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28669. }
  28670. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28671. if (parsedInstance.parentId) {
  28672. instance._waitingParentId = parsedInstance.parentId;
  28673. }
  28674. if (parsedInstance.rotationQuaternion) {
  28675. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28676. }
  28677. else if (parsedInstance.rotation) {
  28678. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28679. }
  28680. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28681. instance.checkCollisions = mesh.checkCollisions;
  28682. if (parsedMesh.animations) {
  28683. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28684. parsedAnimation = parsedMesh.animations[animationIndex];
  28685. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28686. }
  28687. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28688. }
  28689. }
  28690. }
  28691. return mesh;
  28692. };
  28693. /**
  28694. * Creates a ribbon mesh.
  28695. * Please consider using the same method from the MeshBuilder class instead.
  28696. * 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.
  28697. *
  28698. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28699. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28700. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28701. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28702. * 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.
  28703. * 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.
  28704. * 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
  28705. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28706. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28708. */
  28709. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28710. if (closeArray === void 0) { closeArray = false; }
  28711. if (updatable === void 0) { updatable = false; }
  28712. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28713. pathArray: pathArray,
  28714. closeArray: closeArray,
  28715. closePath: closePath,
  28716. offset: offset,
  28717. updatable: updatable,
  28718. sideOrientation: sideOrientation,
  28719. instance: instance
  28720. }, scene);
  28721. };
  28722. /**
  28723. * Creates a plane polygonal mesh. By default, this is a disc.
  28724. * Please consider using the same method from the MeshBuilder class instead.
  28725. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28726. * 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.
  28727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28728. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28730. */
  28731. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28732. if (scene === void 0) { scene = null; }
  28733. var options = {
  28734. radius: radius,
  28735. tessellation: tessellation,
  28736. sideOrientation: sideOrientation,
  28737. updatable: updatable
  28738. };
  28739. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28740. };
  28741. /**
  28742. * Creates a box mesh.
  28743. * Please consider using the same method from the MeshBuilder class instead.
  28744. * The parameter `size` sets the size (float) of each box side (default 1).
  28745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28748. */
  28749. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28750. if (scene === void 0) { scene = null; }
  28751. var options = {
  28752. size: size,
  28753. sideOrientation: sideOrientation,
  28754. updatable: updatable
  28755. };
  28756. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28757. };
  28758. /**
  28759. * Creates a sphere mesh.
  28760. * Please consider using the same method from the MeshBuilder class instead.
  28761. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28762. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28763. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28764. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28766. */
  28767. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28768. var options = {
  28769. segments: segments,
  28770. diameterX: diameter,
  28771. diameterY: diameter,
  28772. diameterZ: diameter,
  28773. sideOrientation: sideOrientation,
  28774. updatable: updatable
  28775. };
  28776. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28777. };
  28778. /**
  28779. * Creates a cylinder or a cone mesh.
  28780. * Please consider using the same method from the MeshBuilder class instead.
  28781. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28782. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28783. * 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.
  28784. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28785. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28789. */
  28790. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28791. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28792. if (scene !== undefined) {
  28793. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28794. updatable = scene;
  28795. }
  28796. scene = subdivisions;
  28797. subdivisions = 1;
  28798. }
  28799. var options = {
  28800. height: height,
  28801. diameterTop: diameterTop,
  28802. diameterBottom: diameterBottom,
  28803. tessellation: tessellation,
  28804. subdivisions: subdivisions,
  28805. sideOrientation: sideOrientation,
  28806. updatable: updatable
  28807. };
  28808. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28809. };
  28810. // Torus (Code from SharpDX.org)
  28811. /**
  28812. * Creates a torus mesh.
  28813. * Please consider using the same method from the MeshBuilder class instead.
  28814. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28815. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28816. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28820. */
  28821. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28822. var options = {
  28823. diameter: diameter,
  28824. thickness: thickness,
  28825. tessellation: tessellation,
  28826. sideOrientation: sideOrientation,
  28827. updatable: updatable
  28828. };
  28829. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28830. };
  28831. /**
  28832. * Creates a torus knot mesh.
  28833. * Please consider using the same method from the MeshBuilder class instead.
  28834. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28835. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28836. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28837. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28841. */
  28842. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28843. var options = {
  28844. radius: radius,
  28845. tube: tube,
  28846. radialSegments: radialSegments,
  28847. tubularSegments: tubularSegments,
  28848. p: p,
  28849. q: q,
  28850. sideOrientation: sideOrientation,
  28851. updatable: updatable
  28852. };
  28853. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28854. };
  28855. /**
  28856. * Creates a line mesh.
  28857. * Please consider using the same method from the MeshBuilder class instead.
  28858. * 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.
  28859. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28860. * The parameter `points` is an array successive Vector3.
  28861. * 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
  28862. * When updating an instance, remember that only point positions can change, not the number of points.
  28863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28864. */
  28865. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28866. if (scene === void 0) { scene = null; }
  28867. if (updatable === void 0) { updatable = false; }
  28868. if (instance === void 0) { instance = null; }
  28869. var options = {
  28870. points: points,
  28871. updatable: updatable,
  28872. instance: instance
  28873. };
  28874. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28875. };
  28876. /**
  28877. * Creates a dashed line mesh.
  28878. * Please consider using the same method from the MeshBuilder class instead.
  28879. * 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.
  28880. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28881. * The parameter `points` is an array successive Vector3.
  28882. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28883. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28884. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28885. * 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
  28886. * When updating an instance, remember that only point positions can change, not the number of points.
  28887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28888. */
  28889. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28890. if (scene === void 0) { scene = null; }
  28891. var options = {
  28892. points: points,
  28893. dashSize: dashSize,
  28894. gapSize: gapSize,
  28895. dashNb: dashNb,
  28896. updatable: updatable,
  28897. instance: instance
  28898. };
  28899. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28900. };
  28901. /**
  28902. * Creates a polygon mesh.
  28903. * Please consider using the same method from the MeshBuilder class instead.
  28904. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28905. * 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.
  28906. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28908. * Remember you can only change the shape positions, not their number when updating a polygon.
  28909. */
  28910. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28911. var options = {
  28912. shape: shape,
  28913. holes: holes,
  28914. updatable: updatable,
  28915. sideOrientation: sideOrientation
  28916. };
  28917. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28918. };
  28919. /**
  28920. * Creates an extruded polygon mesh, with depth in the Y direction.
  28921. * Please consider using the same method from the MeshBuilder class instead.
  28922. */
  28923. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28924. var options = {
  28925. shape: shape,
  28926. holes: holes,
  28927. depth: depth,
  28928. updatable: updatable,
  28929. sideOrientation: sideOrientation
  28930. };
  28931. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28932. };
  28933. /**
  28934. * Creates an extruded shape mesh.
  28935. * 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.
  28936. * Please consider using the same method from the MeshBuilder class instead.
  28937. *
  28938. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28939. * 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
  28940. * extruded along the Z axis.
  28941. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28942. * 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.
  28943. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28944. * 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
  28945. * 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
  28946. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28950. */
  28951. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28952. if (scene === void 0) { scene = null; }
  28953. var options = {
  28954. shape: shape,
  28955. path: path,
  28956. scale: scale,
  28957. rotation: rotation,
  28958. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28959. sideOrientation: sideOrientation,
  28960. instance: instance,
  28961. updatable: updatable
  28962. };
  28963. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28964. };
  28965. /**
  28966. * Creates an custom extruded shape mesh.
  28967. * 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.
  28968. * Please consider using the same method from the MeshBuilder class instead.
  28969. *
  28970. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28971. * 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
  28972. * extruded along the Z axis.
  28973. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28974. * 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
  28975. * and the distance of this point from the begining of the path :
  28976. * ```javascript
  28977. * var rotationFunction = function(i, distance) {
  28978. * // do things
  28979. * return rotationValue; }
  28980. * ```
  28981. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28982. * 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
  28983. * and the distance of this point from the begining of the path :
  28984. * ```javascript
  28985. * var scaleFunction = function(i, distance) {
  28986. * // do things
  28987. * return scaleValue;}
  28988. * ```
  28989. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28990. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28991. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28992. * 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
  28993. * 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
  28994. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28995. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28996. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28998. */
  28999. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29000. var options = {
  29001. shape: shape,
  29002. path: path,
  29003. scaleFunction: scaleFunction,
  29004. rotationFunction: rotationFunction,
  29005. ribbonCloseArray: ribbonCloseArray,
  29006. ribbonClosePath: ribbonClosePath,
  29007. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29008. sideOrientation: sideOrientation,
  29009. instance: instance,
  29010. updatable: updatable
  29011. };
  29012. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29013. };
  29014. /**
  29015. * Creates lathe mesh.
  29016. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29017. * Please consider using the same method from the MeshBuilder class instead.
  29018. * 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
  29019. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29020. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29021. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29023. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29025. */
  29026. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29027. var options = {
  29028. shape: shape,
  29029. radius: radius,
  29030. tessellation: tessellation,
  29031. sideOrientation: sideOrientation,
  29032. updatable: updatable
  29033. };
  29034. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29035. };
  29036. /**
  29037. * Creates a plane mesh.
  29038. * Please consider using the same method from the MeshBuilder class instead.
  29039. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29040. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29041. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29043. */
  29044. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29045. var options = {
  29046. size: size,
  29047. width: size,
  29048. height: size,
  29049. sideOrientation: sideOrientation,
  29050. updatable: updatable
  29051. };
  29052. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29053. };
  29054. /**
  29055. * Creates a ground mesh.
  29056. * Please consider using the same method from the MeshBuilder class instead.
  29057. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29058. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29059. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29060. */
  29061. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29062. var options = {
  29063. width: width,
  29064. height: height,
  29065. subdivisions: subdivisions,
  29066. updatable: updatable
  29067. };
  29068. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29069. };
  29070. /**
  29071. * Creates a tiled ground mesh.
  29072. * Please consider using the same method from the MeshBuilder class instead.
  29073. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29074. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29075. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29076. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29077. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29078. * numbers of subdivisions on the ground width and height of each tile.
  29079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29080. */
  29081. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29082. var options = {
  29083. xmin: xmin,
  29084. zmin: zmin,
  29085. xmax: xmax,
  29086. zmax: zmax,
  29087. subdivisions: subdivisions,
  29088. precision: precision,
  29089. updatable: updatable
  29090. };
  29091. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29092. };
  29093. /**
  29094. * Creates a ground mesh from a height map.
  29095. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29096. * Please consider using the same method from the MeshBuilder class instead.
  29097. * The parameter `url` sets the URL of the height map image resource.
  29098. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29099. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29100. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29101. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29102. * 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).
  29103. * This function is passed the newly built mesh :
  29104. * ```javascript
  29105. * function(mesh) { // do things
  29106. * return; }
  29107. * ```
  29108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29109. */
  29110. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29111. var options = {
  29112. width: width,
  29113. height: height,
  29114. subdivisions: subdivisions,
  29115. minHeight: minHeight,
  29116. maxHeight: maxHeight,
  29117. updatable: updatable,
  29118. onReady: onReady
  29119. };
  29120. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29121. };
  29122. /**
  29123. * Creates a tube mesh.
  29124. * 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.
  29125. * Please consider using the same method from the MeshBuilder class instead.
  29126. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29127. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29128. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29129. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29130. * 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.
  29131. * It must return a radius value (positive float) :
  29132. * ```javascript
  29133. * var radiusFunction = function(i, distance) {
  29134. * // do things
  29135. * return radius; }
  29136. * ```
  29137. * 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
  29138. * 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
  29139. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29140. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29141. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29142. */
  29143. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29144. var options = {
  29145. path: path,
  29146. radius: radius,
  29147. tessellation: tessellation,
  29148. radiusFunction: radiusFunction,
  29149. arc: 1,
  29150. cap: cap,
  29151. updatable: updatable,
  29152. sideOrientation: sideOrientation,
  29153. instance: instance
  29154. };
  29155. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29156. };
  29157. /**
  29158. * Creates a polyhedron mesh.
  29159. * Please consider using the same method from the MeshBuilder class instead.
  29160. * 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
  29161. * to choose the wanted type.
  29162. * The parameter `size` (positive float, default 1) sets the polygon size.
  29163. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29164. * 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`.
  29165. * 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
  29166. * 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)`).
  29167. * 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
  29168. * 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.
  29169. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29170. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29172. */
  29173. Mesh.CreatePolyhedron = function (name, options, scene) {
  29174. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29175. };
  29176. /**
  29177. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29178. * Please consider using the same method from the MeshBuilder class instead.
  29179. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29180. * 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`).
  29181. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29182. * 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.
  29183. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29184. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29185. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29186. */
  29187. Mesh.CreateIcoSphere = function (name, options, scene) {
  29188. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29189. };
  29190. /**
  29191. * Creates a decal mesh.
  29192. * Please consider using the same method from the MeshBuilder class instead.
  29193. * 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.
  29194. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29195. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29196. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29197. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29198. */
  29199. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29200. var options = {
  29201. position: position,
  29202. normal: normal,
  29203. size: size,
  29204. angle: angle
  29205. };
  29206. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29207. };
  29208. // Skeletons
  29209. /**
  29210. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29211. */
  29212. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29213. if (!this._sourcePositions) {
  29214. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29215. if (!source) {
  29216. return this._sourcePositions;
  29217. }
  29218. this._sourcePositions = new Float32Array(source);
  29219. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29220. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29221. }
  29222. }
  29223. return this._sourcePositions;
  29224. };
  29225. /**
  29226. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29227. */
  29228. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29229. if (!this._sourceNormals) {
  29230. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29231. if (!source) {
  29232. return this._sourceNormals;
  29233. }
  29234. this._sourceNormals = new Float32Array(source);
  29235. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29236. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29237. }
  29238. }
  29239. return this._sourceNormals;
  29240. };
  29241. /**
  29242. * Updates the vertex buffer by applying transformation from the bones.
  29243. * Returns the Mesh.
  29244. *
  29245. * @param {skeleton} skeleton to apply
  29246. */
  29247. Mesh.prototype.applySkeleton = function (skeleton) {
  29248. if (!this.geometry) {
  29249. return this;
  29250. }
  29251. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29252. return this;
  29253. }
  29254. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29255. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29256. return this;
  29257. }
  29258. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29259. return this;
  29260. }
  29261. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29262. return this;
  29263. }
  29264. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29265. return this;
  29266. }
  29267. if (!this._sourcePositions) {
  29268. var submeshes = this.subMeshes.slice();
  29269. this.setPositionsForCPUSkinning();
  29270. this.subMeshes = submeshes;
  29271. }
  29272. if (!this._sourceNormals) {
  29273. this.setNormalsForCPUSkinning();
  29274. }
  29275. // positionsData checks for not being Float32Array will only pass at most once
  29276. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29277. if (!positionsData) {
  29278. return this;
  29279. }
  29280. if (!(positionsData instanceof Float32Array)) {
  29281. positionsData = new Float32Array(positionsData);
  29282. }
  29283. // normalsData checks for not being Float32Array will only pass at most once
  29284. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29285. if (!normalsData) {
  29286. return this;
  29287. }
  29288. if (!(normalsData instanceof Float32Array)) {
  29289. normalsData = new Float32Array(normalsData);
  29290. }
  29291. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29292. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29293. if (!matricesWeightsData || !matricesIndicesData) {
  29294. return this;
  29295. }
  29296. var needExtras = this.numBoneInfluencers > 4;
  29297. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29298. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29299. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29300. var tempVector3 = BABYLON.Vector3.Zero();
  29301. var finalMatrix = new BABYLON.Matrix();
  29302. var tempMatrix = new BABYLON.Matrix();
  29303. var matWeightIdx = 0;
  29304. var inf;
  29305. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29306. var weight;
  29307. for (inf = 0; inf < 4; inf++) {
  29308. weight = matricesWeightsData[matWeightIdx + inf];
  29309. if (weight > 0) {
  29310. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29311. finalMatrix.addToSelf(tempMatrix);
  29312. }
  29313. else
  29314. break;
  29315. }
  29316. if (needExtras) {
  29317. for (inf = 0; inf < 4; inf++) {
  29318. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29319. if (weight > 0) {
  29320. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29321. finalMatrix.addToSelf(tempMatrix);
  29322. }
  29323. else
  29324. break;
  29325. }
  29326. }
  29327. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29328. tempVector3.toArray(positionsData, index);
  29329. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29330. tempVector3.toArray(normalsData, index);
  29331. finalMatrix.reset();
  29332. }
  29333. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29334. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29335. return this;
  29336. };
  29337. // Tools
  29338. /**
  29339. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29340. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29341. */
  29342. Mesh.MinMax = function (meshes) {
  29343. var minVector = null;
  29344. var maxVector = null;
  29345. meshes.forEach(function (mesh, index, array) {
  29346. var boundingInfo = mesh.getBoundingInfo();
  29347. var boundingBox = boundingInfo.boundingBox;
  29348. if (!minVector || !maxVector) {
  29349. minVector = boundingBox.minimumWorld;
  29350. maxVector = boundingBox.maximumWorld;
  29351. }
  29352. else {
  29353. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29354. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29355. }
  29356. });
  29357. if (!minVector || !maxVector) {
  29358. return {
  29359. min: BABYLON.Vector3.Zero(),
  29360. max: BABYLON.Vector3.Zero()
  29361. };
  29362. }
  29363. return {
  29364. min: minVector,
  29365. max: maxVector
  29366. };
  29367. };
  29368. /**
  29369. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29370. */
  29371. Mesh.Center = function (meshesOrMinMaxVector) {
  29372. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29373. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29374. };
  29375. /**
  29376. * Merge the array of meshes into a single mesh for performance reasons.
  29377. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29378. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29379. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29380. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29381. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29382. */
  29383. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29384. if (disposeSource === void 0) { disposeSource = true; }
  29385. var index;
  29386. if (!allow32BitsIndices) {
  29387. var totalVertices = 0;
  29388. // Counting vertices
  29389. for (index = 0; index < meshes.length; index++) {
  29390. if (meshes[index]) {
  29391. totalVertices += meshes[index].getTotalVertices();
  29392. if (totalVertices > 65536) {
  29393. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29394. return null;
  29395. }
  29396. }
  29397. }
  29398. }
  29399. // Merge
  29400. var vertexData = null;
  29401. var otherVertexData;
  29402. var indiceArray = new Array();
  29403. var source = null;
  29404. for (index = 0; index < meshes.length; index++) {
  29405. if (meshes[index]) {
  29406. meshes[index].computeWorldMatrix(true);
  29407. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29408. otherVertexData.transform(meshes[index].getWorldMatrix());
  29409. if (vertexData) {
  29410. vertexData.merge(otherVertexData);
  29411. }
  29412. else {
  29413. vertexData = otherVertexData;
  29414. source = meshes[index];
  29415. }
  29416. if (subdivideWithSubMeshes) {
  29417. indiceArray.push(meshes[index].getTotalIndices());
  29418. }
  29419. }
  29420. }
  29421. source = source;
  29422. if (!meshSubclass) {
  29423. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29424. }
  29425. vertexData.applyToMesh(meshSubclass);
  29426. // Setting properties
  29427. meshSubclass.material = source.material;
  29428. meshSubclass.checkCollisions = source.checkCollisions;
  29429. // Cleaning
  29430. if (disposeSource) {
  29431. for (index = 0; index < meshes.length; index++) {
  29432. if (meshes[index]) {
  29433. meshes[index].dispose();
  29434. }
  29435. }
  29436. }
  29437. // Subdivide
  29438. if (subdivideWithSubMeshes) {
  29439. //-- Suppresions du submesh global
  29440. meshSubclass.releaseSubMeshes();
  29441. index = 0;
  29442. var offset = 0;
  29443. //-- aplique la subdivision en fonction du tableau d'indices
  29444. while (index < indiceArray.length) {
  29445. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29446. offset += indiceArray[index];
  29447. index++;
  29448. }
  29449. }
  29450. return meshSubclass;
  29451. };
  29452. // Consts
  29453. Mesh._FRONTSIDE = 0;
  29454. Mesh._BACKSIDE = 1;
  29455. Mesh._DOUBLESIDE = 2;
  29456. Mesh._DEFAULTSIDE = 0;
  29457. Mesh._NO_CAP = 0;
  29458. Mesh._CAP_START = 1;
  29459. Mesh._CAP_END = 2;
  29460. Mesh._CAP_ALL = 3;
  29461. return Mesh;
  29462. }(BABYLON.AbstractMesh));
  29463. BABYLON.Mesh = Mesh;
  29464. })(BABYLON || (BABYLON = {}));
  29465. //# sourceMappingURL=babylon.mesh.js.map
  29466. var BABYLON;
  29467. (function (BABYLON) {
  29468. var BaseSubMesh = /** @class */ (function () {
  29469. function BaseSubMesh() {
  29470. }
  29471. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29472. get: function () {
  29473. return this._materialEffect;
  29474. },
  29475. enumerable: true,
  29476. configurable: true
  29477. });
  29478. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29479. if (defines === void 0) { defines = null; }
  29480. if (this._materialEffect === effect) {
  29481. if (!effect) {
  29482. this._materialDefines = null;
  29483. }
  29484. return;
  29485. }
  29486. this._materialDefines = defines;
  29487. this._materialEffect = effect;
  29488. };
  29489. return BaseSubMesh;
  29490. }());
  29491. BABYLON.BaseSubMesh = BaseSubMesh;
  29492. var SubMesh = /** @class */ (function (_super) {
  29493. __extends(SubMesh, _super);
  29494. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29495. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29496. var _this = _super.call(this) || this;
  29497. _this.materialIndex = materialIndex;
  29498. _this.verticesStart = verticesStart;
  29499. _this.verticesCount = verticesCount;
  29500. _this.indexStart = indexStart;
  29501. _this.indexCount = indexCount;
  29502. _this._renderId = 0;
  29503. _this._mesh = mesh;
  29504. _this._renderingMesh = renderingMesh || mesh;
  29505. mesh.subMeshes.push(_this);
  29506. _this._trianglePlanes = [];
  29507. _this._id = mesh.subMeshes.length - 1;
  29508. if (createBoundingBox) {
  29509. _this.refreshBoundingInfo();
  29510. mesh.computeWorldMatrix(true);
  29511. }
  29512. return _this;
  29513. }
  29514. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29515. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29516. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29517. };
  29518. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29519. get: function () {
  29520. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29521. },
  29522. enumerable: true,
  29523. configurable: true
  29524. });
  29525. /**
  29526. * Returns the submesh BoudingInfo object.
  29527. */
  29528. SubMesh.prototype.getBoundingInfo = function () {
  29529. if (this.IsGlobal) {
  29530. return this._mesh.getBoundingInfo();
  29531. }
  29532. return this._boundingInfo;
  29533. };
  29534. /**
  29535. * Sets the submesh BoundingInfo.
  29536. * Return the SubMesh.
  29537. */
  29538. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29539. this._boundingInfo = boundingInfo;
  29540. return this;
  29541. };
  29542. /**
  29543. * Returns the mesh of the current submesh.
  29544. */
  29545. SubMesh.prototype.getMesh = function () {
  29546. return this._mesh;
  29547. };
  29548. /**
  29549. * Returns the rendering mesh of the submesh.
  29550. */
  29551. SubMesh.prototype.getRenderingMesh = function () {
  29552. return this._renderingMesh;
  29553. };
  29554. /**
  29555. * Returns the submesh material.
  29556. */
  29557. SubMesh.prototype.getMaterial = function () {
  29558. var rootMaterial = this._renderingMesh.material;
  29559. if (rootMaterial === null || rootMaterial === undefined) {
  29560. return this._mesh.getScene().defaultMaterial;
  29561. }
  29562. else if (rootMaterial.getSubMaterial) {
  29563. var multiMaterial = rootMaterial;
  29564. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29565. if (this._currentMaterial !== effectiveMaterial) {
  29566. this._currentMaterial = effectiveMaterial;
  29567. this._materialDefines = null;
  29568. }
  29569. return effectiveMaterial;
  29570. }
  29571. return rootMaterial;
  29572. };
  29573. // Methods
  29574. /**
  29575. * Sets a new updated BoundingInfo object to the submesh.
  29576. * Returns the SubMesh.
  29577. */
  29578. SubMesh.prototype.refreshBoundingInfo = function () {
  29579. this._lastColliderWorldVertices = null;
  29580. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29581. return this;
  29582. }
  29583. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29584. if (!data) {
  29585. this._boundingInfo = this._mesh.getBoundingInfo();
  29586. return this;
  29587. }
  29588. var indices = this._renderingMesh.getIndices();
  29589. var extend;
  29590. //is this the only submesh?
  29591. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29592. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29593. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29594. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29595. }
  29596. else {
  29597. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29598. }
  29599. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29600. return this;
  29601. };
  29602. SubMesh.prototype._checkCollision = function (collider) {
  29603. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29604. return boundingInfo._checkCollision(collider);
  29605. };
  29606. /**
  29607. * Updates the submesh BoundingInfo.
  29608. * Returns the Submesh.
  29609. */
  29610. SubMesh.prototype.updateBoundingInfo = function (world) {
  29611. var boundingInfo = this.getBoundingInfo();
  29612. if (!boundingInfo) {
  29613. this.refreshBoundingInfo();
  29614. boundingInfo = this.getBoundingInfo();
  29615. }
  29616. boundingInfo.update(world);
  29617. return this;
  29618. };
  29619. /**
  29620. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29621. * Boolean returned.
  29622. */
  29623. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29624. var boundingInfo = this.getBoundingInfo();
  29625. if (!boundingInfo) {
  29626. return false;
  29627. }
  29628. return boundingInfo.isInFrustum(frustumPlanes);
  29629. };
  29630. /**
  29631. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29632. * Boolean returned.
  29633. */
  29634. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29635. var boundingInfo = this.getBoundingInfo();
  29636. if (!boundingInfo) {
  29637. return false;
  29638. }
  29639. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29640. };
  29641. /**
  29642. * Renders the submesh.
  29643. * Returns it.
  29644. */
  29645. SubMesh.prototype.render = function (enableAlphaMode) {
  29646. this._renderingMesh.render(this, enableAlphaMode);
  29647. return this;
  29648. };
  29649. /**
  29650. * Returns a new Index Buffer.
  29651. * Type returned : WebGLBuffer.
  29652. */
  29653. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29654. if (!this._linesIndexBuffer) {
  29655. var linesIndices = [];
  29656. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29657. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29658. }
  29659. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29660. this.linesIndexCount = linesIndices.length;
  29661. }
  29662. return this._linesIndexBuffer;
  29663. };
  29664. /**
  29665. * True is the passed Ray intersects the submesh bounding box.
  29666. * Boolean returned.
  29667. */
  29668. SubMesh.prototype.canIntersects = function (ray) {
  29669. var boundingInfo = this.getBoundingInfo();
  29670. if (!boundingInfo) {
  29671. return false;
  29672. }
  29673. return ray.intersectsBox(boundingInfo.boundingBox);
  29674. };
  29675. /**
  29676. * Returns an object IntersectionInfo.
  29677. */
  29678. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29679. var intersectInfo = null;
  29680. // LineMesh first as it's also a Mesh...
  29681. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29682. var lineMesh = this._mesh;
  29683. // Line test
  29684. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29685. var p0 = positions[indices[index]];
  29686. var p1 = positions[indices[index + 1]];
  29687. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29688. if (length < 0) {
  29689. continue;
  29690. }
  29691. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29692. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29693. if (fastCheck) {
  29694. break;
  29695. }
  29696. }
  29697. }
  29698. }
  29699. else {
  29700. // Triangles test
  29701. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29702. var p0 = positions[indices[index]];
  29703. var p1 = positions[indices[index + 1]];
  29704. var p2 = positions[indices[index + 2]];
  29705. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29706. if (currentIntersectInfo) {
  29707. if (currentIntersectInfo.distance < 0) {
  29708. continue;
  29709. }
  29710. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29711. intersectInfo = currentIntersectInfo;
  29712. intersectInfo.faceId = index / 3;
  29713. if (fastCheck) {
  29714. break;
  29715. }
  29716. }
  29717. }
  29718. }
  29719. }
  29720. return intersectInfo;
  29721. };
  29722. SubMesh.prototype._rebuild = function () {
  29723. if (this._linesIndexBuffer) {
  29724. this._linesIndexBuffer = null;
  29725. }
  29726. };
  29727. // Clone
  29728. /**
  29729. * Creates a new Submesh from the passed Mesh.
  29730. */
  29731. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29732. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29733. if (!this.IsGlobal) {
  29734. var boundingInfo = this.getBoundingInfo();
  29735. if (!boundingInfo) {
  29736. return result;
  29737. }
  29738. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29739. }
  29740. return result;
  29741. };
  29742. // Dispose
  29743. /**
  29744. * Disposes the Submesh.
  29745. * Returns nothing.
  29746. */
  29747. SubMesh.prototype.dispose = function () {
  29748. if (this._linesIndexBuffer) {
  29749. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29750. this._linesIndexBuffer = null;
  29751. }
  29752. // Remove from mesh
  29753. var index = this._mesh.subMeshes.indexOf(this);
  29754. this._mesh.subMeshes.splice(index, 1);
  29755. };
  29756. // Statics
  29757. /**
  29758. * Creates a new Submesh from the passed parameters :
  29759. * - materialIndex (integer) : the index of the main mesh material.
  29760. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29761. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29762. * - mesh (Mesh) : the main mesh to create the submesh from.
  29763. * - renderingMesh (optional Mesh) : rendering mesh.
  29764. */
  29765. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29766. var minVertexIndex = Number.MAX_VALUE;
  29767. var maxVertexIndex = -Number.MAX_VALUE;
  29768. renderingMesh = (renderingMesh || mesh);
  29769. var indices = renderingMesh.getIndices();
  29770. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29771. var vertexIndex = indices[index];
  29772. if (vertexIndex < minVertexIndex)
  29773. minVertexIndex = vertexIndex;
  29774. if (vertexIndex > maxVertexIndex)
  29775. maxVertexIndex = vertexIndex;
  29776. }
  29777. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29778. };
  29779. return SubMesh;
  29780. }(BaseSubMesh));
  29781. BABYLON.SubMesh = SubMesh;
  29782. })(BABYLON || (BABYLON = {}));
  29783. //# sourceMappingURL=babylon.subMesh.js.map
  29784. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29785. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29786. s = arguments[i];
  29787. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29788. t[p] = s[p];
  29789. }
  29790. return t;
  29791. };
  29792. var BABYLON;
  29793. (function (BABYLON) {
  29794. /**
  29795. * Manages the defines for the Material.
  29796. */
  29797. var MaterialDefines = /** @class */ (function () {
  29798. function MaterialDefines() {
  29799. this._isDirty = true;
  29800. this._areLightsDirty = true;
  29801. this._areAttributesDirty = true;
  29802. this._areTexturesDirty = true;
  29803. this._areFresnelDirty = true;
  29804. this._areMiscDirty = true;
  29805. this._areImageProcessingDirty = true;
  29806. this._normals = false;
  29807. this._uvs = false;
  29808. this._needNormals = false;
  29809. this._needUVs = false;
  29810. }
  29811. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29812. /**
  29813. * Specifies if the material needs to be re-calculated.
  29814. */
  29815. get: function () {
  29816. return this._isDirty;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. /**
  29822. * Marks the material to indicate that it has been re-calculated.
  29823. */
  29824. MaterialDefines.prototype.markAsProcessed = function () {
  29825. this._isDirty = false;
  29826. this._areAttributesDirty = false;
  29827. this._areTexturesDirty = false;
  29828. this._areFresnelDirty = false;
  29829. this._areLightsDirty = false;
  29830. this._areMiscDirty = false;
  29831. this._areImageProcessingDirty = false;
  29832. };
  29833. /**
  29834. * Marks the material to indicate that it needs to be re-calculated.
  29835. */
  29836. MaterialDefines.prototype.markAsUnprocessed = function () {
  29837. this._isDirty = true;
  29838. };
  29839. /**
  29840. * Marks the material to indicate all of its defines need to be re-calculated.
  29841. */
  29842. MaterialDefines.prototype.markAllAsDirty = function () {
  29843. this._areTexturesDirty = true;
  29844. this._areAttributesDirty = true;
  29845. this._areLightsDirty = true;
  29846. this._areFresnelDirty = true;
  29847. this._areMiscDirty = true;
  29848. this._areImageProcessingDirty = true;
  29849. this._isDirty = true;
  29850. };
  29851. /**
  29852. * Marks the material to indicate that image processing needs to be re-calculated.
  29853. */
  29854. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29855. this._areImageProcessingDirty = true;
  29856. this._isDirty = true;
  29857. };
  29858. /**
  29859. * Marks the material to indicate the lights need to be re-calculated.
  29860. */
  29861. MaterialDefines.prototype.markAsLightDirty = function () {
  29862. this._areLightsDirty = true;
  29863. this._isDirty = true;
  29864. };
  29865. /**
  29866. * Marks the attribute state as changed.
  29867. */
  29868. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29869. this._areAttributesDirty = true;
  29870. this._isDirty = true;
  29871. };
  29872. /**
  29873. * Marks the texture state as changed.
  29874. */
  29875. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29876. this._areTexturesDirty = true;
  29877. this._isDirty = true;
  29878. };
  29879. /**
  29880. * Marks the fresnel state as changed.
  29881. */
  29882. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29883. this._areFresnelDirty = true;
  29884. this._isDirty = true;
  29885. };
  29886. /**
  29887. * Marks the misc state as changed.
  29888. */
  29889. MaterialDefines.prototype.markAsMiscDirty = function () {
  29890. this._areMiscDirty = true;
  29891. this._isDirty = true;
  29892. };
  29893. /**
  29894. * Rebuilds the material defines.
  29895. */
  29896. MaterialDefines.prototype.rebuild = function () {
  29897. if (this._keys) {
  29898. delete this._keys;
  29899. }
  29900. this._keys = [];
  29901. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29902. var key = _a[_i];
  29903. if (key[0] === "_") {
  29904. continue;
  29905. }
  29906. this._keys.push(key);
  29907. }
  29908. };
  29909. /**
  29910. * Specifies if two material defines are equal.
  29911. * @param other - A material define instance to compare to.
  29912. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  29913. */
  29914. MaterialDefines.prototype.isEqual = function (other) {
  29915. if (this._keys.length !== other._keys.length) {
  29916. return false;
  29917. }
  29918. for (var index = 0; index < this._keys.length; index++) {
  29919. var prop = this._keys[index];
  29920. if (this[prop] !== other[prop]) {
  29921. return false;
  29922. }
  29923. }
  29924. return true;
  29925. };
  29926. /**
  29927. * Clones this instance's defines to another instance.
  29928. * @param other - material defines to clone values to.
  29929. */
  29930. MaterialDefines.prototype.cloneTo = function (other) {
  29931. if (this._keys.length !== other._keys.length) {
  29932. other._keys = this._keys.slice(0);
  29933. }
  29934. for (var index = 0; index < this._keys.length; index++) {
  29935. var prop = this._keys[index];
  29936. other[prop] = this[prop];
  29937. }
  29938. };
  29939. /**
  29940. * Resets the material define values.
  29941. */
  29942. MaterialDefines.prototype.reset = function () {
  29943. for (var index = 0; index < this._keys.length; index++) {
  29944. var prop = this._keys[index];
  29945. if (typeof (this[prop]) === "number") {
  29946. this[prop] = 0;
  29947. }
  29948. else {
  29949. this[prop] = false;
  29950. }
  29951. }
  29952. };
  29953. /**
  29954. * Converts the material define values to a string.
  29955. * @returns - String of material define information.
  29956. */
  29957. MaterialDefines.prototype.toString = function () {
  29958. var result = "";
  29959. for (var index = 0; index < this._keys.length; index++) {
  29960. var prop = this._keys[index];
  29961. var value = this[prop];
  29962. if (typeof (value) === "number") {
  29963. result += "#define " + prop + " " + this[prop] + "\n";
  29964. }
  29965. else if (value) {
  29966. result += "#define " + prop + "\n";
  29967. }
  29968. }
  29969. return result;
  29970. };
  29971. return MaterialDefines;
  29972. }());
  29973. BABYLON.MaterialDefines = MaterialDefines;
  29974. /**
  29975. * This offers the main features of a material in BJS.
  29976. */
  29977. var Material = /** @class */ (function () {
  29978. /**
  29979. * Creates a material instance.
  29980. * @param name - The name of the material.
  29981. * @param scene - The BJS scene to reference.
  29982. * @param doNotAdd - Specifies if the material should be added to the scene.
  29983. */
  29984. function Material(name, scene, doNotAdd) {
  29985. /**
  29986. * Specifies if the ready state should be checked on each call.
  29987. */
  29988. this.checkReadyOnEveryCall = false;
  29989. /**
  29990. * Specifies if the ready state should be checked once.
  29991. */
  29992. this.checkReadyOnlyOnce = false;
  29993. /**
  29994. * The state of the material.
  29995. */
  29996. this.state = "";
  29997. /**
  29998. * The alpha value of the material.
  29999. */
  30000. this._alpha = 1.0;
  30001. /**
  30002. * Specifies if back face culling is enabled.
  30003. */
  30004. this._backFaceCulling = true;
  30005. /**
  30006. * Specifies if the material should be serialized.
  30007. */
  30008. this.doNotSerialize = false;
  30009. /**
  30010. * Specifies if the effect should be stored on sub meshes.
  30011. */
  30012. this.storeEffectOnSubMeshes = false;
  30013. /**
  30014. * An event triggered when the material is disposed.
  30015. * @type {BABYLON.Observable}
  30016. */
  30017. this.onDisposeObservable = new BABYLON.Observable();
  30018. /**
  30019. * An event triggered when the material is bound.
  30020. * @type {BABYLON.Observable}
  30021. */
  30022. this.onBindObservable = new BABYLON.Observable();
  30023. /**
  30024. * An event triggered when the material is unbound.
  30025. * @type {BABYLON.Observable}
  30026. */
  30027. this.onUnBindObservable = new BABYLON.Observable();
  30028. /**
  30029. * Stores the value of the alpha mode.
  30030. */
  30031. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30032. /**
  30033. * Stores the state of the need depth pre-pass value.
  30034. */
  30035. this._needDepthPrePass = false;
  30036. /**
  30037. * Specifies if depth writing should be disabled.
  30038. */
  30039. this.disableDepthWrite = false;
  30040. /**
  30041. * Specifies if depth writing should be forced.
  30042. */
  30043. this.forceDepthWrite = false;
  30044. /**
  30045. * Specifies if there should be a separate pass for culling.
  30046. */
  30047. this.separateCullingPass = false;
  30048. /**
  30049. * Stores the state specifing if fog should be enabled.
  30050. */
  30051. this._fogEnabled = true;
  30052. /**
  30053. * Stores the size of points.
  30054. */
  30055. this.pointSize = 1.0;
  30056. /**
  30057. * Stores the z offset value.
  30058. */
  30059. this.zOffset = 0;
  30060. /**
  30061. * Specifies if the material was previously ready.
  30062. */
  30063. this._wasPreviouslyReady = false;
  30064. /**
  30065. * Stores the fill mode state.
  30066. */
  30067. this._fillMode = Material.TriangleFillMode;
  30068. this.name = name;
  30069. this.id = name || BABYLON.Tools.RandomId();
  30070. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30071. if (this._scene.useRightHandedSystem) {
  30072. this.sideOrientation = Material.ClockWiseSideOrientation;
  30073. }
  30074. else {
  30075. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30076. }
  30077. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30078. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30079. if (!doNotAdd) {
  30080. this._scene.materials.push(this);
  30081. }
  30082. }
  30083. Object.defineProperty(Material, "TriangleFillMode", {
  30084. /**
  30085. * Returns the triangle fill mode.
  30086. */
  30087. get: function () {
  30088. return Material._TriangleFillMode;
  30089. },
  30090. enumerable: true,
  30091. configurable: true
  30092. });
  30093. Object.defineProperty(Material, "WireFrameFillMode", {
  30094. /**
  30095. * Returns the wireframe mode.
  30096. */
  30097. get: function () {
  30098. return Material._WireFrameFillMode;
  30099. },
  30100. enumerable: true,
  30101. configurable: true
  30102. });
  30103. Object.defineProperty(Material, "PointFillMode", {
  30104. /**
  30105. * Returns the point fill mode.
  30106. */
  30107. get: function () {
  30108. return Material._PointFillMode;
  30109. },
  30110. enumerable: true,
  30111. configurable: true
  30112. });
  30113. Object.defineProperty(Material, "PointListDrawMode", {
  30114. /**
  30115. * Returns the point list draw mode.
  30116. */
  30117. get: function () {
  30118. return Material._PointListDrawMode;
  30119. },
  30120. enumerable: true,
  30121. configurable: true
  30122. });
  30123. Object.defineProperty(Material, "LineListDrawMode", {
  30124. /**
  30125. * Returns the line list draw mode.
  30126. */
  30127. get: function () {
  30128. return Material._LineListDrawMode;
  30129. },
  30130. enumerable: true,
  30131. configurable: true
  30132. });
  30133. Object.defineProperty(Material, "LineLoopDrawMode", {
  30134. /**
  30135. * Returns the line loop draw mode.
  30136. */
  30137. get: function () {
  30138. return Material._LineLoopDrawMode;
  30139. },
  30140. enumerable: true,
  30141. configurable: true
  30142. });
  30143. Object.defineProperty(Material, "LineStripDrawMode", {
  30144. /**
  30145. * Returns the line strip draw mode.
  30146. */
  30147. get: function () {
  30148. return Material._LineStripDrawMode;
  30149. },
  30150. enumerable: true,
  30151. configurable: true
  30152. });
  30153. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30154. /**
  30155. * Returns the triangle strip draw mode.
  30156. */
  30157. get: function () {
  30158. return Material._TriangleStripDrawMode;
  30159. },
  30160. enumerable: true,
  30161. configurable: true
  30162. });
  30163. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30164. /**
  30165. * Returns the triangle fan draw mode.
  30166. */
  30167. get: function () {
  30168. return Material._TriangleFanDrawMode;
  30169. },
  30170. enumerable: true,
  30171. configurable: true
  30172. });
  30173. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30174. /**
  30175. * Returns the clock-wise side orientation.
  30176. */
  30177. get: function () {
  30178. return Material._ClockWiseSideOrientation;
  30179. },
  30180. enumerable: true,
  30181. configurable: true
  30182. });
  30183. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30184. /**
  30185. * Returns the counter clock-wise side orientation.
  30186. */
  30187. get: function () {
  30188. return Material._CounterClockWiseSideOrientation;
  30189. },
  30190. enumerable: true,
  30191. configurable: true
  30192. });
  30193. Object.defineProperty(Material, "TextureDirtyFlag", {
  30194. /**
  30195. * Returns the dirty texture flag value.
  30196. */
  30197. get: function () {
  30198. return Material._TextureDirtyFlag;
  30199. },
  30200. enumerable: true,
  30201. configurable: true
  30202. });
  30203. Object.defineProperty(Material, "LightDirtyFlag", {
  30204. /**
  30205. * Returns the dirty light flag value.
  30206. */
  30207. get: function () {
  30208. return Material._LightDirtyFlag;
  30209. },
  30210. enumerable: true,
  30211. configurable: true
  30212. });
  30213. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30214. /**
  30215. * Returns the dirty fresnel flag value.
  30216. */
  30217. get: function () {
  30218. return Material._FresnelDirtyFlag;
  30219. },
  30220. enumerable: true,
  30221. configurable: true
  30222. });
  30223. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30224. /**
  30225. * Returns the dirty attributes flag value.
  30226. */
  30227. get: function () {
  30228. return Material._AttributesDirtyFlag;
  30229. },
  30230. enumerable: true,
  30231. configurable: true
  30232. });
  30233. Object.defineProperty(Material, "MiscDirtyFlag", {
  30234. /**
  30235. * Returns the dirty misc flag value.
  30236. */
  30237. get: function () {
  30238. return Material._MiscDirtyFlag;
  30239. },
  30240. enumerable: true,
  30241. configurable: true
  30242. });
  30243. Object.defineProperty(Material.prototype, "alpha", {
  30244. /**
  30245. * Gets the alpha value of the material.
  30246. */
  30247. get: function () {
  30248. return this._alpha;
  30249. },
  30250. /**
  30251. * Sets the alpha value of the material.
  30252. */
  30253. set: function (value) {
  30254. if (this._alpha === value) {
  30255. return;
  30256. }
  30257. this._alpha = value;
  30258. this.markAsDirty(Material.MiscDirtyFlag);
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30264. /**
  30265. * Gets the back-face culling state.
  30266. */
  30267. get: function () {
  30268. return this._backFaceCulling;
  30269. },
  30270. /**
  30271. * Sets the back-face culling state.
  30272. */
  30273. set: function (value) {
  30274. if (this._backFaceCulling === value) {
  30275. return;
  30276. }
  30277. this._backFaceCulling = value;
  30278. this.markAsDirty(Material.TextureDirtyFlag);
  30279. },
  30280. enumerable: true,
  30281. configurable: true
  30282. });
  30283. Object.defineProperty(Material.prototype, "onDispose", {
  30284. /**
  30285. * Called during a dispose event.
  30286. */
  30287. set: function (callback) {
  30288. if (this._onDisposeObserver) {
  30289. this.onDisposeObservable.remove(this._onDisposeObserver);
  30290. }
  30291. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30292. },
  30293. enumerable: true,
  30294. configurable: true
  30295. });
  30296. Object.defineProperty(Material.prototype, "onBind", {
  30297. /**
  30298. * Called during a bind event.
  30299. */
  30300. set: function (callback) {
  30301. if (this._onBindObserver) {
  30302. this.onBindObservable.remove(this._onBindObserver);
  30303. }
  30304. this._onBindObserver = this.onBindObservable.add(callback);
  30305. },
  30306. enumerable: true,
  30307. configurable: true
  30308. });
  30309. Object.defineProperty(Material.prototype, "alphaMode", {
  30310. /**
  30311. * Gets the value of the alpha mode.
  30312. */
  30313. get: function () {
  30314. return this._alphaMode;
  30315. },
  30316. /**
  30317. * Sets the value of the alpha mode.
  30318. */
  30319. set: function (value) {
  30320. if (this._alphaMode === value) {
  30321. return;
  30322. }
  30323. this._alphaMode = value;
  30324. this.markAsDirty(Material.TextureDirtyFlag);
  30325. },
  30326. enumerable: true,
  30327. configurable: true
  30328. });
  30329. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30330. /**
  30331. * Gets the depth pre-pass value.
  30332. */
  30333. get: function () {
  30334. return this._needDepthPrePass;
  30335. },
  30336. /**
  30337. * Sets the need depth pre-pass value.
  30338. */
  30339. set: function (value) {
  30340. if (this._needDepthPrePass === value) {
  30341. return;
  30342. }
  30343. this._needDepthPrePass = value;
  30344. if (this._needDepthPrePass) {
  30345. this.checkReadyOnEveryCall = true;
  30346. }
  30347. },
  30348. enumerable: true,
  30349. configurable: true
  30350. });
  30351. Object.defineProperty(Material.prototype, "fogEnabled", {
  30352. /**
  30353. * Gets the value of the fog enabled state.
  30354. */
  30355. get: function () {
  30356. return this._fogEnabled;
  30357. },
  30358. /**
  30359. * Sets the state for enabling fog.
  30360. */
  30361. set: function (value) {
  30362. if (this._fogEnabled === value) {
  30363. return;
  30364. }
  30365. this._fogEnabled = value;
  30366. this.markAsDirty(Material.MiscDirtyFlag);
  30367. },
  30368. enumerable: true,
  30369. configurable: true
  30370. });
  30371. Object.defineProperty(Material.prototype, "wireframe", {
  30372. /**
  30373. * Gets a value specifying if wireframe mode is enabled.
  30374. */
  30375. get: function () {
  30376. return this._fillMode === Material.WireFrameFillMode;
  30377. },
  30378. /**
  30379. * Sets the state of wireframe mode.
  30380. */
  30381. set: function (value) {
  30382. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. Object.defineProperty(Material.prototype, "pointsCloud", {
  30388. /**
  30389. * Gets the value specifying if point clouds are enabled.
  30390. */
  30391. get: function () {
  30392. return this._fillMode === Material.PointFillMode;
  30393. },
  30394. /**
  30395. * Sets the state of point cloud mode.
  30396. */
  30397. set: function (value) {
  30398. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30399. },
  30400. enumerable: true,
  30401. configurable: true
  30402. });
  30403. Object.defineProperty(Material.prototype, "fillMode", {
  30404. /**
  30405. * Gets the material fill mode.
  30406. */
  30407. get: function () {
  30408. return this._fillMode;
  30409. },
  30410. /**
  30411. * Sets the material fill mode.
  30412. */
  30413. set: function (value) {
  30414. if (this._fillMode === value) {
  30415. return;
  30416. }
  30417. this._fillMode = value;
  30418. this.markAsDirty(Material.MiscDirtyFlag);
  30419. },
  30420. enumerable: true,
  30421. configurable: true
  30422. });
  30423. /**
  30424. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30425. * subclasses should override adding information pertainent to themselves.
  30426. * @returns - String with material information.
  30427. */
  30428. Material.prototype.toString = function (fullDetails) {
  30429. var ret = "Name: " + this.name;
  30430. if (fullDetails) {
  30431. }
  30432. return ret;
  30433. };
  30434. /**
  30435. * Gets the class name of the material.
  30436. * @returns - String with the class name of the material.
  30437. */
  30438. Material.prototype.getClassName = function () {
  30439. return "Material";
  30440. };
  30441. Object.defineProperty(Material.prototype, "isFrozen", {
  30442. /**
  30443. * Specifies if updates for the material been locked.
  30444. */
  30445. get: function () {
  30446. return this.checkReadyOnlyOnce;
  30447. },
  30448. enumerable: true,
  30449. configurable: true
  30450. });
  30451. /**
  30452. * Locks updates for the material.
  30453. */
  30454. Material.prototype.freeze = function () {
  30455. this.checkReadyOnlyOnce = true;
  30456. };
  30457. /**
  30458. * Unlocks updates for the material.
  30459. */
  30460. Material.prototype.unfreeze = function () {
  30461. this.checkReadyOnlyOnce = false;
  30462. };
  30463. /**
  30464. * Specifies if the material is ready to be used.
  30465. * @param mesh - BJS mesh.
  30466. * @param useInstances - Specifies if instances should be used.
  30467. * @returns - Boolean indicating if the material is ready to be used.
  30468. */
  30469. Material.prototype.isReady = function (mesh, useInstances) {
  30470. return true;
  30471. };
  30472. /**
  30473. * Specifies that the submesh is ready to be used.
  30474. * @param mesh - BJS mesh.
  30475. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30476. * @param useInstances - Specifies that instances should be used.
  30477. * @returns - boolean indicating that the submesh is ready or not.
  30478. */
  30479. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30480. return false;
  30481. };
  30482. /**
  30483. * Returns the material effect.
  30484. * @returns - Nullable material effect.
  30485. */
  30486. Material.prototype.getEffect = function () {
  30487. return this._effect;
  30488. };
  30489. /**
  30490. * Returns the BJS scene.
  30491. * @returns - BJS Scene.
  30492. */
  30493. Material.prototype.getScene = function () {
  30494. return this._scene;
  30495. };
  30496. /**
  30497. * Specifies if the material will require alpha blending
  30498. * @returns - Boolean specifying if alpha blending is needed.
  30499. */
  30500. Material.prototype.needAlphaBlending = function () {
  30501. return (this.alpha < 1.0);
  30502. };
  30503. /**
  30504. * Specifies if the mesh will require alpha blending.
  30505. * @param mesh - BJS mesh.
  30506. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30507. */
  30508. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30509. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30510. };
  30511. /**
  30512. * Specifies if this material should be rendered in alpha test mode.
  30513. * @returns - Boolean specifying if an alpha test is needed.
  30514. */
  30515. Material.prototype.needAlphaTesting = function () {
  30516. return false;
  30517. };
  30518. /**
  30519. * Gets the texture used for the alpha test.
  30520. * @returns - Nullable alpha test texture.
  30521. */
  30522. Material.prototype.getAlphaTestTexture = function () {
  30523. return null;
  30524. };
  30525. /**
  30526. * Marks the material to indicate that it needs to be re-calculated.
  30527. */
  30528. Material.prototype.markDirty = function () {
  30529. this._wasPreviouslyReady = false;
  30530. };
  30531. Material.prototype._preBind = function (effect, overrideOrientation) {
  30532. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30533. var engine = this._scene.getEngine();
  30534. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30535. var reverse = orientation === Material.ClockWiseSideOrientation;
  30536. engine.enableEffect(effect ? effect : this._effect);
  30537. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30538. return reverse;
  30539. };
  30540. /**
  30541. * Binds the material to the mesh.
  30542. * @param world - World transformation matrix.
  30543. * @param mesh - Mesh to bind the material to.
  30544. */
  30545. Material.prototype.bind = function (world, mesh) {
  30546. };
  30547. /**
  30548. * Binds the submesh to the material.
  30549. * @param world - World transformation matrix.
  30550. * @param mesh - Mesh containing the submesh.
  30551. * @param subMesh - Submesh to bind the material to.
  30552. */
  30553. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30554. };
  30555. /**
  30556. * Binds the world matrix to the material.
  30557. * @param world - World transformation matrix.
  30558. */
  30559. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30560. };
  30561. /**
  30562. * Binds the scene's uniform buffer to the effect.
  30563. * @param effect - Effect to bind to the scene uniform buffer.
  30564. * @param sceneUbo - Scene uniform buffer.
  30565. */
  30566. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30567. sceneUbo.bindToEffect(effect, "Scene");
  30568. };
  30569. /**
  30570. * Binds the view matrix to the effect.
  30571. * @param effect - Effect to bind the view matrix to.
  30572. */
  30573. Material.prototype.bindView = function (effect) {
  30574. if (!this._useUBO) {
  30575. effect.setMatrix("view", this.getScene().getViewMatrix());
  30576. }
  30577. else {
  30578. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30579. }
  30580. };
  30581. /**
  30582. * Binds the view projection matrix to the effect.
  30583. * @param effect - Effect to bind the view projection matrix to.
  30584. */
  30585. Material.prototype.bindViewProjection = function (effect) {
  30586. if (!this._useUBO) {
  30587. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30588. }
  30589. else {
  30590. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30591. }
  30592. };
  30593. /**
  30594. * Specifies if material alpha testing should be turned on for the mesh.
  30595. * @param mesh - BJS mesh.
  30596. */
  30597. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30598. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30599. };
  30600. /**
  30601. * Processes to execute after binding the material to a mesh.
  30602. * @param mesh - BJS mesh.
  30603. */
  30604. Material.prototype._afterBind = function (mesh) {
  30605. this._scene._cachedMaterial = this;
  30606. if (mesh) {
  30607. this._scene._cachedVisibility = mesh.visibility;
  30608. }
  30609. else {
  30610. this._scene._cachedVisibility = 1;
  30611. }
  30612. if (mesh) {
  30613. this.onBindObservable.notifyObservers(mesh);
  30614. }
  30615. if (this.disableDepthWrite) {
  30616. var engine = this._scene.getEngine();
  30617. this._cachedDepthWriteState = engine.getDepthWrite();
  30618. engine.setDepthWrite(false);
  30619. }
  30620. };
  30621. /**
  30622. * Unbinds the material from the mesh.
  30623. */
  30624. Material.prototype.unbind = function () {
  30625. this.onUnBindObservable.notifyObservers(this);
  30626. if (this.disableDepthWrite) {
  30627. var engine = this._scene.getEngine();
  30628. engine.setDepthWrite(this._cachedDepthWriteState);
  30629. }
  30630. };
  30631. /**
  30632. * Gets the active textures from the material.
  30633. * @returns - Array of textures.
  30634. */
  30635. Material.prototype.getActiveTextures = function () {
  30636. return [];
  30637. };
  30638. /**
  30639. * Specifies if the material uses a texture.
  30640. * @param texture - Texture to check against the material.
  30641. * @returns - Boolean specifying if the material uses the texture.
  30642. */
  30643. Material.prototype.hasTexture = function (texture) {
  30644. return false;
  30645. };
  30646. /**
  30647. * Makes a duplicate of the material, and gives it a new name.
  30648. * @param name - Name to call the duplicated material.
  30649. * @returns - Nullable cloned material
  30650. */
  30651. Material.prototype.clone = function (name) {
  30652. return null;
  30653. };
  30654. /**
  30655. * Gets the meshes bound to the material.
  30656. * @returns - Array of meshes bound to the material.
  30657. */
  30658. Material.prototype.getBindedMeshes = function () {
  30659. var result = new Array();
  30660. for (var index = 0; index < this._scene.meshes.length; index++) {
  30661. var mesh = this._scene.meshes[index];
  30662. if (mesh.material === this) {
  30663. result.push(mesh);
  30664. }
  30665. }
  30666. return result;
  30667. };
  30668. /**
  30669. * Force shader compilation including textures ready check
  30670. * @param mesh - BJS mesh.
  30671. * @param onCompiled - function to execute once the material is compiled.
  30672. * @param options - options to pass to this function.
  30673. */
  30674. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30675. var _this = this;
  30676. var localOptions = __assign({ clipPlane: false }, options);
  30677. var subMesh = new BABYLON.BaseSubMesh();
  30678. var scene = this.getScene();
  30679. var checkReady = function () {
  30680. if (!_this._scene || !_this._scene.getEngine()) {
  30681. return;
  30682. }
  30683. if (subMesh._materialDefines) {
  30684. subMesh._materialDefines._renderId = -1;
  30685. }
  30686. var clipPlaneState = scene.clipPlane;
  30687. if (localOptions.clipPlane) {
  30688. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30689. }
  30690. if (_this.storeEffectOnSubMeshes) {
  30691. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30692. if (onCompiled) {
  30693. onCompiled(_this);
  30694. }
  30695. }
  30696. else {
  30697. setTimeout(checkReady, 16);
  30698. }
  30699. }
  30700. else {
  30701. if (_this.isReady(mesh)) {
  30702. if (onCompiled) {
  30703. onCompiled(_this);
  30704. }
  30705. }
  30706. else {
  30707. setTimeout(checkReady, 16);
  30708. }
  30709. }
  30710. if (options && options.clipPlane) {
  30711. scene.clipPlane = clipPlaneState;
  30712. }
  30713. };
  30714. checkReady();
  30715. };
  30716. /**
  30717. * Marks a define in the material to indicate that it needs to be re-computed.
  30718. * @param flag - Material define flag.
  30719. */
  30720. Material.prototype.markAsDirty = function (flag) {
  30721. if (flag & Material.TextureDirtyFlag) {
  30722. this._markAllSubMeshesAsTexturesDirty();
  30723. }
  30724. if (flag & Material.LightDirtyFlag) {
  30725. this._markAllSubMeshesAsLightsDirty();
  30726. }
  30727. if (flag & Material.FresnelDirtyFlag) {
  30728. this._markAllSubMeshesAsFresnelDirty();
  30729. }
  30730. if (flag & Material.AttributesDirtyFlag) {
  30731. this._markAllSubMeshesAsAttributesDirty();
  30732. }
  30733. if (flag & Material.MiscDirtyFlag) {
  30734. this._markAllSubMeshesAsMiscDirty();
  30735. }
  30736. this.getScene().resetCachedMaterial();
  30737. };
  30738. /**
  30739. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30740. * @param func - function which checks material defines against the submeshes.
  30741. */
  30742. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30743. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30744. var mesh = _a[_i];
  30745. if (!mesh.subMeshes) {
  30746. continue;
  30747. }
  30748. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30749. var subMesh = _c[_b];
  30750. if (subMesh.getMaterial() !== this) {
  30751. continue;
  30752. }
  30753. if (!subMesh._materialDefines) {
  30754. continue;
  30755. }
  30756. func(subMesh._materialDefines);
  30757. }
  30758. }
  30759. };
  30760. /**
  30761. * Indicates that image processing needs to be re-calculated for all submeshes.
  30762. */
  30763. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  30764. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  30765. };
  30766. /**
  30767. * Indicates that textures need to be re-calculated for all submeshes.
  30768. */
  30769. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  30770. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  30771. };
  30772. /**
  30773. * Indicates that fresnel needs to be re-calculated for all submeshes.
  30774. */
  30775. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  30776. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  30777. };
  30778. /**
  30779. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  30780. */
  30781. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  30782. this._markAllSubMeshesAsDirty(function (defines) {
  30783. defines.markAsFresnelDirty();
  30784. defines.markAsMiscDirty();
  30785. });
  30786. };
  30787. /**
  30788. * Indicates that lights need to be re-calculated for all submeshes.
  30789. */
  30790. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  30791. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  30792. };
  30793. /**
  30794. * Indicates that attributes need to be re-calculated for all submeshes.
  30795. */
  30796. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  30797. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  30798. };
  30799. /**
  30800. * Indicates that misc needs to be re-calculated for all submeshes.
  30801. */
  30802. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  30803. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  30804. };
  30805. /**
  30806. * Indicates that textures and misc need to be re-calculated for all submeshes.
  30807. */
  30808. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  30809. this._markAllSubMeshesAsDirty(function (defines) {
  30810. defines.markAsTexturesDirty();
  30811. defines.markAsMiscDirty();
  30812. });
  30813. };
  30814. /**
  30815. * Disposes the material.
  30816. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  30817. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  30818. */
  30819. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30820. // Animations
  30821. this.getScene().stopAnimation(this);
  30822. // Remove from scene
  30823. var index = this._scene.materials.indexOf(this);
  30824. if (index >= 0) {
  30825. this._scene.materials.splice(index, 1);
  30826. }
  30827. // Remove from meshes
  30828. for (index = 0; index < this._scene.meshes.length; index++) {
  30829. var mesh = this._scene.meshes[index];
  30830. if (mesh.material === this) {
  30831. mesh.material = null;
  30832. if (mesh.geometry) {
  30833. var geometry = (mesh.geometry);
  30834. if (this.storeEffectOnSubMeshes) {
  30835. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  30836. var subMesh = _a[_i];
  30837. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  30838. if (forceDisposeEffect && subMesh._materialEffect) {
  30839. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  30840. }
  30841. }
  30842. }
  30843. else {
  30844. geometry._releaseVertexArrayObject(this._effect);
  30845. }
  30846. }
  30847. }
  30848. }
  30849. this._uniformBuffer.dispose();
  30850. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  30851. if (forceDisposeEffect && this._effect) {
  30852. if (!this.storeEffectOnSubMeshes) {
  30853. this._scene.getEngine()._releaseEffect(this._effect);
  30854. }
  30855. this._effect = null;
  30856. }
  30857. // Callback
  30858. this.onDisposeObservable.notifyObservers(this);
  30859. this.onDisposeObservable.clear();
  30860. this.onBindObservable.clear();
  30861. this.onUnBindObservable.clear();
  30862. };
  30863. /**
  30864. * Serializes this material.
  30865. * @returns - serialized material object.
  30866. */
  30867. Material.prototype.serialize = function () {
  30868. return BABYLON.SerializationHelper.Serialize(this);
  30869. };
  30870. /**
  30871. * Creates a MultiMaterial from parse MultiMaterial data.
  30872. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  30873. * @param scene - BJS scene.
  30874. * @returns - MultiMaterial.
  30875. */
  30876. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  30877. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  30878. multiMaterial.id = parsedMultiMaterial.id;
  30879. if (BABYLON.Tags) {
  30880. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  30881. }
  30882. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  30883. var subMatId = parsedMultiMaterial.materials[matIndex];
  30884. if (subMatId) {
  30885. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  30886. }
  30887. else {
  30888. multiMaterial.subMaterials.push(null);
  30889. }
  30890. }
  30891. return multiMaterial;
  30892. };
  30893. /**
  30894. * Creates a material from parsed material data.
  30895. * @param parsedMaterial - Parsed material data.
  30896. * @param scene - BJS scene.
  30897. * @param rootUrl - Root URL containing the material information.
  30898. * @returns - Parsed material.
  30899. */
  30900. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  30901. if (!parsedMaterial.customType) {
  30902. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  30903. }
  30904. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  30905. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  30906. if (!BABYLON.LegacyPBRMaterial) {
  30907. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  30908. return;
  30909. }
  30910. }
  30911. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  30912. return materialType.Parse(parsedMaterial, scene, rootUrl);
  30913. ;
  30914. };
  30915. // Triangle views
  30916. Material._TriangleFillMode = 0;
  30917. Material._WireFrameFillMode = 1;
  30918. Material._PointFillMode = 2;
  30919. // Draw modes
  30920. Material._PointListDrawMode = 3;
  30921. Material._LineListDrawMode = 4;
  30922. Material._LineLoopDrawMode = 5;
  30923. Material._LineStripDrawMode = 6;
  30924. Material._TriangleStripDrawMode = 7;
  30925. Material._TriangleFanDrawMode = 8;
  30926. /**
  30927. * Stores the clock-wise side orientation.
  30928. */
  30929. Material._ClockWiseSideOrientation = 0;
  30930. /**
  30931. * Stores the counter clock-wise side orientation.
  30932. */
  30933. Material._CounterClockWiseSideOrientation = 1;
  30934. /**
  30935. * The dirty texture flag value.
  30936. */
  30937. Material._TextureDirtyFlag = 1;
  30938. /**
  30939. * The dirty light flag value.
  30940. */
  30941. Material._LightDirtyFlag = 2;
  30942. /**
  30943. * The dirty fresnel flag value.
  30944. */
  30945. Material._FresnelDirtyFlag = 4;
  30946. /**
  30947. * The dirty attribute flag value.
  30948. */
  30949. Material._AttributesDirtyFlag = 8;
  30950. /**
  30951. * The dirty misc flag value.
  30952. */
  30953. Material._MiscDirtyFlag = 16;
  30954. __decorate([
  30955. BABYLON.serialize()
  30956. ], Material.prototype, "id", void 0);
  30957. __decorate([
  30958. BABYLON.serialize()
  30959. ], Material.prototype, "name", void 0);
  30960. __decorate([
  30961. BABYLON.serialize()
  30962. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  30963. __decorate([
  30964. BABYLON.serialize()
  30965. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  30966. __decorate([
  30967. BABYLON.serialize()
  30968. ], Material.prototype, "state", void 0);
  30969. __decorate([
  30970. BABYLON.serialize("alpha")
  30971. ], Material.prototype, "_alpha", void 0);
  30972. __decorate([
  30973. BABYLON.serialize("backFaceCulling")
  30974. ], Material.prototype, "_backFaceCulling", void 0);
  30975. __decorate([
  30976. BABYLON.serialize()
  30977. ], Material.prototype, "sideOrientation", void 0);
  30978. __decorate([
  30979. BABYLON.serialize("alphaMode")
  30980. ], Material.prototype, "_alphaMode", void 0);
  30981. __decorate([
  30982. BABYLON.serialize()
  30983. ], Material.prototype, "_needDepthPrePass", void 0);
  30984. __decorate([
  30985. BABYLON.serialize()
  30986. ], Material.prototype, "disableDepthWrite", void 0);
  30987. __decorate([
  30988. BABYLON.serialize()
  30989. ], Material.prototype, "forceDepthWrite", void 0);
  30990. __decorate([
  30991. BABYLON.serialize()
  30992. ], Material.prototype, "separateCullingPass", void 0);
  30993. __decorate([
  30994. BABYLON.serialize("fogEnabled")
  30995. ], Material.prototype, "_fogEnabled", void 0);
  30996. __decorate([
  30997. BABYLON.serialize()
  30998. ], Material.prototype, "pointSize", void 0);
  30999. __decorate([
  31000. BABYLON.serialize()
  31001. ], Material.prototype, "zOffset", void 0);
  31002. __decorate([
  31003. BABYLON.serialize()
  31004. ], Material.prototype, "wireframe", null);
  31005. __decorate([
  31006. BABYLON.serialize()
  31007. ], Material.prototype, "pointsCloud", null);
  31008. __decorate([
  31009. BABYLON.serialize()
  31010. ], Material.prototype, "fillMode", null);
  31011. return Material;
  31012. }());
  31013. BABYLON.Material = Material;
  31014. })(BABYLON || (BABYLON = {}));
  31015. //# sourceMappingURL=babylon.material.js.map
  31016. var BABYLON;
  31017. (function (BABYLON) {
  31018. var UniformBuffer = /** @class */ (function () {
  31019. /**
  31020. * Uniform buffer objects.
  31021. *
  31022. * Handles blocks of uniform on the GPU.
  31023. *
  31024. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31025. *
  31026. * For more information, please refer to :
  31027. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31028. */
  31029. function UniformBuffer(engine, data, dynamic) {
  31030. this._engine = engine;
  31031. this._noUBO = !engine.supportsUniformBuffers;
  31032. this._dynamic = dynamic;
  31033. this._data = data || [];
  31034. this._uniformLocations = {};
  31035. this._uniformSizes = {};
  31036. this._uniformLocationPointer = 0;
  31037. this._needSync = false;
  31038. if (this._noUBO) {
  31039. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31040. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31041. this.updateFloat = this._updateFloatForEffect;
  31042. this.updateFloat2 = this._updateFloat2ForEffect;
  31043. this.updateFloat3 = this._updateFloat3ForEffect;
  31044. this.updateFloat4 = this._updateFloat4ForEffect;
  31045. this.updateMatrix = this._updateMatrixForEffect;
  31046. this.updateVector3 = this._updateVector3ForEffect;
  31047. this.updateVector4 = this._updateVector4ForEffect;
  31048. this.updateColor3 = this._updateColor3ForEffect;
  31049. this.updateColor4 = this._updateColor4ForEffect;
  31050. }
  31051. else {
  31052. this._engine._uniformBuffers.push(this);
  31053. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31054. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31055. this.updateFloat = this._updateFloatForUniform;
  31056. this.updateFloat2 = this._updateFloat2ForUniform;
  31057. this.updateFloat3 = this._updateFloat3ForUniform;
  31058. this.updateFloat4 = this._updateFloat4ForUniform;
  31059. this.updateMatrix = this._updateMatrixForUniform;
  31060. this.updateVector3 = this._updateVector3ForUniform;
  31061. this.updateVector4 = this._updateVector4ForUniform;
  31062. this.updateColor3 = this._updateColor3ForUniform;
  31063. this.updateColor4 = this._updateColor4ForUniform;
  31064. }
  31065. }
  31066. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31067. // Properties
  31068. /**
  31069. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31070. * or just falling back on setUniformXXX calls.
  31071. */
  31072. get: function () {
  31073. return !this._noUBO;
  31074. },
  31075. enumerable: true,
  31076. configurable: true
  31077. });
  31078. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31079. /**
  31080. * Indicates if the WebGL underlying uniform buffer is in sync
  31081. * with the javascript cache data.
  31082. */
  31083. get: function () {
  31084. return !this._needSync;
  31085. },
  31086. enumerable: true,
  31087. configurable: true
  31088. });
  31089. /**
  31090. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31091. * Also, a dynamic UniformBuffer will disable cache verification and always
  31092. * update the underlying WebGL uniform buffer to the GPU.
  31093. */
  31094. UniformBuffer.prototype.isDynamic = function () {
  31095. return this._dynamic !== undefined;
  31096. };
  31097. /**
  31098. * The data cache on JS side.
  31099. */
  31100. UniformBuffer.prototype.getData = function () {
  31101. return this._bufferData;
  31102. };
  31103. /**
  31104. * The underlying WebGL Uniform buffer.
  31105. */
  31106. UniformBuffer.prototype.getBuffer = function () {
  31107. return this._buffer;
  31108. };
  31109. /**
  31110. * std140 layout specifies how to align data within an UBO structure.
  31111. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31112. * for specs.
  31113. */
  31114. UniformBuffer.prototype._fillAlignment = function (size) {
  31115. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31116. // and 4x4 matrices
  31117. // TODO : change if other types are used
  31118. var alignment;
  31119. if (size <= 2) {
  31120. alignment = size;
  31121. }
  31122. else {
  31123. alignment = 4;
  31124. }
  31125. if ((this._uniformLocationPointer % alignment) !== 0) {
  31126. var oldPointer = this._uniformLocationPointer;
  31127. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31128. var diff = this._uniformLocationPointer - oldPointer;
  31129. for (var i = 0; i < diff; i++) {
  31130. this._data.push(0);
  31131. }
  31132. }
  31133. };
  31134. /**
  31135. * Adds an uniform in the buffer.
  31136. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31137. * for the layout to be correct !
  31138. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31139. * @param {number|number[]} size Data size, or data directly.
  31140. */
  31141. UniformBuffer.prototype.addUniform = function (name, size) {
  31142. if (this._noUBO) {
  31143. return;
  31144. }
  31145. if (this._uniformLocations[name] !== undefined) {
  31146. // Already existing uniform
  31147. return;
  31148. }
  31149. // This function must be called in the order of the shader layout !
  31150. // size can be the size of the uniform, or data directly
  31151. var data;
  31152. if (size instanceof Array) {
  31153. data = size;
  31154. size = data.length;
  31155. }
  31156. else {
  31157. size = size;
  31158. data = [];
  31159. // Fill with zeros
  31160. for (var i = 0; i < size; i++) {
  31161. data.push(0);
  31162. }
  31163. }
  31164. this._fillAlignment(size);
  31165. this._uniformSizes[name] = size;
  31166. this._uniformLocations[name] = this._uniformLocationPointer;
  31167. this._uniformLocationPointer += size;
  31168. for (var i = 0; i < size; i++) {
  31169. this._data.push(data[i]);
  31170. }
  31171. this._needSync = true;
  31172. };
  31173. /**
  31174. * Wrapper for addUniform.
  31175. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31176. * @param {Matrix} mat A 4x4 matrix.
  31177. */
  31178. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31179. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31180. };
  31181. /**
  31182. * Wrapper for addUniform.
  31183. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31184. * @param {number} x
  31185. * @param {number} y
  31186. */
  31187. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31188. var temp = [x, y];
  31189. this.addUniform(name, temp);
  31190. };
  31191. /**
  31192. * Wrapper for addUniform.
  31193. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31194. * @param {number} x
  31195. * @param {number} y
  31196. * @param {number} z
  31197. */
  31198. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31199. var temp = [x, y, z];
  31200. this.addUniform(name, temp);
  31201. };
  31202. /**
  31203. * Wrapper for addUniform.
  31204. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31205. * @param {Color3} color
  31206. */
  31207. UniformBuffer.prototype.addColor3 = function (name, color) {
  31208. var temp = new Array();
  31209. color.toArray(temp);
  31210. this.addUniform(name, temp);
  31211. };
  31212. /**
  31213. * Wrapper for addUniform.
  31214. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31215. * @param {Color3} color
  31216. * @param {number} alpha
  31217. */
  31218. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31219. var temp = new Array();
  31220. color.toArray(temp);
  31221. temp.push(alpha);
  31222. this.addUniform(name, temp);
  31223. };
  31224. /**
  31225. * Wrapper for addUniform.
  31226. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31227. * @param {Vector3} vector
  31228. */
  31229. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31230. var temp = new Array();
  31231. vector.toArray(temp);
  31232. this.addUniform(name, temp);
  31233. };
  31234. /**
  31235. * Wrapper for addUniform.
  31236. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31237. */
  31238. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31239. this.addUniform(name, 12);
  31240. };
  31241. /**
  31242. * Wrapper for addUniform.
  31243. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31244. */
  31245. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31246. this.addUniform(name, 8);
  31247. };
  31248. /**
  31249. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31250. */
  31251. UniformBuffer.prototype.create = function () {
  31252. if (this._noUBO) {
  31253. return;
  31254. }
  31255. if (this._buffer) {
  31256. return; // nothing to do
  31257. }
  31258. // See spec, alignment must be filled as a vec4
  31259. this._fillAlignment(4);
  31260. this._bufferData = new Float32Array(this._data);
  31261. this._rebuild();
  31262. this._needSync = true;
  31263. };
  31264. UniformBuffer.prototype._rebuild = function () {
  31265. if (this._noUBO) {
  31266. return;
  31267. }
  31268. if (this._dynamic) {
  31269. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31270. }
  31271. else {
  31272. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31273. }
  31274. };
  31275. /**
  31276. * Updates the WebGL Uniform Buffer on the GPU.
  31277. * If the `dynamic` flag is set to true, no cache comparison is done.
  31278. * Otherwise, the buffer will be updated only if the cache differs.
  31279. */
  31280. UniformBuffer.prototype.update = function () {
  31281. if (!this._buffer) {
  31282. this.create();
  31283. return;
  31284. }
  31285. if (!this._dynamic && !this._needSync) {
  31286. return;
  31287. }
  31288. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31289. this._needSync = false;
  31290. };
  31291. /**
  31292. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31293. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31294. * @param {number[]|Float32Array} data Flattened data
  31295. * @param {number} size Size of the data.
  31296. */
  31297. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31298. var location = this._uniformLocations[uniformName];
  31299. if (location === undefined) {
  31300. if (this._buffer) {
  31301. // Cannot add an uniform if the buffer is already created
  31302. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31303. return;
  31304. }
  31305. this.addUniform(uniformName, size);
  31306. location = this._uniformLocations[uniformName];
  31307. }
  31308. if (!this._buffer) {
  31309. this.create();
  31310. }
  31311. if (!this._dynamic) {
  31312. // Cache for static uniform buffers
  31313. var changed = false;
  31314. for (var i = 0; i < size; i++) {
  31315. if (this._bufferData[location + i] !== data[i]) {
  31316. changed = true;
  31317. this._bufferData[location + i] = data[i];
  31318. }
  31319. }
  31320. this._needSync = this._needSync || changed;
  31321. }
  31322. else {
  31323. // No cache for dynamic
  31324. for (var i = 0; i < size; i++) {
  31325. this._bufferData[location + i] = data[i];
  31326. }
  31327. }
  31328. };
  31329. // Update methods
  31330. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31331. // To match std140, matrix must be realigned
  31332. for (var i = 0; i < 3; i++) {
  31333. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31334. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31335. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31336. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31337. }
  31338. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31339. };
  31340. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31341. this._currentEffect.setMatrix3x3(name, matrix);
  31342. };
  31343. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31344. this._currentEffect.setMatrix2x2(name, matrix);
  31345. };
  31346. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31347. // To match std140, matrix must be realigned
  31348. for (var i = 0; i < 2; i++) {
  31349. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31350. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31351. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31352. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31353. }
  31354. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31355. };
  31356. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31357. this._currentEffect.setFloat(name, x);
  31358. };
  31359. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31360. UniformBuffer._tempBuffer[0] = x;
  31361. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31362. };
  31363. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31364. if (suffix === void 0) { suffix = ""; }
  31365. this._currentEffect.setFloat2(name + suffix, x, y);
  31366. };
  31367. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31368. if (suffix === void 0) { suffix = ""; }
  31369. UniformBuffer._tempBuffer[0] = x;
  31370. UniformBuffer._tempBuffer[1] = y;
  31371. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31372. };
  31373. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31374. if (suffix === void 0) { suffix = ""; }
  31375. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31376. };
  31377. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31378. if (suffix === void 0) { suffix = ""; }
  31379. UniformBuffer._tempBuffer[0] = x;
  31380. UniformBuffer._tempBuffer[1] = y;
  31381. UniformBuffer._tempBuffer[2] = z;
  31382. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31383. };
  31384. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31385. if (suffix === void 0) { suffix = ""; }
  31386. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31387. };
  31388. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31389. if (suffix === void 0) { suffix = ""; }
  31390. UniformBuffer._tempBuffer[0] = x;
  31391. UniformBuffer._tempBuffer[1] = y;
  31392. UniformBuffer._tempBuffer[2] = z;
  31393. UniformBuffer._tempBuffer[3] = w;
  31394. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31395. };
  31396. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31397. this._currentEffect.setMatrix(name, mat);
  31398. };
  31399. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31400. this.updateUniform(name, mat.toArray(), 16);
  31401. };
  31402. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31403. this._currentEffect.setVector3(name, vector);
  31404. };
  31405. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31406. vector.toArray(UniformBuffer._tempBuffer);
  31407. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31408. };
  31409. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31410. this._currentEffect.setVector4(name, vector);
  31411. };
  31412. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31413. vector.toArray(UniformBuffer._tempBuffer);
  31414. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31415. };
  31416. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31417. if (suffix === void 0) { suffix = ""; }
  31418. this._currentEffect.setColor3(name + suffix, color);
  31419. };
  31420. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31421. if (suffix === void 0) { suffix = ""; }
  31422. color.toArray(UniformBuffer._tempBuffer);
  31423. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31424. };
  31425. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31426. if (suffix === void 0) { suffix = ""; }
  31427. this._currentEffect.setColor4(name + suffix, color, alpha);
  31428. };
  31429. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31430. if (suffix === void 0) { suffix = ""; }
  31431. color.toArray(UniformBuffer._tempBuffer);
  31432. UniformBuffer._tempBuffer[3] = alpha;
  31433. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31434. };
  31435. /**
  31436. * Sets a sampler uniform on the effect.
  31437. * @param {string} name Name of the sampler.
  31438. * @param {Texture} texture
  31439. */
  31440. UniformBuffer.prototype.setTexture = function (name, texture) {
  31441. this._currentEffect.setTexture(name, texture);
  31442. };
  31443. /**
  31444. * Directly updates the value of the uniform in the cache AND on the GPU.
  31445. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31446. * @param {number[]|Float32Array} data Flattened data
  31447. */
  31448. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31449. this.updateUniform(uniformName, data, data.length);
  31450. this.update();
  31451. };
  31452. /**
  31453. * Binds this uniform buffer to an effect.
  31454. * @param {Effect} effect
  31455. * @param {string} name Name of the uniform block in the shader.
  31456. */
  31457. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31458. this._currentEffect = effect;
  31459. if (this._noUBO || !this._buffer) {
  31460. return;
  31461. }
  31462. effect.bindUniformBuffer(this._buffer, name);
  31463. };
  31464. /**
  31465. * Disposes the uniform buffer.
  31466. */
  31467. UniformBuffer.prototype.dispose = function () {
  31468. if (this._noUBO) {
  31469. return;
  31470. }
  31471. var index = this._engine._uniformBuffers.indexOf(this);
  31472. if (index !== -1) {
  31473. this._engine._uniformBuffers.splice(index, 1);
  31474. }
  31475. if (!this._buffer) {
  31476. return;
  31477. }
  31478. if (this._engine._releaseBuffer(this._buffer)) {
  31479. this._buffer = null;
  31480. }
  31481. };
  31482. // Pool for avoiding memory leaks
  31483. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31484. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31485. return UniformBuffer;
  31486. }());
  31487. BABYLON.UniformBuffer = UniformBuffer;
  31488. })(BABYLON || (BABYLON = {}));
  31489. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31490. var BABYLON;
  31491. (function (BABYLON) {
  31492. var VertexData = /** @class */ (function () {
  31493. function VertexData() {
  31494. }
  31495. VertexData.prototype.set = function (data, kind) {
  31496. switch (kind) {
  31497. case BABYLON.VertexBuffer.PositionKind:
  31498. this.positions = data;
  31499. break;
  31500. case BABYLON.VertexBuffer.NormalKind:
  31501. this.normals = data;
  31502. break;
  31503. case BABYLON.VertexBuffer.TangentKind:
  31504. this.tangents = data;
  31505. break;
  31506. case BABYLON.VertexBuffer.UVKind:
  31507. this.uvs = data;
  31508. break;
  31509. case BABYLON.VertexBuffer.UV2Kind:
  31510. this.uvs2 = data;
  31511. break;
  31512. case BABYLON.VertexBuffer.UV3Kind:
  31513. this.uvs3 = data;
  31514. break;
  31515. case BABYLON.VertexBuffer.UV4Kind:
  31516. this.uvs4 = data;
  31517. break;
  31518. case BABYLON.VertexBuffer.UV5Kind:
  31519. this.uvs5 = data;
  31520. break;
  31521. case BABYLON.VertexBuffer.UV6Kind:
  31522. this.uvs6 = data;
  31523. break;
  31524. case BABYLON.VertexBuffer.ColorKind:
  31525. this.colors = data;
  31526. break;
  31527. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31528. this.matricesIndices = data;
  31529. break;
  31530. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31531. this.matricesWeights = data;
  31532. break;
  31533. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31534. this.matricesIndicesExtra = data;
  31535. break;
  31536. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31537. this.matricesWeightsExtra = data;
  31538. break;
  31539. }
  31540. };
  31541. /**
  31542. * Associates the vertexData to the passed Mesh.
  31543. * Sets it as updatable or not (default `false`).
  31544. * Returns the VertexData.
  31545. */
  31546. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31547. this._applyTo(mesh, updatable);
  31548. return this;
  31549. };
  31550. /**
  31551. * Associates the vertexData to the passed Geometry.
  31552. * Sets it as updatable or not (default `false`).
  31553. * Returns the VertexData.
  31554. */
  31555. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31556. this._applyTo(geometry, updatable);
  31557. return this;
  31558. };
  31559. /**
  31560. * Updates the associated mesh.
  31561. * Returns the VertexData.
  31562. */
  31563. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31564. this._update(mesh);
  31565. return this;
  31566. };
  31567. /**
  31568. * Updates the associated geometry.
  31569. * Returns the VertexData.
  31570. */
  31571. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31572. this._update(geometry);
  31573. return this;
  31574. };
  31575. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31576. if (updatable === void 0) { updatable = false; }
  31577. if (this.positions) {
  31578. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31579. }
  31580. if (this.normals) {
  31581. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31582. }
  31583. if (this.tangents) {
  31584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31585. }
  31586. if (this.uvs) {
  31587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31588. }
  31589. if (this.uvs2) {
  31590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31591. }
  31592. if (this.uvs3) {
  31593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31594. }
  31595. if (this.uvs4) {
  31596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31597. }
  31598. if (this.uvs5) {
  31599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31600. }
  31601. if (this.uvs6) {
  31602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31603. }
  31604. if (this.colors) {
  31605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31606. }
  31607. if (this.matricesIndices) {
  31608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31609. }
  31610. if (this.matricesWeights) {
  31611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31612. }
  31613. if (this.matricesIndicesExtra) {
  31614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31615. }
  31616. if (this.matricesWeightsExtra) {
  31617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31618. }
  31619. if (this.indices) {
  31620. meshOrGeometry.setIndices(this.indices, null, updatable);
  31621. }
  31622. return this;
  31623. };
  31624. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31625. if (this.positions) {
  31626. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31627. }
  31628. if (this.normals) {
  31629. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31630. }
  31631. if (this.tangents) {
  31632. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31633. }
  31634. if (this.uvs) {
  31635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31636. }
  31637. if (this.uvs2) {
  31638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31639. }
  31640. if (this.uvs3) {
  31641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31642. }
  31643. if (this.uvs4) {
  31644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31645. }
  31646. if (this.uvs5) {
  31647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31648. }
  31649. if (this.uvs6) {
  31650. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31651. }
  31652. if (this.colors) {
  31653. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31654. }
  31655. if (this.matricesIndices) {
  31656. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31657. }
  31658. if (this.matricesWeights) {
  31659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31660. }
  31661. if (this.matricesIndicesExtra) {
  31662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31663. }
  31664. if (this.matricesWeightsExtra) {
  31665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31666. }
  31667. if (this.indices) {
  31668. meshOrGeometry.setIndices(this.indices, null);
  31669. }
  31670. return this;
  31671. };
  31672. /**
  31673. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31674. * Returns the VertexData.
  31675. */
  31676. VertexData.prototype.transform = function (matrix) {
  31677. var transformed = BABYLON.Vector3.Zero();
  31678. var index;
  31679. if (this.positions) {
  31680. var position = BABYLON.Vector3.Zero();
  31681. for (index = 0; index < this.positions.length; index += 3) {
  31682. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31683. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31684. this.positions[index] = transformed.x;
  31685. this.positions[index + 1] = transformed.y;
  31686. this.positions[index + 2] = transformed.z;
  31687. }
  31688. }
  31689. if (this.normals) {
  31690. var normal = BABYLON.Vector3.Zero();
  31691. for (index = 0; index < this.normals.length; index += 3) {
  31692. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31693. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31694. this.normals[index] = transformed.x;
  31695. this.normals[index + 1] = transformed.y;
  31696. this.normals[index + 2] = transformed.z;
  31697. }
  31698. }
  31699. if (this.tangents) {
  31700. var tangent = BABYLON.Vector4.Zero();
  31701. var tangentTransformed = BABYLON.Vector4.Zero();
  31702. for (index = 0; index < this.tangents.length; index += 4) {
  31703. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31704. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31705. this.tangents[index] = tangentTransformed.x;
  31706. this.tangents[index + 1] = tangentTransformed.y;
  31707. this.tangents[index + 2] = tangentTransformed.z;
  31708. this.tangents[index + 3] = tangentTransformed.w;
  31709. }
  31710. }
  31711. return this;
  31712. };
  31713. /**
  31714. * Merges the passed VertexData into the current one.
  31715. * Returns the modified VertexData.
  31716. */
  31717. VertexData.prototype.merge = function (other, options) {
  31718. options = options || {};
  31719. if (other.indices) {
  31720. if (!this.indices) {
  31721. this.indices = [];
  31722. }
  31723. var offset = this.positions ? this.positions.length / 3 : 0;
  31724. for (var index = 0; index < other.indices.length; index++) {
  31725. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31726. this.indices.push(other.indices[index] + offset);
  31727. }
  31728. }
  31729. this.positions = this._mergeElement(this.positions, other.positions);
  31730. if (!this.positions) {
  31731. return this;
  31732. }
  31733. var count = this.positions.length / 3;
  31734. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  31735. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  31736. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  31737. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  31738. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  31739. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  31740. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  31741. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  31742. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  31743. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  31744. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  31745. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  31746. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  31747. return this;
  31748. };
  31749. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  31750. if (length === void 0) { length = 0; }
  31751. if (defaultValue === void 0) { defaultValue = 0; }
  31752. if (!other && !source) {
  31753. return null;
  31754. }
  31755. if (!other) {
  31756. var padding = new Float32Array(source.length);
  31757. padding.fill(defaultValue);
  31758. return this._mergeElement(source, padding, length);
  31759. }
  31760. if (!source) {
  31761. if (length === 0 || length === other.length) {
  31762. return other;
  31763. }
  31764. var padding = new Float32Array(length - other.length);
  31765. padding.fill(defaultValue);
  31766. return this._mergeElement(padding, other, length);
  31767. }
  31768. var len = other.length + source.length;
  31769. var isSrcTypedArray = source instanceof Float32Array;
  31770. var isOthTypedArray = other instanceof Float32Array;
  31771. // use non-loop method when the source is Float32Array
  31772. if (isSrcTypedArray) {
  31773. var ret32 = new Float32Array(len);
  31774. ret32.set(source);
  31775. ret32.set(other, source.length);
  31776. return ret32;
  31777. // source is number[], when other is also use concat
  31778. }
  31779. else if (!isOthTypedArray) {
  31780. return source.concat(other);
  31781. // source is a number[], but other is a Float32Array, loop required
  31782. }
  31783. else {
  31784. var ret = source.slice(0); // copy source to a separate array
  31785. for (var i = 0, len = other.length; i < len; i++) {
  31786. ret.push(other[i]);
  31787. }
  31788. return ret;
  31789. }
  31790. };
  31791. /**
  31792. * Serializes the VertexData.
  31793. * Returns a serialized object.
  31794. */
  31795. VertexData.prototype.serialize = function () {
  31796. var serializationObject = this.serialize();
  31797. if (this.positions) {
  31798. serializationObject.positions = this.positions;
  31799. }
  31800. if (this.normals) {
  31801. serializationObject.normals = this.normals;
  31802. }
  31803. if (this.tangents) {
  31804. serializationObject.tangents = this.tangents;
  31805. }
  31806. if (this.uvs) {
  31807. serializationObject.uvs = this.uvs;
  31808. }
  31809. if (this.uvs2) {
  31810. serializationObject.uvs2 = this.uvs2;
  31811. }
  31812. if (this.uvs3) {
  31813. serializationObject.uvs3 = this.uvs3;
  31814. }
  31815. if (this.uvs4) {
  31816. serializationObject.uvs4 = this.uvs4;
  31817. }
  31818. if (this.uvs5) {
  31819. serializationObject.uvs5 = this.uvs5;
  31820. }
  31821. if (this.uvs6) {
  31822. serializationObject.uvs6 = this.uvs6;
  31823. }
  31824. if (this.colors) {
  31825. serializationObject.colors = this.colors;
  31826. }
  31827. if (this.matricesIndices) {
  31828. serializationObject.matricesIndices = this.matricesIndices;
  31829. serializationObject.matricesIndices._isExpanded = true;
  31830. }
  31831. if (this.matricesWeights) {
  31832. serializationObject.matricesWeights = this.matricesWeights;
  31833. }
  31834. if (this.matricesIndicesExtra) {
  31835. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  31836. serializationObject.matricesIndicesExtra._isExpanded = true;
  31837. }
  31838. if (this.matricesWeightsExtra) {
  31839. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  31840. }
  31841. serializationObject.indices = this.indices;
  31842. return serializationObject;
  31843. };
  31844. // Statics
  31845. /**
  31846. * Returns the object VertexData associated to the passed mesh.
  31847. */
  31848. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  31849. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  31850. };
  31851. /**
  31852. * Returns the object VertexData associated to the passed geometry.
  31853. */
  31854. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  31855. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  31856. };
  31857. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  31858. var result = new VertexData();
  31859. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31860. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  31861. }
  31862. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31863. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  31864. }
  31865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  31866. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  31867. }
  31868. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31869. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  31870. }
  31871. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31872. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  31873. }
  31874. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31875. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  31876. }
  31877. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31878. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  31879. }
  31880. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31881. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  31882. }
  31883. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31884. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  31885. }
  31886. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31887. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  31888. }
  31889. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31890. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  31891. }
  31892. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31893. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  31894. }
  31895. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  31896. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  31897. }
  31898. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  31899. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  31900. }
  31901. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  31902. return result;
  31903. };
  31904. /**
  31905. * Creates the vertexData of the Ribbon.
  31906. */
  31907. VertexData.CreateRibbon = function (options) {
  31908. var pathArray = options.pathArray;
  31909. var closeArray = options.closeArray || false;
  31910. var closePath = options.closePath || false;
  31911. var invertUV = options.invertUV || false;
  31912. var defaultOffset = Math.floor(pathArray[0].length / 2);
  31913. var offset = options.offset || defaultOffset;
  31914. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  31915. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31916. var customUV = options.uvs;
  31917. var customColors = options.colors;
  31918. var positions = [];
  31919. var indices = [];
  31920. var normals = [];
  31921. var uvs = [];
  31922. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  31923. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  31924. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  31925. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  31926. var minlg; // minimal length among all paths from pathArray
  31927. var lg = []; // array of path lengths : nb of vertex per path
  31928. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  31929. var p; // path iterator
  31930. var i; // point iterator
  31931. var j; // point iterator
  31932. // if single path in pathArray
  31933. if (pathArray.length < 2) {
  31934. var ar1 = [];
  31935. var ar2 = [];
  31936. for (i = 0; i < pathArray[0].length - offset; i++) {
  31937. ar1.push(pathArray[0][i]);
  31938. ar2.push(pathArray[0][i + offset]);
  31939. }
  31940. pathArray = [ar1, ar2];
  31941. }
  31942. // positions and horizontal distances (u)
  31943. var idc = 0;
  31944. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  31945. var path;
  31946. var l;
  31947. minlg = pathArray[0].length;
  31948. var vectlg;
  31949. var dist;
  31950. for (p = 0; p < pathArray.length; p++) {
  31951. uTotalDistance[p] = 0;
  31952. us[p] = [0];
  31953. path = pathArray[p];
  31954. l = path.length;
  31955. minlg = (minlg < l) ? minlg : l;
  31956. j = 0;
  31957. while (j < l) {
  31958. positions.push(path[j].x, path[j].y, path[j].z);
  31959. if (j > 0) {
  31960. vectlg = path[j].subtract(path[j - 1]).length();
  31961. dist = vectlg + uTotalDistance[p];
  31962. us[p].push(dist);
  31963. uTotalDistance[p] = dist;
  31964. }
  31965. j++;
  31966. }
  31967. if (closePath) {
  31968. j--;
  31969. positions.push(path[0].x, path[0].y, path[0].z);
  31970. vectlg = path[j].subtract(path[0]).length();
  31971. dist = vectlg + uTotalDistance[p];
  31972. us[p].push(dist);
  31973. uTotalDistance[p] = dist;
  31974. }
  31975. lg[p] = l + closePathCorr;
  31976. idx[p] = idc;
  31977. idc += (l + closePathCorr);
  31978. }
  31979. // vertical distances (v)
  31980. var path1;
  31981. var path2;
  31982. var vertex1 = null;
  31983. var vertex2 = null;
  31984. for (i = 0; i < minlg + closePathCorr; i++) {
  31985. vTotalDistance[i] = 0;
  31986. vs[i] = [0];
  31987. for (p = 0; p < pathArray.length - 1; p++) {
  31988. path1 = pathArray[p];
  31989. path2 = pathArray[p + 1];
  31990. if (i === minlg) {
  31991. vertex1 = path1[0];
  31992. vertex2 = path2[0];
  31993. }
  31994. else {
  31995. vertex1 = path1[i];
  31996. vertex2 = path2[i];
  31997. }
  31998. vectlg = vertex2.subtract(vertex1).length();
  31999. dist = vectlg + vTotalDistance[i];
  32000. vs[i].push(dist);
  32001. vTotalDistance[i] = dist;
  32002. }
  32003. if (closeArray && vertex2 && vertex1) {
  32004. path1 = pathArray[p];
  32005. path2 = pathArray[0];
  32006. if (i === minlg) {
  32007. vertex2 = path2[0];
  32008. }
  32009. vectlg = vertex2.subtract(vertex1).length();
  32010. dist = vectlg + vTotalDistance[i];
  32011. vTotalDistance[i] = dist;
  32012. }
  32013. }
  32014. // uvs
  32015. var u;
  32016. var v;
  32017. if (customUV) {
  32018. for (p = 0; p < customUV.length; p++) {
  32019. uvs.push(customUV[p].x, customUV[p].y);
  32020. }
  32021. }
  32022. else {
  32023. for (p = 0; p < pathArray.length; p++) {
  32024. for (i = 0; i < minlg + closePathCorr; i++) {
  32025. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32026. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32027. if (invertUV) {
  32028. uvs.push(v, u);
  32029. }
  32030. else {
  32031. uvs.push(u, v);
  32032. }
  32033. }
  32034. }
  32035. }
  32036. // indices
  32037. p = 0; // path index
  32038. var pi = 0; // positions array index
  32039. var l1 = lg[p] - 1; // path1 length
  32040. var l2 = lg[p + 1] - 1; // path2 length
  32041. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32042. var shft = idx[1] - idx[0]; // shift
  32043. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32044. while (pi <= min && p < path1nb) {
  32045. // 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
  32046. indices.push(pi, pi + shft, pi + 1);
  32047. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32048. pi += 1;
  32049. if (pi === min) {
  32050. p++;
  32051. if (p === lg.length - 1) {
  32052. shft = idx[0] - idx[p];
  32053. l1 = lg[p] - 1;
  32054. l2 = lg[0] - 1;
  32055. }
  32056. else {
  32057. shft = idx[p + 1] - idx[p];
  32058. l1 = lg[p] - 1;
  32059. l2 = lg[p + 1] - 1;
  32060. }
  32061. pi = idx[p];
  32062. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32063. }
  32064. }
  32065. // normals
  32066. VertexData.ComputeNormals(positions, indices, normals);
  32067. if (closePath) {
  32068. var indexFirst = 0;
  32069. var indexLast = 0;
  32070. for (p = 0; p < pathArray.length; p++) {
  32071. indexFirst = idx[p] * 3;
  32072. if (p + 1 < pathArray.length) {
  32073. indexLast = (idx[p + 1] - 1) * 3;
  32074. }
  32075. else {
  32076. indexLast = normals.length - 3;
  32077. }
  32078. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32079. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32080. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32081. normals[indexLast] = normals[indexFirst];
  32082. normals[indexLast + 1] = normals[indexFirst + 1];
  32083. normals[indexLast + 2] = normals[indexFirst + 2];
  32084. }
  32085. }
  32086. // sides
  32087. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32088. // Colors
  32089. var colors = null;
  32090. if (customColors) {
  32091. colors = new Float32Array(customColors.length * 4);
  32092. for (var c = 0; c < customColors.length; c++) {
  32093. colors[c * 4] = customColors[c].r;
  32094. colors[c * 4 + 1] = customColors[c].g;
  32095. colors[c * 4 + 2] = customColors[c].b;
  32096. colors[c * 4 + 3] = customColors[c].a;
  32097. }
  32098. }
  32099. // Result
  32100. var vertexData = new VertexData();
  32101. var positions32 = new Float32Array(positions);
  32102. var normals32 = new Float32Array(normals);
  32103. var uvs32 = new Float32Array(uvs);
  32104. vertexData.indices = indices;
  32105. vertexData.positions = positions32;
  32106. vertexData.normals = normals32;
  32107. vertexData.uvs = uvs32;
  32108. if (colors) {
  32109. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32110. }
  32111. if (closePath) {
  32112. vertexData._idx = idx;
  32113. }
  32114. return vertexData;
  32115. };
  32116. /**
  32117. * Creates the VertexData of the Box.
  32118. */
  32119. VertexData.CreateBox = function (options) {
  32120. var normalsSource = [
  32121. new BABYLON.Vector3(0, 0, 1),
  32122. new BABYLON.Vector3(0, 0, -1),
  32123. new BABYLON.Vector3(1, 0, 0),
  32124. new BABYLON.Vector3(-1, 0, 0),
  32125. new BABYLON.Vector3(0, 1, 0),
  32126. new BABYLON.Vector3(0, -1, 0)
  32127. ];
  32128. var indices = [];
  32129. var positions = [];
  32130. var normals = [];
  32131. var uvs = [];
  32132. var width = options.width || options.size || 1;
  32133. var height = options.height || options.size || 1;
  32134. var depth = options.depth || options.size || 1;
  32135. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32136. var faceUV = options.faceUV || new Array(6);
  32137. var faceColors = options.faceColors;
  32138. var colors = [];
  32139. // default face colors and UV if undefined
  32140. for (var f = 0; f < 6; f++) {
  32141. if (faceUV[f] === undefined) {
  32142. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32143. }
  32144. if (faceColors && faceColors[f] === undefined) {
  32145. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32146. }
  32147. }
  32148. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32149. // Create each face in turn.
  32150. for (var index = 0; index < normalsSource.length; index++) {
  32151. var normal = normalsSource[index];
  32152. // Get two vectors perpendicular to the face normal and to each other.
  32153. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32154. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32155. // Six indices (two triangles) per face.
  32156. var verticesLength = positions.length / 3;
  32157. indices.push(verticesLength);
  32158. indices.push(verticesLength + 1);
  32159. indices.push(verticesLength + 2);
  32160. indices.push(verticesLength);
  32161. indices.push(verticesLength + 2);
  32162. indices.push(verticesLength + 3);
  32163. // Four vertices per face.
  32164. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32165. positions.push(vertex.x, vertex.y, vertex.z);
  32166. normals.push(normal.x, normal.y, normal.z);
  32167. uvs.push(faceUV[index].z, faceUV[index].w);
  32168. if (faceColors) {
  32169. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32170. }
  32171. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32172. positions.push(vertex.x, vertex.y, vertex.z);
  32173. normals.push(normal.x, normal.y, normal.z);
  32174. uvs.push(faceUV[index].x, faceUV[index].w);
  32175. if (faceColors) {
  32176. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32177. }
  32178. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32179. positions.push(vertex.x, vertex.y, vertex.z);
  32180. normals.push(normal.x, normal.y, normal.z);
  32181. uvs.push(faceUV[index].x, faceUV[index].y);
  32182. if (faceColors) {
  32183. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32184. }
  32185. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32186. positions.push(vertex.x, vertex.y, vertex.z);
  32187. normals.push(normal.x, normal.y, normal.z);
  32188. uvs.push(faceUV[index].z, faceUV[index].y);
  32189. if (faceColors) {
  32190. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32191. }
  32192. }
  32193. // sides
  32194. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32195. // Result
  32196. var vertexData = new VertexData();
  32197. vertexData.indices = indices;
  32198. vertexData.positions = positions;
  32199. vertexData.normals = normals;
  32200. vertexData.uvs = uvs;
  32201. if (faceColors) {
  32202. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32203. vertexData.colors = totalColors;
  32204. }
  32205. return vertexData;
  32206. };
  32207. /**
  32208. * Creates the VertexData of the Sphere.
  32209. */
  32210. VertexData.CreateSphere = function (options) {
  32211. var segments = options.segments || 32;
  32212. var diameterX = options.diameterX || options.diameter || 1;
  32213. var diameterY = options.diameterY || options.diameter || 1;
  32214. var diameterZ = options.diameterZ || options.diameter || 1;
  32215. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32216. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32217. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32218. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32219. var totalZRotationSteps = 2 + segments;
  32220. var totalYRotationSteps = 2 * totalZRotationSteps;
  32221. var indices = [];
  32222. var positions = [];
  32223. var normals = [];
  32224. var uvs = [];
  32225. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32226. var normalizedZ = zRotationStep / totalZRotationSteps;
  32227. var angleZ = normalizedZ * Math.PI * slice;
  32228. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32229. var normalizedY = yRotationStep / totalYRotationSteps;
  32230. var angleY = normalizedY * Math.PI * 2 * arc;
  32231. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32232. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32233. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32234. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32235. var vertex = complete.multiply(radius);
  32236. var normal = complete.divide(radius).normalize();
  32237. positions.push(vertex.x, vertex.y, vertex.z);
  32238. normals.push(normal.x, normal.y, normal.z);
  32239. uvs.push(normalizedY, normalizedZ);
  32240. }
  32241. if (zRotationStep > 0) {
  32242. var verticesCount = positions.length / 3;
  32243. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32244. indices.push((firstIndex));
  32245. indices.push((firstIndex + 1));
  32246. indices.push(firstIndex + totalYRotationSteps + 1);
  32247. indices.push((firstIndex + totalYRotationSteps + 1));
  32248. indices.push((firstIndex + 1));
  32249. indices.push((firstIndex + totalYRotationSteps + 2));
  32250. }
  32251. }
  32252. }
  32253. // Sides
  32254. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32255. // Result
  32256. var vertexData = new VertexData();
  32257. vertexData.indices = indices;
  32258. vertexData.positions = positions;
  32259. vertexData.normals = normals;
  32260. vertexData.uvs = uvs;
  32261. return vertexData;
  32262. };
  32263. /**
  32264. * Creates the VertexData of the Cylinder or Cone.
  32265. */
  32266. VertexData.CreateCylinder = function (options) {
  32267. var height = options.height || 2;
  32268. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32269. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32270. var tessellation = options.tessellation || 24;
  32271. var subdivisions = options.subdivisions || 1;
  32272. var hasRings = options.hasRings ? true : false;
  32273. var enclose = options.enclose ? true : false;
  32274. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32275. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32276. var faceUV = options.faceUV || new Array(3);
  32277. var faceColors = options.faceColors;
  32278. // default face colors and UV if undefined
  32279. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32280. var ringNb = (hasRings) ? subdivisions : 1;
  32281. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32282. var f;
  32283. for (f = 0; f < surfaceNb; f++) {
  32284. if (faceColors && faceColors[f] === undefined) {
  32285. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32286. }
  32287. }
  32288. for (f = 0; f < surfaceNb; f++) {
  32289. if (faceUV && faceUV[f] === undefined) {
  32290. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32291. }
  32292. }
  32293. var indices = new Array();
  32294. var positions = new Array();
  32295. var normals = new Array();
  32296. var uvs = new Array();
  32297. var colors = new Array();
  32298. var angle_step = Math.PI * 2 * arc / tessellation;
  32299. var angle;
  32300. var h;
  32301. var radius;
  32302. var tan = (diameterBottom - diameterTop) / 2 / height;
  32303. var ringVertex = BABYLON.Vector3.Zero();
  32304. var ringNormal = BABYLON.Vector3.Zero();
  32305. var ringFirstVertex = BABYLON.Vector3.Zero();
  32306. var ringFirstNormal = BABYLON.Vector3.Zero();
  32307. var quadNormal = BABYLON.Vector3.Zero();
  32308. var Y = BABYLON.Axis.Y;
  32309. // positions, normals, uvs
  32310. var i;
  32311. var j;
  32312. var r;
  32313. var ringIdx = 1;
  32314. var s = 1; // surface index
  32315. var cs = 0;
  32316. var v = 0;
  32317. for (i = 0; i <= subdivisions; i++) {
  32318. h = i / subdivisions;
  32319. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32320. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32321. for (r = 0; r < ringIdx; r++) {
  32322. if (hasRings) {
  32323. s += r;
  32324. }
  32325. if (enclose) {
  32326. s += 2 * r;
  32327. }
  32328. for (j = 0; j <= tessellation; j++) {
  32329. angle = j * angle_step;
  32330. // position
  32331. ringVertex.x = Math.cos(-angle) * radius;
  32332. ringVertex.y = -height / 2 + h * height;
  32333. ringVertex.z = Math.sin(-angle) * radius;
  32334. // normal
  32335. if (diameterTop === 0 && i === subdivisions) {
  32336. // if no top cap, reuse former normals
  32337. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32338. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32339. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32340. }
  32341. else {
  32342. ringNormal.x = ringVertex.x;
  32343. ringNormal.z = ringVertex.z;
  32344. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32345. ringNormal.normalize();
  32346. }
  32347. // keep first ring vertex values for enclose
  32348. if (j === 0) {
  32349. ringFirstVertex.copyFrom(ringVertex);
  32350. ringFirstNormal.copyFrom(ringNormal);
  32351. }
  32352. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32353. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32354. if (hasRings) {
  32355. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32356. }
  32357. else {
  32358. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32359. }
  32360. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32361. if (faceColors) {
  32362. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32363. }
  32364. }
  32365. // if enclose, add four vertices and their dedicated normals
  32366. if (arc !== 1 && enclose) {
  32367. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32368. positions.push(0, ringVertex.y, 0);
  32369. positions.push(0, ringVertex.y, 0);
  32370. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32371. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32372. quadNormal.normalize();
  32373. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32374. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32375. quadNormal.normalize();
  32376. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32377. if (hasRings) {
  32378. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32379. }
  32380. else {
  32381. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32382. }
  32383. uvs.push(faceUV[s + 1].x, v);
  32384. uvs.push(faceUV[s + 1].z, v);
  32385. if (hasRings) {
  32386. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32387. }
  32388. else {
  32389. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32390. }
  32391. uvs.push(faceUV[s + 2].x, v);
  32392. uvs.push(faceUV[s + 2].z, v);
  32393. if (faceColors) {
  32394. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32395. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32396. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32397. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32398. }
  32399. }
  32400. if (cs !== s) {
  32401. cs = s;
  32402. }
  32403. }
  32404. }
  32405. // indices
  32406. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32407. var s;
  32408. i = 0;
  32409. for (s = 0; s < subdivisions; s++) {
  32410. var i0 = 0;
  32411. var i1 = 0;
  32412. var i2 = 0;
  32413. var i3 = 0;
  32414. for (j = 0; j < tessellation; j++) {
  32415. i0 = i * (e + 1) + j;
  32416. i1 = (i + 1) * (e + 1) + j;
  32417. i2 = i * (e + 1) + (j + 1);
  32418. i3 = (i + 1) * (e + 1) + (j + 1);
  32419. indices.push(i0, i1, i2);
  32420. indices.push(i3, i2, i1);
  32421. }
  32422. if (arc !== 1 && enclose) {
  32423. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32424. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32425. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32426. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32427. }
  32428. i = (hasRings) ? (i + 2) : (i + 1);
  32429. }
  32430. // Caps
  32431. var createCylinderCap = function (isTop) {
  32432. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32433. if (radius === 0) {
  32434. return;
  32435. }
  32436. // Cap positions, normals & uvs
  32437. var angle;
  32438. var circleVector;
  32439. var i;
  32440. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32441. var c = null;
  32442. if (faceColors) {
  32443. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32444. }
  32445. // cap center
  32446. var vbase = positions.length / 3;
  32447. var offset = isTop ? height / 2 : -height / 2;
  32448. var center = new BABYLON.Vector3(0, offset, 0);
  32449. positions.push(center.x, center.y, center.z);
  32450. normals.push(0, isTop ? 1 : -1, 0);
  32451. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32452. if (c) {
  32453. colors.push(c.r, c.g, c.b, c.a);
  32454. }
  32455. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32456. for (i = 0; i <= tessellation; i++) {
  32457. angle = Math.PI * 2 * i * arc / tessellation;
  32458. var cos = Math.cos(-angle);
  32459. var sin = Math.sin(-angle);
  32460. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32461. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32462. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32463. normals.push(0, isTop ? 1 : -1, 0);
  32464. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32465. if (c) {
  32466. colors.push(c.r, c.g, c.b, c.a);
  32467. }
  32468. }
  32469. // Cap indices
  32470. for (i = 0; i < tessellation; i++) {
  32471. if (!isTop) {
  32472. indices.push(vbase);
  32473. indices.push(vbase + (i + 1));
  32474. indices.push(vbase + (i + 2));
  32475. }
  32476. else {
  32477. indices.push(vbase);
  32478. indices.push(vbase + (i + 2));
  32479. indices.push(vbase + (i + 1));
  32480. }
  32481. }
  32482. };
  32483. // add caps to geometry
  32484. createCylinderCap(false);
  32485. createCylinderCap(true);
  32486. // Sides
  32487. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32488. var vertexData = new VertexData();
  32489. vertexData.indices = indices;
  32490. vertexData.positions = positions;
  32491. vertexData.normals = normals;
  32492. vertexData.uvs = uvs;
  32493. if (faceColors) {
  32494. vertexData.colors = colors;
  32495. }
  32496. return vertexData;
  32497. };
  32498. /**
  32499. * Creates the VertexData of the Torus.
  32500. */
  32501. VertexData.CreateTorus = function (options) {
  32502. var indices = [];
  32503. var positions = [];
  32504. var normals = [];
  32505. var uvs = [];
  32506. var diameter = options.diameter || 1;
  32507. var thickness = options.thickness || 0.5;
  32508. var tessellation = options.tessellation || 16;
  32509. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32510. var stride = tessellation + 1;
  32511. for (var i = 0; i <= tessellation; i++) {
  32512. var u = i / tessellation;
  32513. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32514. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32515. for (var j = 0; j <= tessellation; j++) {
  32516. var v = 1 - j / tessellation;
  32517. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32518. var dx = Math.cos(innerAngle);
  32519. var dy = Math.sin(innerAngle);
  32520. // Create a vertex.
  32521. var normal = new BABYLON.Vector3(dx, dy, 0);
  32522. var position = normal.scale(thickness / 2);
  32523. var textureCoordinate = new BABYLON.Vector2(u, v);
  32524. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32525. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32526. positions.push(position.x, position.y, position.z);
  32527. normals.push(normal.x, normal.y, normal.z);
  32528. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32529. // And create indices for two triangles.
  32530. var nextI = (i + 1) % stride;
  32531. var nextJ = (j + 1) % stride;
  32532. indices.push(i * stride + j);
  32533. indices.push(i * stride + nextJ);
  32534. indices.push(nextI * stride + j);
  32535. indices.push(i * stride + nextJ);
  32536. indices.push(nextI * stride + nextJ);
  32537. indices.push(nextI * stride + j);
  32538. }
  32539. }
  32540. // Sides
  32541. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32542. // Result
  32543. var vertexData = new VertexData();
  32544. vertexData.indices = indices;
  32545. vertexData.positions = positions;
  32546. vertexData.normals = normals;
  32547. vertexData.uvs = uvs;
  32548. return vertexData;
  32549. };
  32550. /**
  32551. * Creates the VertexData of the LineSystem.
  32552. */
  32553. VertexData.CreateLineSystem = function (options) {
  32554. var indices = [];
  32555. var positions = [];
  32556. var lines = options.lines;
  32557. var colors = options.colors;
  32558. var vertexColors = [];
  32559. var idx = 0;
  32560. for (var l = 0; l < lines.length; l++) {
  32561. var points = lines[l];
  32562. for (var index = 0; index < points.length; index++) {
  32563. positions.push(points[index].x, points[index].y, points[index].z);
  32564. if (colors) {
  32565. var color = colors[l];
  32566. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32567. }
  32568. if (index > 0) {
  32569. indices.push(idx - 1);
  32570. indices.push(idx);
  32571. }
  32572. idx++;
  32573. }
  32574. }
  32575. var vertexData = new VertexData();
  32576. vertexData.indices = indices;
  32577. vertexData.positions = positions;
  32578. if (colors) {
  32579. vertexData.colors = vertexColors;
  32580. }
  32581. return vertexData;
  32582. };
  32583. /**
  32584. * Create the VertexData of the DashedLines.
  32585. */
  32586. VertexData.CreateDashedLines = function (options) {
  32587. var dashSize = options.dashSize || 3;
  32588. var gapSize = options.gapSize || 1;
  32589. var dashNb = options.dashNb || 200;
  32590. var points = options.points;
  32591. var positions = new Array();
  32592. var indices = new Array();
  32593. var curvect = BABYLON.Vector3.Zero();
  32594. var lg = 0;
  32595. var nb = 0;
  32596. var shft = 0;
  32597. var dashshft = 0;
  32598. var curshft = 0;
  32599. var idx = 0;
  32600. var i = 0;
  32601. for (i = 0; i < points.length - 1; i++) {
  32602. points[i + 1].subtractToRef(points[i], curvect);
  32603. lg += curvect.length();
  32604. }
  32605. shft = lg / dashNb;
  32606. dashshft = dashSize * shft / (dashSize + gapSize);
  32607. for (i = 0; i < points.length - 1; i++) {
  32608. points[i + 1].subtractToRef(points[i], curvect);
  32609. nb = Math.floor(curvect.length() / shft);
  32610. curvect.normalize();
  32611. for (var j = 0; j < nb; j++) {
  32612. curshft = shft * j;
  32613. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32614. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32615. indices.push(idx, idx + 1);
  32616. idx += 2;
  32617. }
  32618. }
  32619. // Result
  32620. var vertexData = new VertexData();
  32621. vertexData.positions = positions;
  32622. vertexData.indices = indices;
  32623. return vertexData;
  32624. };
  32625. /**
  32626. * Creates the VertexData of the Ground.
  32627. */
  32628. VertexData.CreateGround = function (options) {
  32629. var indices = [];
  32630. var positions = [];
  32631. var normals = [];
  32632. var uvs = [];
  32633. var row, col;
  32634. var width = options.width || 1;
  32635. var height = options.height || 1;
  32636. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32637. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32638. for (row = 0; row <= subdivisionsY; row++) {
  32639. for (col = 0; col <= subdivisionsX; col++) {
  32640. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32641. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32642. positions.push(position.x, position.y, position.z);
  32643. normals.push(normal.x, normal.y, normal.z);
  32644. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32645. }
  32646. }
  32647. for (row = 0; row < subdivisionsY; row++) {
  32648. for (col = 0; col < subdivisionsX; col++) {
  32649. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32650. indices.push(col + 1 + row * (subdivisionsX + 1));
  32651. indices.push(col + row * (subdivisionsX + 1));
  32652. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32653. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32654. indices.push(col + row * (subdivisionsX + 1));
  32655. }
  32656. }
  32657. // Result
  32658. var vertexData = new VertexData();
  32659. vertexData.indices = indices;
  32660. vertexData.positions = positions;
  32661. vertexData.normals = normals;
  32662. vertexData.uvs = uvs;
  32663. return vertexData;
  32664. };
  32665. /**
  32666. * Creates the VertexData of the TiledGround.
  32667. */
  32668. VertexData.CreateTiledGround = function (options) {
  32669. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32670. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32671. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32672. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32673. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32674. var precision = options.precision || { w: 1, h: 1 };
  32675. var indices = new Array();
  32676. var positions = new Array();
  32677. var normals = new Array();
  32678. var uvs = new Array();
  32679. var row, col, tileRow, tileCol;
  32680. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32681. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32682. precision.w = (precision.w < 1) ? 1 : precision.w;
  32683. precision.h = (precision.h < 1) ? 1 : precision.h;
  32684. var tileSize = {
  32685. 'w': (xmax - xmin) / subdivisions.w,
  32686. 'h': (zmax - zmin) / subdivisions.h
  32687. };
  32688. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32689. // Indices
  32690. var base = positions.length / 3;
  32691. var rowLength = precision.w + 1;
  32692. for (row = 0; row < precision.h; row++) {
  32693. for (col = 0; col < precision.w; col++) {
  32694. var square = [
  32695. base + col + row * rowLength,
  32696. base + (col + 1) + row * rowLength,
  32697. base + (col + 1) + (row + 1) * rowLength,
  32698. base + col + (row + 1) * rowLength
  32699. ];
  32700. indices.push(square[1]);
  32701. indices.push(square[2]);
  32702. indices.push(square[3]);
  32703. indices.push(square[0]);
  32704. indices.push(square[1]);
  32705. indices.push(square[3]);
  32706. }
  32707. }
  32708. // Position, normals and uvs
  32709. var position = BABYLON.Vector3.Zero();
  32710. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32711. for (row = 0; row <= precision.h; row++) {
  32712. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32713. for (col = 0; col <= precision.w; col++) {
  32714. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32715. position.y = 0;
  32716. positions.push(position.x, position.y, position.z);
  32717. normals.push(normal.x, normal.y, normal.z);
  32718. uvs.push(col / precision.w, row / precision.h);
  32719. }
  32720. }
  32721. }
  32722. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32723. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32724. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32725. }
  32726. }
  32727. // Result
  32728. var vertexData = new VertexData();
  32729. vertexData.indices = indices;
  32730. vertexData.positions = positions;
  32731. vertexData.normals = normals;
  32732. vertexData.uvs = uvs;
  32733. return vertexData;
  32734. };
  32735. /**
  32736. * Creates the VertexData of the Ground designed from a heightmap.
  32737. */
  32738. VertexData.CreateGroundFromHeightMap = function (options) {
  32739. var indices = [];
  32740. var positions = [];
  32741. var normals = [];
  32742. var uvs = [];
  32743. var row, col;
  32744. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  32745. // Vertices
  32746. for (row = 0; row <= options.subdivisions; row++) {
  32747. for (col = 0; col <= options.subdivisions; col++) {
  32748. 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));
  32749. // Compute height
  32750. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32751. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32752. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32753. var r = options.buffer[pos] / 255.0;
  32754. var g = options.buffer[pos + 1] / 255.0;
  32755. var b = options.buffer[pos + 2] / 255.0;
  32756. var gradient = r * filter.r + g * filter.g + b * filter.b;
  32757. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32758. // Add vertex
  32759. positions.push(position.x, position.y, position.z);
  32760. normals.push(0, 0, 0);
  32761. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32762. }
  32763. }
  32764. // Indices
  32765. for (row = 0; row < options.subdivisions; row++) {
  32766. for (col = 0; col < options.subdivisions; col++) {
  32767. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32768. indices.push(col + 1 + row * (options.subdivisions + 1));
  32769. indices.push(col + row * (options.subdivisions + 1));
  32770. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32771. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32772. indices.push(col + row * (options.subdivisions + 1));
  32773. }
  32774. }
  32775. // Normals
  32776. VertexData.ComputeNormals(positions, indices, normals);
  32777. // Result
  32778. var vertexData = new VertexData();
  32779. vertexData.indices = indices;
  32780. vertexData.positions = positions;
  32781. vertexData.normals = normals;
  32782. vertexData.uvs = uvs;
  32783. return vertexData;
  32784. };
  32785. /**
  32786. * Creates the VertexData of the Plane.
  32787. */
  32788. VertexData.CreatePlane = function (options) {
  32789. var indices = [];
  32790. var positions = [];
  32791. var normals = [];
  32792. var uvs = [];
  32793. var width = options.width || options.size || 1;
  32794. var height = options.height || options.size || 1;
  32795. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32796. // Vertices
  32797. var halfWidth = width / 2.0;
  32798. var halfHeight = height / 2.0;
  32799. positions.push(-halfWidth, -halfHeight, 0);
  32800. normals.push(0, 0, -1.0);
  32801. uvs.push(0.0, 0.0);
  32802. positions.push(halfWidth, -halfHeight, 0);
  32803. normals.push(0, 0, -1.0);
  32804. uvs.push(1.0, 0.0);
  32805. positions.push(halfWidth, halfHeight, 0);
  32806. normals.push(0, 0, -1.0);
  32807. uvs.push(1.0, 1.0);
  32808. positions.push(-halfWidth, halfHeight, 0);
  32809. normals.push(0, 0, -1.0);
  32810. uvs.push(0.0, 1.0);
  32811. // Indices
  32812. indices.push(0);
  32813. indices.push(1);
  32814. indices.push(2);
  32815. indices.push(0);
  32816. indices.push(2);
  32817. indices.push(3);
  32818. // Sides
  32819. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32820. // Result
  32821. var vertexData = new VertexData();
  32822. vertexData.indices = indices;
  32823. vertexData.positions = positions;
  32824. vertexData.normals = normals;
  32825. vertexData.uvs = uvs;
  32826. return vertexData;
  32827. };
  32828. /**
  32829. * Creates the VertexData of the Disc or regular Polygon.
  32830. */
  32831. VertexData.CreateDisc = function (options) {
  32832. var positions = new Array();
  32833. var indices = new Array();
  32834. var normals = new Array();
  32835. var uvs = new Array();
  32836. var radius = options.radius || 0.5;
  32837. var tessellation = options.tessellation || 64;
  32838. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32839. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32840. // positions and uvs
  32841. positions.push(0, 0, 0); // disc center first
  32842. uvs.push(0.5, 0.5);
  32843. var theta = Math.PI * 2 * arc;
  32844. var step = theta / tessellation;
  32845. for (var a = 0; a < theta; a += step) {
  32846. var x = Math.cos(a);
  32847. var y = Math.sin(a);
  32848. var u = (x + 1) / 2;
  32849. var v = (1 - y) / 2;
  32850. positions.push(radius * x, radius * y, 0);
  32851. uvs.push(u, v);
  32852. }
  32853. if (arc === 1) {
  32854. positions.push(positions[3], positions[4], positions[5]); // close the circle
  32855. uvs.push(uvs[2], uvs[3]);
  32856. }
  32857. //indices
  32858. var vertexNb = positions.length / 3;
  32859. for (var i = 1; i < vertexNb - 1; i++) {
  32860. indices.push(i + 1, 0, i);
  32861. }
  32862. // result
  32863. VertexData.ComputeNormals(positions, indices, normals);
  32864. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32865. var vertexData = new VertexData();
  32866. vertexData.indices = indices;
  32867. vertexData.positions = positions;
  32868. vertexData.normals = normals;
  32869. vertexData.uvs = uvs;
  32870. return vertexData;
  32871. };
  32872. /**
  32873. * Re-creates the VertexData of the Polygon for sideOrientation.
  32874. */
  32875. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  32876. var faceUV = fUV || new Array(3);
  32877. var faceColors = fColors;
  32878. var colors = [];
  32879. // default face colors and UV if undefined
  32880. for (var f = 0; f < 3; f++) {
  32881. if (faceUV[f] === undefined) {
  32882. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32883. }
  32884. if (faceColors && faceColors[f] === undefined) {
  32885. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32886. }
  32887. }
  32888. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32889. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32890. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32891. var indices = polygon.getIndices();
  32892. // set face colours and textures
  32893. var idx = 0;
  32894. var face = 0;
  32895. for (var index = 0; index < normals.length; index += 3) {
  32896. //Edge Face no. 1
  32897. if (Math.abs(normals[index + 1]) < 0.001) {
  32898. face = 1;
  32899. }
  32900. //Top Face no. 0
  32901. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  32902. face = 0;
  32903. }
  32904. //Bottom Face no. 2
  32905. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  32906. face = 2;
  32907. }
  32908. idx = index / 3;
  32909. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  32910. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  32911. if (faceColors) {
  32912. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  32913. }
  32914. }
  32915. // sides
  32916. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  32917. // Result
  32918. var vertexData = new VertexData();
  32919. vertexData.indices = indices;
  32920. vertexData.positions = positions;
  32921. vertexData.normals = normals;
  32922. vertexData.uvs = uvs;
  32923. if (faceColors) {
  32924. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32925. vertexData.colors = totalColors;
  32926. }
  32927. return vertexData;
  32928. };
  32929. /**
  32930. * Creates the VertexData of the IcoSphere.
  32931. */
  32932. VertexData.CreateIcoSphere = function (options) {
  32933. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32934. var radius = options.radius || 1;
  32935. var flat = (options.flat === undefined) ? true : options.flat;
  32936. var subdivisions = options.subdivisions || 4;
  32937. var radiusX = options.radiusX || radius;
  32938. var radiusY = options.radiusY || radius;
  32939. var radiusZ = options.radiusZ || radius;
  32940. var t = (1 + Math.sqrt(5)) / 2;
  32941. // 12 vertex x,y,z
  32942. var ico_vertices = [
  32943. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  32944. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  32945. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  32946. ];
  32947. // index of 3 vertex makes a face of icopshere
  32948. var ico_indices = [
  32949. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  32950. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  32951. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  32952. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  32953. ];
  32954. // vertex for uv have aliased position, not for UV
  32955. var vertices_unalias_id = [
  32956. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  32957. // vertex alias
  32958. 0,
  32959. 2,
  32960. 3,
  32961. 3,
  32962. 3,
  32963. 4,
  32964. 7,
  32965. 8,
  32966. 9,
  32967. 9,
  32968. 10,
  32969. 11 // 23: B + 12
  32970. ];
  32971. // uv as integer step (not pixels !)
  32972. var ico_vertexuv = [
  32973. 5, 1, 3, 1, 6, 4, 0, 0,
  32974. 5, 3, 4, 2, 2, 2, 4, 0,
  32975. 2, 0, 1, 1, 6, 0, 6, 2,
  32976. // vertex alias (for same vertex on different faces)
  32977. 0, 4,
  32978. 3, 3,
  32979. 4, 4,
  32980. 3, 1,
  32981. 4, 2,
  32982. 4, 4,
  32983. 0, 2,
  32984. 1, 1,
  32985. 2, 2,
  32986. 3, 3,
  32987. 1, 3,
  32988. 2, 4 // 23: B + 12
  32989. ];
  32990. // Vertices[0, 1, ...9, A, B] : position on UV plane
  32991. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  32992. // First island of uv mapping
  32993. // v = 4h 3+ 2
  32994. // v = 3h 9+ 4
  32995. // v = 2h 9+ 5 B
  32996. // v = 1h 9 1 0
  32997. // v = 0h 3 8 7 A
  32998. // u = 0 1 2 3 4 5 6 *a
  32999. // Second island of uv mapping
  33000. // v = 4h 0+ B+ 4+
  33001. // v = 3h A+ 2+
  33002. // v = 2h 7+ 6 3+
  33003. // v = 1h 8+ 3+
  33004. // v = 0h
  33005. // u = 0 1 2 3 4 5 6 *a
  33006. // Face layout on texture UV mapping
  33007. // ============
  33008. // \ 4 /\ 16 / ======
  33009. // \ / \ / /\ 11 /
  33010. // \/ 7 \/ / \ /
  33011. // ======= / 10 \/
  33012. // /\ 17 /\ =======
  33013. // / \ / \ \ 15 /\
  33014. // / 8 \/ 12 \ \ / \
  33015. // ============ \/ 6 \
  33016. // \ 18 /\ ============
  33017. // \ / \ \ 5 /\ 0 /
  33018. // \/ 13 \ \ / \ /
  33019. // ======= \/ 1 \/
  33020. // =============
  33021. // /\ 19 /\ 2 /\
  33022. // / \ / \ / \
  33023. // / 14 \/ 9 \/ 3 \
  33024. // ===================
  33025. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33026. var ustep = 138 / 1024;
  33027. var vstep = 239 / 1024;
  33028. var uoffset = 60 / 1024;
  33029. var voffset = 26 / 1024;
  33030. // Second island should have margin, not to touch the first island
  33031. // avoid any borderline artefact in pixel rounding
  33032. var island_u_offset = -40 / 1024;
  33033. var island_v_offset = +20 / 1024;
  33034. // face is either island 0 or 1 :
  33035. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33036. var island = [
  33037. 0, 0, 0, 0, 1,
  33038. 0, 0, 1, 1, 0,
  33039. 0, 0, 1, 1, 0,
  33040. 0, 1, 1, 1, 0 // 15 - 19
  33041. ];
  33042. var indices = new Array();
  33043. var positions = new Array();
  33044. var normals = new Array();
  33045. var uvs = new Array();
  33046. var current_indice = 0;
  33047. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33048. var face_vertex_pos = new Array(3);
  33049. var face_vertex_uv = new Array(3);
  33050. var v012;
  33051. for (v012 = 0; v012 < 3; v012++) {
  33052. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33053. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33054. }
  33055. // create all with normals
  33056. for (var face = 0; face < 20; face++) {
  33057. // 3 vertex per face
  33058. for (v012 = 0; v012 < 3; v012++) {
  33059. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33060. var v_id = ico_indices[3 * face + v012];
  33061. // vertex have 3D position (x,y,z)
  33062. 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]);
  33063. // Normalize to get normal, then scale to radius
  33064. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33065. // uv Coordinates from vertex ID
  33066. 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);
  33067. }
  33068. // Subdivide the face (interpolate pos, norm, uv)
  33069. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33070. // - norm is linear interpolation of vertex corner normal
  33071. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33072. // - uv is linear interpolation
  33073. //
  33074. // Topology is as below for sub-divide by 2
  33075. // vertex shown as v0,v1,v2
  33076. // interp index is i1 to progress in range [v0,v1[
  33077. // interp index is i2 to progress in range [v0,v2[
  33078. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33079. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33080. //
  33081. //
  33082. // i2 v2
  33083. // ^ ^
  33084. // / / \
  33085. // / / \
  33086. // / / \
  33087. // / / (0,1) \
  33088. // / #---------\
  33089. // / / \ (0,0)'/ \
  33090. // / / \ / \
  33091. // / / \ / \
  33092. // / / (0,0) \ / (1,0) \
  33093. // / #---------#---------\
  33094. // v0 v1
  33095. //
  33096. // --------------------> i1
  33097. //
  33098. // interp of (i1,i2):
  33099. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33100. // along i1 : lerp(x0,x1, i1/(S-i2))
  33101. //
  33102. // centroid of triangle is needed to get help normal computation
  33103. // (c1,c2) are used for centroid location
  33104. var interp_vertex = function (i1, i2, c1, c2) {
  33105. // vertex is interpolated from
  33106. // - face_vertex_pos[0..2]
  33107. // - face_vertex_uv[0..2]
  33108. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33109. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33110. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33111. pos_interp.normalize();
  33112. var vertex_normal;
  33113. if (flat) {
  33114. // in flat mode, recalculate normal as face centroid normal
  33115. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33116. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33117. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33118. }
  33119. else {
  33120. // in smooth mode, recalculate normal from each single vertex position
  33121. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33122. }
  33123. // Vertex normal need correction due to X,Y,Z radius scaling
  33124. vertex_normal.x /= radiusX;
  33125. vertex_normal.y /= radiusY;
  33126. vertex_normal.z /= radiusZ;
  33127. vertex_normal.normalize();
  33128. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33129. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33130. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33131. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33132. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33133. uvs.push(uv_interp.x, uv_interp.y);
  33134. // push each vertex has member of a face
  33135. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33136. indices.push(current_indice);
  33137. current_indice++;
  33138. };
  33139. for (var i2 = 0; i2 < subdivisions; i2++) {
  33140. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33141. // face : (i1,i2) for /\ :
  33142. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33143. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33144. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33145. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33146. if (i1 + i2 + 1 < subdivisions) {
  33147. // face : (i1,i2)' for \/ :
  33148. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33149. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33150. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33151. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33152. }
  33153. }
  33154. }
  33155. }
  33156. // Sides
  33157. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33158. // Result
  33159. var vertexData = new VertexData();
  33160. vertexData.indices = indices;
  33161. vertexData.positions = positions;
  33162. vertexData.normals = normals;
  33163. vertexData.uvs = uvs;
  33164. return vertexData;
  33165. };
  33166. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33167. /**
  33168. * Creates the VertexData of the Polyhedron.
  33169. */
  33170. VertexData.CreatePolyhedron = function (options) {
  33171. // provided polyhedron types :
  33172. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33173. // 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)
  33174. var polyhedra = [];
  33175. 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]] };
  33176. 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]] };
  33177. polyhedra[2] = {
  33178. 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]],
  33179. 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]]
  33180. };
  33181. polyhedra[3] = {
  33182. 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]],
  33183. 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]]
  33184. };
  33185. polyhedra[4] = {
  33186. 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]],
  33187. 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]]
  33188. };
  33189. 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]] };
  33190. 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]] };
  33191. 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]] };
  33192. 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]] };
  33193. 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]] };
  33194. 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]] };
  33195. 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]] };
  33196. 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]] };
  33197. 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]] };
  33198. polyhedra[14] = {
  33199. 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]],
  33200. 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]]
  33201. };
  33202. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33203. var size = options.size;
  33204. var sizeX = options.sizeX || size || 1;
  33205. var sizeY = options.sizeY || size || 1;
  33206. var sizeZ = options.sizeZ || size || 1;
  33207. var data = options.custom || polyhedra[type];
  33208. var nbfaces = data.face.length;
  33209. var faceUV = options.faceUV || new Array(nbfaces);
  33210. var faceColors = options.faceColors;
  33211. var flat = (options.flat === undefined) ? true : options.flat;
  33212. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33213. var positions = new Array();
  33214. var indices = new Array();
  33215. var normals = new Array();
  33216. var uvs = new Array();
  33217. var colors = new Array();
  33218. var index = 0;
  33219. var faceIdx = 0; // face cursor in the array "indexes"
  33220. var indexes = new Array();
  33221. var i = 0;
  33222. var f = 0;
  33223. var u, v, ang, x, y, tmp;
  33224. // default face colors and UV if undefined
  33225. if (flat) {
  33226. for (f = 0; f < nbfaces; f++) {
  33227. if (faceColors && faceColors[f] === undefined) {
  33228. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33229. }
  33230. if (faceUV && faceUV[f] === undefined) {
  33231. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33232. }
  33233. }
  33234. }
  33235. if (!flat) {
  33236. for (i = 0; i < data.vertex.length; i++) {
  33237. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33238. uvs.push(0, 0);
  33239. }
  33240. for (f = 0; f < nbfaces; f++) {
  33241. for (i = 0; i < data.face[f].length - 2; i++) {
  33242. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33243. }
  33244. }
  33245. }
  33246. else {
  33247. for (f = 0; f < nbfaces; f++) {
  33248. var fl = data.face[f].length; // number of vertices of the current face
  33249. ang = 2 * Math.PI / fl;
  33250. x = 0.5 * Math.tan(ang / 2);
  33251. y = 0.5;
  33252. // positions, uvs, colors
  33253. for (i = 0; i < fl; i++) {
  33254. // positions
  33255. 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);
  33256. indexes.push(index);
  33257. index++;
  33258. // uvs
  33259. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33260. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33261. uvs.push(u, v);
  33262. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33263. y = x * Math.sin(ang) + y * Math.cos(ang);
  33264. x = tmp;
  33265. // colors
  33266. if (faceColors) {
  33267. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33268. }
  33269. }
  33270. // indices from indexes
  33271. for (i = 0; i < fl - 2; i++) {
  33272. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33273. }
  33274. faceIdx += fl;
  33275. }
  33276. }
  33277. VertexData.ComputeNormals(positions, indices, normals);
  33278. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33279. var vertexData = new VertexData();
  33280. vertexData.positions = positions;
  33281. vertexData.indices = indices;
  33282. vertexData.normals = normals;
  33283. vertexData.uvs = uvs;
  33284. if (faceColors && flat) {
  33285. vertexData.colors = colors;
  33286. }
  33287. return vertexData;
  33288. };
  33289. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33290. /**
  33291. * Creates the VertexData of the Torus Knot.
  33292. */
  33293. VertexData.CreateTorusKnot = function (options) {
  33294. var indices = new Array();
  33295. var positions = new Array();
  33296. var normals = new Array();
  33297. var uvs = new Array();
  33298. var radius = options.radius || 2;
  33299. var tube = options.tube || 0.5;
  33300. var radialSegments = options.radialSegments || 32;
  33301. var tubularSegments = options.tubularSegments || 32;
  33302. var p = options.p || 2;
  33303. var q = options.q || 3;
  33304. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33305. // Helper
  33306. var getPos = function (angle) {
  33307. var cu = Math.cos(angle);
  33308. var su = Math.sin(angle);
  33309. var quOverP = q / p * angle;
  33310. var cs = Math.cos(quOverP);
  33311. var tx = radius * (2 + cs) * 0.5 * cu;
  33312. var ty = radius * (2 + cs) * su * 0.5;
  33313. var tz = radius * Math.sin(quOverP) * 0.5;
  33314. return new BABYLON.Vector3(tx, ty, tz);
  33315. };
  33316. // Vertices
  33317. var i;
  33318. var j;
  33319. for (i = 0; i <= radialSegments; i++) {
  33320. var modI = i % radialSegments;
  33321. var u = modI / radialSegments * 2 * p * Math.PI;
  33322. var p1 = getPos(u);
  33323. var p2 = getPos(u + 0.01);
  33324. var tang = p2.subtract(p1);
  33325. var n = p2.add(p1);
  33326. var bitan = BABYLON.Vector3.Cross(tang, n);
  33327. n = BABYLON.Vector3.Cross(bitan, tang);
  33328. bitan.normalize();
  33329. n.normalize();
  33330. for (j = 0; j < tubularSegments; j++) {
  33331. var modJ = j % tubularSegments;
  33332. var v = modJ / tubularSegments * 2 * Math.PI;
  33333. var cx = -tube * Math.cos(v);
  33334. var cy = tube * Math.sin(v);
  33335. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33336. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33337. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33338. uvs.push(i / radialSegments);
  33339. uvs.push(j / tubularSegments);
  33340. }
  33341. }
  33342. for (i = 0; i < radialSegments; i++) {
  33343. for (j = 0; j < tubularSegments; j++) {
  33344. var jNext = (j + 1) % tubularSegments;
  33345. var a = i * tubularSegments + j;
  33346. var b = (i + 1) * tubularSegments + j;
  33347. var c = (i + 1) * tubularSegments + jNext;
  33348. var d = i * tubularSegments + jNext;
  33349. indices.push(d);
  33350. indices.push(b);
  33351. indices.push(a);
  33352. indices.push(d);
  33353. indices.push(c);
  33354. indices.push(b);
  33355. }
  33356. }
  33357. // Normals
  33358. VertexData.ComputeNormals(positions, indices, normals);
  33359. // Sides
  33360. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33361. // Result
  33362. var vertexData = new VertexData();
  33363. vertexData.indices = indices;
  33364. vertexData.positions = positions;
  33365. vertexData.normals = normals;
  33366. vertexData.uvs = uvs;
  33367. return vertexData;
  33368. };
  33369. // Tools
  33370. /**
  33371. * @param {any} - positions (number[] or Float32Array)
  33372. * @param {any} - indices (number[] or Uint16Array)
  33373. * @param {any} - normals (number[] or Float32Array)
  33374. * options (optional) :
  33375. * facetPositions : optional array of facet positions (vector3)
  33376. * facetNormals : optional array of facet normals (vector3)
  33377. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33378. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33379. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33380. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33381. * bInfo : optional bounding info, required for facetPartitioning computation
  33382. * useRightHandedSystem: optional boolean to for right handed system computation
  33383. * depthSort : optional boolean to enable the facet depth sort computation
  33384. * distanceTo : optional Vector3 to compute the facet depth from this location
  33385. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33386. */
  33387. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33388. // temporary scalar variables
  33389. var index = 0; // facet index
  33390. var p1p2x = 0.0; // p1p2 vector x coordinate
  33391. var p1p2y = 0.0; // p1p2 vector y coordinate
  33392. var p1p2z = 0.0; // p1p2 vector z coordinate
  33393. var p3p2x = 0.0; // p3p2 vector x coordinate
  33394. var p3p2y = 0.0; // p3p2 vector y coordinate
  33395. var p3p2z = 0.0; // p3p2 vector z coordinate
  33396. var faceNormalx = 0.0; // facet normal x coordinate
  33397. var faceNormaly = 0.0; // facet normal y coordinate
  33398. var faceNormalz = 0.0; // facet normal z coordinate
  33399. var length = 0.0; // facet normal length before normalization
  33400. var v1x = 0; // vector1 x index in the positions array
  33401. var v1y = 0; // vector1 y index in the positions array
  33402. var v1z = 0; // vector1 z index in the positions array
  33403. var v2x = 0; // vector2 x index in the positions array
  33404. var v2y = 0; // vector2 y index in the positions array
  33405. var v2z = 0; // vector2 z index in the positions array
  33406. var v3x = 0; // vector3 x index in the positions array
  33407. var v3y = 0; // vector3 y index in the positions array
  33408. var v3z = 0; // vector3 z index in the positions array
  33409. var computeFacetNormals = false;
  33410. var computeFacetPositions = false;
  33411. var computeFacetPartitioning = false;
  33412. var computeDepthSort = false;
  33413. var faceNormalSign = 1;
  33414. var ratio = 0;
  33415. var distanceTo = null;
  33416. if (options) {
  33417. computeFacetNormals = (options.facetNormals) ? true : false;
  33418. computeFacetPositions = (options.facetPositions) ? true : false;
  33419. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33420. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33421. ratio = options.ratio || 0;
  33422. computeDepthSort = (options.depthSort) ? true : false;
  33423. distanceTo = (options.distanceTo);
  33424. if (computeDepthSort) {
  33425. if (distanceTo === undefined) {
  33426. distanceTo = BABYLON.Vector3.Zero();
  33427. }
  33428. var depthSortedFacets = options.depthSortedFacets;
  33429. }
  33430. }
  33431. // facetPartitioning reinit if needed
  33432. var xSubRatio = 0;
  33433. var ySubRatio = 0;
  33434. var zSubRatio = 0;
  33435. var subSq = 0;
  33436. if (computeFacetPartitioning && options && options.bbSize) {
  33437. var ox = 0; // X partitioning index for facet position
  33438. var oy = 0; // Y partinioning index for facet position
  33439. var oz = 0; // Z partinioning index for facet position
  33440. var b1x = 0; // X partitioning index for facet v1 vertex
  33441. var b1y = 0; // Y partitioning index for facet v1 vertex
  33442. var b1z = 0; // z partitioning index for facet v1 vertex
  33443. var b2x = 0; // X partitioning index for facet v2 vertex
  33444. var b2y = 0; // Y partitioning index for facet v2 vertex
  33445. var b2z = 0; // Z partitioning index for facet v2 vertex
  33446. var b3x = 0; // X partitioning index for facet v3 vertex
  33447. var b3y = 0; // Y partitioning index for facet v3 vertex
  33448. var b3z = 0; // Z partitioning index for facet v3 vertex
  33449. var block_idx_o = 0; // facet barycenter block index
  33450. var block_idx_v1 = 0; // v1 vertex block index
  33451. var block_idx_v2 = 0; // v2 vertex block index
  33452. var block_idx_v3 = 0; // v3 vertex block index
  33453. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33454. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33455. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33456. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33457. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33458. subSq = options.subDiv.max * options.subDiv.max;
  33459. options.facetPartitioning.length = 0;
  33460. }
  33461. // reset the normals
  33462. for (index = 0; index < positions.length; index++) {
  33463. normals[index] = 0.0;
  33464. }
  33465. // Loop : 1 indice triplet = 1 facet
  33466. var nbFaces = (indices.length / 3) | 0;
  33467. for (index = 0; index < nbFaces; index++) {
  33468. // get the indexes of the coordinates of each vertex of the facet
  33469. v1x = indices[index * 3] * 3;
  33470. v1y = v1x + 1;
  33471. v1z = v1x + 2;
  33472. v2x = indices[index * 3 + 1] * 3;
  33473. v2y = v2x + 1;
  33474. v2z = v2x + 2;
  33475. v3x = indices[index * 3 + 2] * 3;
  33476. v3y = v3x + 1;
  33477. v3z = v3x + 2;
  33478. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33479. p1p2y = positions[v1y] - positions[v2y];
  33480. p1p2z = positions[v1z] - positions[v2z];
  33481. p3p2x = positions[v3x] - positions[v2x];
  33482. p3p2y = positions[v3y] - positions[v2y];
  33483. p3p2z = positions[v3z] - positions[v2z];
  33484. // compute the face normal with the cross product
  33485. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33486. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33487. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33488. // normalize this normal and store it in the array facetData
  33489. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33490. length = (length === 0) ? 1.0 : length;
  33491. faceNormalx /= length;
  33492. faceNormaly /= length;
  33493. faceNormalz /= length;
  33494. if (computeFacetNormals && options) {
  33495. options.facetNormals[index].x = faceNormalx;
  33496. options.facetNormals[index].y = faceNormaly;
  33497. options.facetNormals[index].z = faceNormalz;
  33498. }
  33499. if (computeFacetPositions && options) {
  33500. // compute and the facet barycenter coordinates in the array facetPositions
  33501. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33502. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33503. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33504. }
  33505. if (computeFacetPartitioning && options) {
  33506. // store the facet indexes in arrays in the main facetPartitioning array :
  33507. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33508. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33509. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33510. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33511. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33512. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33513. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33514. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33515. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33516. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33517. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33518. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33519. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33520. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33521. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33522. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33523. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33524. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33525. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33526. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33527. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33528. // push each facet index in each block containing the vertex
  33529. options.facetPartitioning[block_idx_v1].push(index);
  33530. if (block_idx_v2 != block_idx_v1) {
  33531. options.facetPartitioning[block_idx_v2].push(index);
  33532. }
  33533. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33534. options.facetPartitioning[block_idx_v3].push(index);
  33535. }
  33536. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33537. options.facetPartitioning[block_idx_o].push(index);
  33538. }
  33539. }
  33540. if (computeDepthSort && options && options.facetPositions) {
  33541. var dsf = depthSortedFacets[index];
  33542. dsf.ind = index * 3;
  33543. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33544. }
  33545. // compute the normals anyway
  33546. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33547. normals[v1y] += faceNormaly;
  33548. normals[v1z] += faceNormalz;
  33549. normals[v2x] += faceNormalx;
  33550. normals[v2y] += faceNormaly;
  33551. normals[v2z] += faceNormalz;
  33552. normals[v3x] += faceNormalx;
  33553. normals[v3y] += faceNormaly;
  33554. normals[v3z] += faceNormalz;
  33555. }
  33556. // last normalization of each normal
  33557. for (index = 0; index < normals.length / 3; index++) {
  33558. faceNormalx = normals[index * 3];
  33559. faceNormaly = normals[index * 3 + 1];
  33560. faceNormalz = normals[index * 3 + 2];
  33561. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33562. length = (length === 0) ? 1.0 : length;
  33563. faceNormalx /= length;
  33564. faceNormaly /= length;
  33565. faceNormalz /= length;
  33566. normals[index * 3] = faceNormalx;
  33567. normals[index * 3 + 1] = faceNormaly;
  33568. normals[index * 3 + 2] = faceNormalz;
  33569. }
  33570. };
  33571. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33572. var li = indices.length;
  33573. var ln = normals.length;
  33574. var i;
  33575. var n;
  33576. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33577. switch (sideOrientation) {
  33578. case BABYLON.Mesh.FRONTSIDE:
  33579. // nothing changed
  33580. break;
  33581. case BABYLON.Mesh.BACKSIDE:
  33582. var tmp;
  33583. // indices
  33584. for (i = 0; i < li; i += 3) {
  33585. tmp = indices[i];
  33586. indices[i] = indices[i + 2];
  33587. indices[i + 2] = tmp;
  33588. }
  33589. // normals
  33590. for (n = 0; n < ln; n++) {
  33591. normals[n] = -normals[n];
  33592. }
  33593. break;
  33594. case BABYLON.Mesh.DOUBLESIDE:
  33595. // positions
  33596. var lp = positions.length;
  33597. var l = lp / 3;
  33598. for (var p = 0; p < lp; p++) {
  33599. positions[lp + p] = positions[p];
  33600. }
  33601. // indices
  33602. for (i = 0; i < li; i += 3) {
  33603. indices[i + li] = indices[i + 2] + l;
  33604. indices[i + 1 + li] = indices[i + 1] + l;
  33605. indices[i + 2 + li] = indices[i] + l;
  33606. }
  33607. // normals
  33608. for (n = 0; n < ln; n++) {
  33609. normals[ln + n] = -normals[n];
  33610. }
  33611. // uvs
  33612. var lu = uvs.length;
  33613. var u = 0;
  33614. for (u = 0; u < lu; u++) {
  33615. uvs[u + lu] = uvs[u];
  33616. }
  33617. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33618. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33619. u = 0;
  33620. for (i = 0; i < lu / 2; i++) {
  33621. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33622. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33623. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33624. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33625. u += 2;
  33626. }
  33627. break;
  33628. }
  33629. };
  33630. /**
  33631. * Creates a new VertexData from the imported parameters.
  33632. */
  33633. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33634. var vertexData = new VertexData();
  33635. // positions
  33636. var positions = parsedVertexData.positions;
  33637. if (positions) {
  33638. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33639. }
  33640. // normals
  33641. var normals = parsedVertexData.normals;
  33642. if (normals) {
  33643. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33644. }
  33645. // tangents
  33646. var tangents = parsedVertexData.tangents;
  33647. if (tangents) {
  33648. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33649. }
  33650. // uvs
  33651. var uvs = parsedVertexData.uvs;
  33652. if (uvs) {
  33653. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33654. }
  33655. // uv2s
  33656. var uv2s = parsedVertexData.uv2s;
  33657. if (uv2s) {
  33658. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33659. }
  33660. // uv3s
  33661. var uv3s = parsedVertexData.uv3s;
  33662. if (uv3s) {
  33663. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33664. }
  33665. // uv4s
  33666. var uv4s = parsedVertexData.uv4s;
  33667. if (uv4s) {
  33668. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33669. }
  33670. // uv5s
  33671. var uv5s = parsedVertexData.uv5s;
  33672. if (uv5s) {
  33673. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33674. }
  33675. // uv6s
  33676. var uv6s = parsedVertexData.uv6s;
  33677. if (uv6s) {
  33678. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33679. }
  33680. // colors
  33681. var colors = parsedVertexData.colors;
  33682. if (colors) {
  33683. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33684. }
  33685. // matricesIndices
  33686. var matricesIndices = parsedVertexData.matricesIndices;
  33687. if (matricesIndices) {
  33688. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33689. }
  33690. // matricesWeights
  33691. var matricesWeights = parsedVertexData.matricesWeights;
  33692. if (matricesWeights) {
  33693. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33694. }
  33695. // indices
  33696. var indices = parsedVertexData.indices;
  33697. if (indices) {
  33698. vertexData.indices = indices;
  33699. }
  33700. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33701. };
  33702. return VertexData;
  33703. }());
  33704. BABYLON.VertexData = VertexData;
  33705. })(BABYLON || (BABYLON = {}));
  33706. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33707. var BABYLON;
  33708. (function (BABYLON) {
  33709. /**
  33710. * Class used to store geometry data (vertex buffers + index buffer)
  33711. */
  33712. var Geometry = /** @class */ (function () {
  33713. /**
  33714. * Creates a new geometry
  33715. * @param id defines the unique ID
  33716. * @param scene defines the hosting scene
  33717. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  33718. * @param updatable defines if geometry must be updatable (false by default)
  33719. * @param mesh defines the mesh that will be associated with the geometry
  33720. */
  33721. function Geometry(id, scene, vertexData, updatable, mesh) {
  33722. if (updatable === void 0) { updatable = false; }
  33723. if (mesh === void 0) { mesh = null; }
  33724. /**
  33725. * Gets the delay loading state of the geometry (none by default which means not delayed)
  33726. */
  33727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33728. this._totalVertices = 0;
  33729. this._isDisposed = false;
  33730. this._indexBufferIsUpdatable = false;
  33731. this.id = id;
  33732. this._engine = scene.getEngine();
  33733. this._meshes = [];
  33734. this._scene = scene;
  33735. //Init vertex buffer cache
  33736. this._vertexBuffers = {};
  33737. this._indices = [];
  33738. this._updatable = updatable;
  33739. // vertexData
  33740. if (vertexData) {
  33741. this.setAllVerticesData(vertexData, updatable);
  33742. }
  33743. else {
  33744. this._totalVertices = 0;
  33745. this._indices = [];
  33746. }
  33747. if (this._engine.getCaps().vertexArrayObject) {
  33748. this._vertexArrayObjects = {};
  33749. }
  33750. // applyToMesh
  33751. if (mesh) {
  33752. if (mesh.getClassName() === "LinesMesh") {
  33753. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33754. this.updateExtend();
  33755. }
  33756. this.applyToMesh(mesh);
  33757. mesh.computeWorldMatrix(true);
  33758. }
  33759. }
  33760. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33761. /**
  33762. * 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
  33763. */
  33764. get: function () {
  33765. return this._boundingBias;
  33766. },
  33767. /**
  33768. * 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
  33769. */
  33770. set: function (value) {
  33771. if (this._boundingBias && this._boundingBias.equals(value)) {
  33772. return;
  33773. }
  33774. this._boundingBias = value.clone();
  33775. this.updateBoundingInfo(true, null);
  33776. },
  33777. enumerable: true,
  33778. configurable: true
  33779. });
  33780. /**
  33781. * Static function used to attach a new empty geometry to a mesh
  33782. * @param mesh defines the mesh to attach the geometry to
  33783. * @returns the new {BABYLON.Geometry}
  33784. */
  33785. Geometry.CreateGeometryForMesh = function (mesh) {
  33786. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  33787. geometry.applyToMesh(mesh);
  33788. return geometry;
  33789. };
  33790. Object.defineProperty(Geometry.prototype, "extend", {
  33791. /**
  33792. * Gets the current extend of the geometry
  33793. */
  33794. get: function () {
  33795. return this._extend;
  33796. },
  33797. enumerable: true,
  33798. configurable: true
  33799. });
  33800. /**
  33801. * Gets the hosting scene
  33802. * @returns the hosting {BABYLON.Scene}
  33803. */
  33804. Geometry.prototype.getScene = function () {
  33805. return this._scene;
  33806. };
  33807. /**
  33808. * Gets the hosting engine
  33809. * @returns the hosting {BABYLON.Engine}
  33810. */
  33811. Geometry.prototype.getEngine = function () {
  33812. return this._engine;
  33813. };
  33814. /**
  33815. * Defines if the geometry is ready to use
  33816. * @returns true if the geometry is ready to be used
  33817. */
  33818. Geometry.prototype.isReady = function () {
  33819. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33820. };
  33821. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  33822. /**
  33823. * Gets a value indicating that the geometry should not be serialized
  33824. */
  33825. get: function () {
  33826. for (var index = 0; index < this._meshes.length; index++) {
  33827. if (!this._meshes[index].doNotSerialize) {
  33828. return false;
  33829. }
  33830. }
  33831. return true;
  33832. },
  33833. enumerable: true,
  33834. configurable: true
  33835. });
  33836. /** @ignore */
  33837. Geometry.prototype._rebuild = function () {
  33838. if (this._vertexArrayObjects) {
  33839. this._vertexArrayObjects = {};
  33840. }
  33841. // Index buffer
  33842. if (this._meshes.length !== 0 && this._indices) {
  33843. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33844. }
  33845. // Vertex buffers
  33846. for (var key in this._vertexBuffers) {
  33847. var vertexBuffer = this._vertexBuffers[key];
  33848. vertexBuffer._rebuild();
  33849. }
  33850. };
  33851. /**
  33852. * Affects all gemetry data in one call
  33853. * @param vertexData defines the geometry data
  33854. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  33855. */
  33856. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33857. vertexData.applyToGeometry(this, updatable);
  33858. this.notifyUpdate();
  33859. };
  33860. /**
  33861. * Set specific vertex data
  33862. * @param kind defines the data kind (Position, normal, etc...)
  33863. * @param data defines the vertex data to use
  33864. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  33865. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  33866. */
  33867. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33868. if (updatable === void 0) { updatable = false; }
  33869. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33870. this.setVerticesBuffer(buffer);
  33871. };
  33872. /**
  33873. * Removes a specific vertex data
  33874. * @param kind defines the data kind (Position, normal, etc...)
  33875. */
  33876. Geometry.prototype.removeVerticesData = function (kind) {
  33877. if (this._vertexBuffers[kind]) {
  33878. this._vertexBuffers[kind].dispose();
  33879. delete this._vertexBuffers[kind];
  33880. }
  33881. };
  33882. /**
  33883. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  33884. * @param buffer defines the vertex buffer to use
  33885. */
  33886. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33887. var kind = buffer.getKind();
  33888. if (this._vertexBuffers[kind]) {
  33889. this._vertexBuffers[kind].dispose();
  33890. }
  33891. this._vertexBuffers[kind] = buffer;
  33892. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33893. var data = buffer.getData();
  33894. var stride = buffer.getStrideSize();
  33895. this._totalVertices = data.length / stride;
  33896. this.updateExtend(data, stride);
  33897. this._resetPointsArrayCache();
  33898. var meshes = this._meshes;
  33899. var numOfMeshes = meshes.length;
  33900. for (var index = 0; index < numOfMeshes; index++) {
  33901. var mesh = meshes[index];
  33902. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33903. mesh._createGlobalSubMesh(false);
  33904. mesh.computeWorldMatrix(true);
  33905. }
  33906. }
  33907. this.notifyUpdate(kind);
  33908. if (this._vertexArrayObjects) {
  33909. this._disposeVertexArrayObjects();
  33910. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  33911. }
  33912. };
  33913. /**
  33914. * Update a specific vertex buffer
  33915. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  33916. * It will do nothing if the buffer is not updatable
  33917. * @param kind defines the data kind (Position, normal, etc...)
  33918. * @param data defines the data to use
  33919. * @param offset defines the offset in the target buffer where to store the data
  33920. */
  33921. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33922. var vertexBuffer = this.getVertexBuffer(kind);
  33923. if (!vertexBuffer) {
  33924. return;
  33925. }
  33926. vertexBuffer.updateDirectly(data, offset);
  33927. this.notifyUpdate(kind);
  33928. };
  33929. /**
  33930. * Update a specific vertex buffer
  33931. * This function will create a new buffer if the current one is not updatable
  33932. * @param kind defines the data kind (Position, normal, etc...)
  33933. * @param data defines the data to use
  33934. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  33935. */
  33936. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33937. if (updateExtends === void 0) { updateExtends = false; }
  33938. var vertexBuffer = this.getVertexBuffer(kind);
  33939. if (!vertexBuffer) {
  33940. return;
  33941. }
  33942. vertexBuffer.update(data);
  33943. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33944. var stride = vertexBuffer.getStrideSize();
  33945. this._totalVertices = data.length / stride;
  33946. this.updateBoundingInfo(updateExtends, data);
  33947. }
  33948. this.notifyUpdate(kind);
  33949. };
  33950. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33951. if (updateExtends) {
  33952. this.updateExtend(data);
  33953. }
  33954. var meshes = this._meshes;
  33955. var numOfMeshes = meshes.length;
  33956. this._resetPointsArrayCache();
  33957. for (var index = 0; index < numOfMeshes; index++) {
  33958. var mesh = meshes[index];
  33959. if (updateExtends) {
  33960. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33961. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33962. var subMesh = mesh.subMeshes[subIndex];
  33963. subMesh.refreshBoundingInfo();
  33964. }
  33965. }
  33966. }
  33967. };
  33968. /** @ignore */
  33969. Geometry.prototype._bind = function (effect, indexToBind) {
  33970. if (!effect) {
  33971. return;
  33972. }
  33973. if (indexToBind === undefined) {
  33974. indexToBind = this._indexBuffer;
  33975. }
  33976. var vbs = this.getVertexBuffers();
  33977. if (!vbs) {
  33978. return;
  33979. }
  33980. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  33981. this._engine.bindBuffers(vbs, indexToBind, effect);
  33982. return;
  33983. }
  33984. // Using VAO
  33985. if (!this._vertexArrayObjects[effect.key]) {
  33986. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  33987. }
  33988. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  33989. };
  33990. /**
  33991. * Gets total number of vertices
  33992. * @returns the total number of vertices
  33993. */
  33994. Geometry.prototype.getTotalVertices = function () {
  33995. if (!this.isReady()) {
  33996. return 0;
  33997. }
  33998. return this._totalVertices;
  33999. };
  34000. /**
  34001. * Gets a specific vertex data attached to this geometry
  34002. * @param kind defines the data kind (Position, normal, etc...)
  34003. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34004. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34005. * @returns a float array containing vertex data
  34006. */
  34007. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34008. var vertexBuffer = this.getVertexBuffer(kind);
  34009. if (!vertexBuffer) {
  34010. return null;
  34011. }
  34012. var orig = vertexBuffer.getData();
  34013. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34014. return orig;
  34015. }
  34016. else {
  34017. var len = orig.length;
  34018. var copy = [];
  34019. for (var i = 0; i < len; i++) {
  34020. copy.push(orig[i]);
  34021. }
  34022. return copy;
  34023. }
  34024. };
  34025. /**
  34026. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34027. * @param kind defines the data kind (Position, normal, etc...)
  34028. * @returns true if the vertex buffer with the specified kind is updatable
  34029. */
  34030. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34031. var vb = this._vertexBuffers[kind];
  34032. if (!vb) {
  34033. return false;
  34034. }
  34035. return vb.isUpdatable();
  34036. };
  34037. /**
  34038. * Gets a specific vertex buffer
  34039. * @param kind defines the data kind (Position, normal, etc...)
  34040. * @returns a {BABYLON.VertexBuffer}
  34041. */
  34042. Geometry.prototype.getVertexBuffer = function (kind) {
  34043. if (!this.isReady()) {
  34044. return null;
  34045. }
  34046. return this._vertexBuffers[kind];
  34047. };
  34048. /**
  34049. * Returns all vertex buffers
  34050. * @return an object holding all vertex buffers indexed by kind
  34051. */
  34052. Geometry.prototype.getVertexBuffers = function () {
  34053. if (!this.isReady()) {
  34054. return null;
  34055. }
  34056. return this._vertexBuffers;
  34057. };
  34058. /**
  34059. * Gets a boolean indicating if specific vertex buffer is present
  34060. * @param kind defines the data kind (Position, normal, etc...)
  34061. * @returns true if data is present
  34062. */
  34063. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34064. if (!this._vertexBuffers) {
  34065. if (this._delayInfo) {
  34066. return this._delayInfo.indexOf(kind) !== -1;
  34067. }
  34068. return false;
  34069. }
  34070. return this._vertexBuffers[kind] !== undefined;
  34071. };
  34072. /**
  34073. * Gets a list of all attached data kinds (Position, normal, etc...)
  34074. * @returns a list of string containing all kinds
  34075. */
  34076. Geometry.prototype.getVerticesDataKinds = function () {
  34077. var result = [];
  34078. var kind;
  34079. if (!this._vertexBuffers && this._delayInfo) {
  34080. for (kind in this._delayInfo) {
  34081. result.push(kind);
  34082. }
  34083. }
  34084. else {
  34085. for (kind in this._vertexBuffers) {
  34086. result.push(kind);
  34087. }
  34088. }
  34089. return result;
  34090. };
  34091. /**
  34092. * Update index buffer
  34093. * @param indices defines the indices to store in the index buffer
  34094. * @param offset defines the offset in the target buffer where to store the data
  34095. */
  34096. Geometry.prototype.updateIndices = function (indices, offset) {
  34097. if (!this._indexBuffer) {
  34098. return;
  34099. }
  34100. if (!this._indexBufferIsUpdatable) {
  34101. this.setIndices(indices, null, true);
  34102. }
  34103. else {
  34104. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34105. }
  34106. };
  34107. /**
  34108. * Creates a new index buffer
  34109. * @param indices defines the indices to store in the index buffer
  34110. * @param totalVertices defines the total number of vertices (could be null)
  34111. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34112. */
  34113. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34114. if (totalVertices === void 0) { totalVertices = null; }
  34115. if (updatable === void 0) { updatable = false; }
  34116. if (this._indexBuffer) {
  34117. this._engine._releaseBuffer(this._indexBuffer);
  34118. }
  34119. this._disposeVertexArrayObjects();
  34120. this._indices = indices;
  34121. this._indexBufferIsUpdatable = updatable;
  34122. if (this._meshes.length !== 0 && this._indices) {
  34123. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34124. }
  34125. if (totalVertices != undefined) {
  34126. this._totalVertices = totalVertices;
  34127. }
  34128. var meshes = this._meshes;
  34129. var numOfMeshes = meshes.length;
  34130. for (var index = 0; index < numOfMeshes; index++) {
  34131. meshes[index]._createGlobalSubMesh(true);
  34132. }
  34133. this.notifyUpdate();
  34134. };
  34135. /**
  34136. * Return the total number of indices
  34137. * @returns the total number of indices
  34138. */
  34139. Geometry.prototype.getTotalIndices = function () {
  34140. if (!this.isReady()) {
  34141. return 0;
  34142. }
  34143. return this._indices.length;
  34144. };
  34145. /**
  34146. * Gets the index buffer array
  34147. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34148. * @returns the index buffer array
  34149. */
  34150. Geometry.prototype.getIndices = function (copyWhenShared) {
  34151. if (!this.isReady()) {
  34152. return null;
  34153. }
  34154. var orig = this._indices;
  34155. if (!copyWhenShared || this._meshes.length === 1) {
  34156. return orig;
  34157. }
  34158. else {
  34159. var len = orig.length;
  34160. var copy = [];
  34161. for (var i = 0; i < len; i++) {
  34162. copy.push(orig[i]);
  34163. }
  34164. return copy;
  34165. }
  34166. };
  34167. /**
  34168. * Gets the index buffer
  34169. * @return the index buffer
  34170. */
  34171. Geometry.prototype.getIndexBuffer = function () {
  34172. if (!this.isReady()) {
  34173. return null;
  34174. }
  34175. return this._indexBuffer;
  34176. };
  34177. /** @ignore */
  34178. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34179. if (effect === void 0) { effect = null; }
  34180. if (!effect || !this._vertexArrayObjects) {
  34181. return;
  34182. }
  34183. if (this._vertexArrayObjects[effect.key]) {
  34184. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34185. delete this._vertexArrayObjects[effect.key];
  34186. }
  34187. };
  34188. /**
  34189. * Release the associated resources for a specific mesh
  34190. * @param mesh defines the source mesh
  34191. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34192. */
  34193. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34194. var meshes = this._meshes;
  34195. var index = meshes.indexOf(mesh);
  34196. if (index === -1) {
  34197. return;
  34198. }
  34199. meshes.splice(index, 1);
  34200. mesh._geometry = null;
  34201. if (meshes.length === 0 && shouldDispose) {
  34202. this.dispose();
  34203. }
  34204. };
  34205. /**
  34206. * Apply current geometry to a given mesh
  34207. * @param mesh defines the mesh to apply geometry to
  34208. */
  34209. Geometry.prototype.applyToMesh = function (mesh) {
  34210. if (mesh._geometry === this) {
  34211. return;
  34212. }
  34213. var previousGeometry = mesh._geometry;
  34214. if (previousGeometry) {
  34215. previousGeometry.releaseForMesh(mesh);
  34216. }
  34217. var meshes = this._meshes;
  34218. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34219. mesh._geometry = this;
  34220. this._scene.pushGeometry(this);
  34221. meshes.push(mesh);
  34222. if (this.isReady()) {
  34223. this._applyToMesh(mesh);
  34224. }
  34225. else {
  34226. mesh._boundingInfo = this._boundingInfo;
  34227. }
  34228. };
  34229. Geometry.prototype.updateExtend = function (data, stride) {
  34230. if (data === void 0) { data = null; }
  34231. if (!data) {
  34232. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34233. }
  34234. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34235. };
  34236. Geometry.prototype._applyToMesh = function (mesh) {
  34237. var numOfMeshes = this._meshes.length;
  34238. // vertexBuffers
  34239. for (var kind in this._vertexBuffers) {
  34240. if (numOfMeshes === 1) {
  34241. this._vertexBuffers[kind].create();
  34242. }
  34243. var buffer = this._vertexBuffers[kind].getBuffer();
  34244. if (buffer)
  34245. buffer.references = numOfMeshes;
  34246. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34247. if (!this._extend) {
  34248. this.updateExtend(this._vertexBuffers[kind].getData());
  34249. }
  34250. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34251. mesh._createGlobalSubMesh(false);
  34252. //bounding info was just created again, world matrix should be applied again.
  34253. mesh._updateBoundingInfo();
  34254. }
  34255. }
  34256. // indexBuffer
  34257. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34258. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34259. }
  34260. if (this._indexBuffer) {
  34261. this._indexBuffer.references = numOfMeshes;
  34262. }
  34263. };
  34264. Geometry.prototype.notifyUpdate = function (kind) {
  34265. if (this.onGeometryUpdated) {
  34266. this.onGeometryUpdated(this, kind);
  34267. }
  34268. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34269. var mesh = _a[_i];
  34270. mesh._markSubMeshesAsAttributesDirty();
  34271. }
  34272. };
  34273. /**
  34274. * Load the geometry if it was flagged as delay loaded
  34275. * @param scene defines the hosting scene
  34276. * @param onLoaded defines a callback called when the geometry is loaded
  34277. */
  34278. Geometry.prototype.load = function (scene, onLoaded) {
  34279. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34280. return;
  34281. }
  34282. if (this.isReady()) {
  34283. if (onLoaded) {
  34284. onLoaded();
  34285. }
  34286. return;
  34287. }
  34288. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34289. this._queueLoad(scene, onLoaded);
  34290. };
  34291. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34292. var _this = this;
  34293. if (!this.delayLoadingFile) {
  34294. return;
  34295. }
  34296. scene._addPendingData(this);
  34297. scene._loadFile(this.delayLoadingFile, function (data) {
  34298. if (!_this._delayLoadingFunction) {
  34299. return;
  34300. }
  34301. _this._delayLoadingFunction(JSON.parse(data), _this);
  34302. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34303. _this._delayInfo = [];
  34304. scene._removePendingData(_this);
  34305. var meshes = _this._meshes;
  34306. var numOfMeshes = meshes.length;
  34307. for (var index = 0; index < numOfMeshes; index++) {
  34308. _this._applyToMesh(meshes[index]);
  34309. }
  34310. if (onLoaded) {
  34311. onLoaded();
  34312. }
  34313. }, undefined, true);
  34314. };
  34315. /**
  34316. * Invert the geometry to move from a right handed system to a left handed one.
  34317. */
  34318. Geometry.prototype.toLeftHanded = function () {
  34319. // Flip faces
  34320. var tIndices = this.getIndices(false);
  34321. if (tIndices != null && tIndices.length > 0) {
  34322. for (var i = 0; i < tIndices.length; i += 3) {
  34323. var tTemp = tIndices[i + 0];
  34324. tIndices[i + 0] = tIndices[i + 2];
  34325. tIndices[i + 2] = tTemp;
  34326. }
  34327. this.setIndices(tIndices);
  34328. }
  34329. // Negate position.z
  34330. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34331. if (tPositions != null && tPositions.length > 0) {
  34332. for (var i = 0; i < tPositions.length; i += 3) {
  34333. tPositions[i + 2] = -tPositions[i + 2];
  34334. }
  34335. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34336. }
  34337. // Negate normal.z
  34338. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34339. if (tNormals != null && tNormals.length > 0) {
  34340. for (var i = 0; i < tNormals.length; i += 3) {
  34341. tNormals[i + 2] = -tNormals[i + 2];
  34342. }
  34343. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34344. }
  34345. };
  34346. // Cache
  34347. /** @ignore */
  34348. Geometry.prototype._resetPointsArrayCache = function () {
  34349. this._positions = null;
  34350. };
  34351. /** @ignore */
  34352. Geometry.prototype._generatePointsArray = function () {
  34353. if (this._positions)
  34354. return true;
  34355. this._positions = [];
  34356. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34357. if (!data) {
  34358. return false;
  34359. }
  34360. for (var index = 0; index < data.length; index += 3) {
  34361. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34362. }
  34363. return true;
  34364. };
  34365. /**
  34366. * Gets a value indicating if the geometry is disposed
  34367. * @returns true if the geometry was disposed
  34368. */
  34369. Geometry.prototype.isDisposed = function () {
  34370. return this._isDisposed;
  34371. };
  34372. Geometry.prototype._disposeVertexArrayObjects = function () {
  34373. if (this._vertexArrayObjects) {
  34374. for (var kind in this._vertexArrayObjects) {
  34375. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34376. }
  34377. this._vertexArrayObjects = {};
  34378. }
  34379. };
  34380. /**
  34381. * Free all associated resources
  34382. */
  34383. Geometry.prototype.dispose = function () {
  34384. var meshes = this._meshes;
  34385. var numOfMeshes = meshes.length;
  34386. var index;
  34387. for (index = 0; index < numOfMeshes; index++) {
  34388. this.releaseForMesh(meshes[index]);
  34389. }
  34390. this._meshes = [];
  34391. this._disposeVertexArrayObjects();
  34392. for (var kind in this._vertexBuffers) {
  34393. this._vertexBuffers[kind].dispose();
  34394. }
  34395. this._vertexBuffers = {};
  34396. this._totalVertices = 0;
  34397. if (this._indexBuffer) {
  34398. this._engine._releaseBuffer(this._indexBuffer);
  34399. }
  34400. this._indexBuffer = null;
  34401. this._indices = [];
  34402. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34403. this.delayLoadingFile = null;
  34404. this._delayLoadingFunction = null;
  34405. this._delayInfo = [];
  34406. this._boundingInfo = null;
  34407. this._scene.removeGeometry(this);
  34408. this._isDisposed = true;
  34409. };
  34410. /**
  34411. * Clone the current geometry into a new geometry
  34412. * @param id defines the unique ID of the new geometry
  34413. * @returns a new geometry object
  34414. */
  34415. Geometry.prototype.copy = function (id) {
  34416. var vertexData = new BABYLON.VertexData();
  34417. vertexData.indices = [];
  34418. var indices = this.getIndices();
  34419. if (indices) {
  34420. for (var index = 0; index < indices.length; index++) {
  34421. vertexData.indices.push(indices[index]);
  34422. }
  34423. }
  34424. var updatable = false;
  34425. var stopChecking = false;
  34426. var kind;
  34427. for (kind in this._vertexBuffers) {
  34428. // using slice() to make a copy of the array and not just reference it
  34429. var data = this.getVerticesData(kind);
  34430. if (data instanceof Float32Array) {
  34431. vertexData.set(new Float32Array(data), kind);
  34432. }
  34433. else {
  34434. vertexData.set(data.slice(0), kind);
  34435. }
  34436. if (!stopChecking) {
  34437. var vb = this.getVertexBuffer(kind);
  34438. if (vb) {
  34439. updatable = vb.isUpdatable();
  34440. stopChecking = !updatable;
  34441. }
  34442. }
  34443. }
  34444. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34445. geometry.delayLoadState = this.delayLoadState;
  34446. geometry.delayLoadingFile = this.delayLoadingFile;
  34447. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34448. for (kind in this._delayInfo) {
  34449. geometry._delayInfo = geometry._delayInfo || [];
  34450. geometry._delayInfo.push(kind);
  34451. }
  34452. // Bounding info
  34453. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34454. return geometry;
  34455. };
  34456. /**
  34457. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34458. * @return a JSON representation of the current geometry data (without the vertices data)
  34459. */
  34460. Geometry.prototype.serialize = function () {
  34461. var serializationObject = {};
  34462. serializationObject.id = this.id;
  34463. serializationObject.updatable = this._updatable;
  34464. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34465. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34466. }
  34467. return serializationObject;
  34468. };
  34469. Geometry.prototype.toNumberArray = function (origin) {
  34470. if (Array.isArray(origin)) {
  34471. return origin;
  34472. }
  34473. else {
  34474. return Array.prototype.slice.call(origin);
  34475. }
  34476. };
  34477. /**
  34478. * Serialize all vertices data into a JSON oject
  34479. * @returns a JSON representation of the current geometry data
  34480. */
  34481. Geometry.prototype.serializeVerticeData = function () {
  34482. var serializationObject = this.serialize();
  34483. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34484. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34485. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34486. serializationObject.positions._updatable = true;
  34487. }
  34488. }
  34489. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34490. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34491. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34492. serializationObject.normals._updatable = true;
  34493. }
  34494. }
  34495. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34496. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34497. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34498. serializationObject.tangets._updatable = true;
  34499. }
  34500. }
  34501. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34502. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34503. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34504. serializationObject.uvs._updatable = true;
  34505. }
  34506. }
  34507. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34508. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34509. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34510. serializationObject.uv2s._updatable = true;
  34511. }
  34512. }
  34513. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34514. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34515. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34516. serializationObject.uv3s._updatable = true;
  34517. }
  34518. }
  34519. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34520. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34521. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34522. serializationObject.uv4s._updatable = true;
  34523. }
  34524. }
  34525. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34526. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34527. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34528. serializationObject.uv5s._updatable = true;
  34529. }
  34530. }
  34531. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34532. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34533. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34534. serializationObject.uv6s._updatable = true;
  34535. }
  34536. }
  34537. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34538. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34539. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34540. serializationObject.colors._updatable = true;
  34541. }
  34542. }
  34543. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34544. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34545. serializationObject.matricesIndices._isExpanded = true;
  34546. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34547. serializationObject.matricesIndices._updatable = true;
  34548. }
  34549. }
  34550. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34551. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34552. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34553. serializationObject.matricesWeights._updatable = true;
  34554. }
  34555. }
  34556. serializationObject.indices = this.toNumberArray(this.getIndices());
  34557. return serializationObject;
  34558. };
  34559. // Statics
  34560. /**
  34561. * Extracts a clone of a mesh geometry
  34562. * @param mesh defines the source mesh
  34563. * @param id defines the unique ID of the new geometry object
  34564. * @returns the new geometry object
  34565. */
  34566. Geometry.ExtractFromMesh = function (mesh, id) {
  34567. var geometry = mesh._geometry;
  34568. if (!geometry) {
  34569. return null;
  34570. }
  34571. return geometry.copy(id);
  34572. };
  34573. /**
  34574. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34575. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34576. * Be aware Math.random() could cause collisions, but:
  34577. * "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"
  34578. * @returns a string containing a new GUID
  34579. */
  34580. Geometry.RandomId = function () {
  34581. return BABYLON.Tools.RandomId();
  34582. };
  34583. /** @ignore */
  34584. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34585. var scene = mesh.getScene();
  34586. // Geometry
  34587. var geometryId = parsedGeometry.geometryId;
  34588. if (geometryId) {
  34589. var geometry = scene.getGeometryByID(geometryId);
  34590. if (geometry) {
  34591. geometry.applyToMesh(mesh);
  34592. }
  34593. }
  34594. else if (parsedGeometry instanceof ArrayBuffer) {
  34595. var binaryInfo = mesh._binaryInfo;
  34596. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34597. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34598. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34599. }
  34600. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34601. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34602. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34603. }
  34604. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34605. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34606. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34607. }
  34608. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34609. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34610. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34611. }
  34612. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34613. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34614. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34615. }
  34616. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34617. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34618. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34619. }
  34620. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34621. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34622. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34623. }
  34624. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34625. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34626. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34627. }
  34628. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34629. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34630. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34631. }
  34632. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34633. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34634. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34635. }
  34636. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34637. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34639. }
  34640. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34641. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34642. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34643. }
  34644. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34645. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34646. mesh.setIndices(indicesData, null);
  34647. }
  34648. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34649. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34650. mesh.subMeshes = [];
  34651. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34652. var materialIndex = subMeshesData[(i * 5) + 0];
  34653. var verticesStart = subMeshesData[(i * 5) + 1];
  34654. var verticesCount = subMeshesData[(i * 5) + 2];
  34655. var indexStart = subMeshesData[(i * 5) + 3];
  34656. var indexCount = subMeshesData[(i * 5) + 4];
  34657. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34658. }
  34659. }
  34660. }
  34661. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34662. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34663. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34664. if (parsedGeometry.tangents) {
  34665. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34666. }
  34667. if (parsedGeometry.uvs) {
  34668. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34669. }
  34670. if (parsedGeometry.uvs2) {
  34671. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34672. }
  34673. if (parsedGeometry.uvs3) {
  34674. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34675. }
  34676. if (parsedGeometry.uvs4) {
  34677. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34678. }
  34679. if (parsedGeometry.uvs5) {
  34680. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34681. }
  34682. if (parsedGeometry.uvs6) {
  34683. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34684. }
  34685. if (parsedGeometry.colors) {
  34686. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34687. }
  34688. if (parsedGeometry.matricesIndices) {
  34689. if (!parsedGeometry.matricesIndices._isExpanded) {
  34690. var floatIndices = [];
  34691. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34692. var matricesIndex = parsedGeometry.matricesIndices[i];
  34693. floatIndices.push(matricesIndex & 0x000000FF);
  34694. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34695. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34696. floatIndices.push(matricesIndex >> 24);
  34697. }
  34698. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34699. }
  34700. else {
  34701. delete parsedGeometry.matricesIndices._isExpanded;
  34702. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34703. }
  34704. }
  34705. if (parsedGeometry.matricesIndicesExtra) {
  34706. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34707. var floatIndices = [];
  34708. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34709. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34710. floatIndices.push(matricesIndex & 0x000000FF);
  34711. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34712. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34713. floatIndices.push(matricesIndex >> 24);
  34714. }
  34715. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  34716. }
  34717. else {
  34718. delete parsedGeometry.matricesIndices._isExpanded;
  34719. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  34720. }
  34721. }
  34722. if (parsedGeometry.matricesWeights) {
  34723. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  34724. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  34725. }
  34726. if (parsedGeometry.matricesWeightsExtra) {
  34727. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  34728. }
  34729. mesh.setIndices(parsedGeometry.indices, null);
  34730. }
  34731. // SubMeshes
  34732. if (parsedGeometry.subMeshes) {
  34733. mesh.subMeshes = [];
  34734. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34735. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34736. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34737. }
  34738. }
  34739. // Flat shading
  34740. if (mesh._shouldGenerateFlatShading) {
  34741. mesh.convertToFlatShadedMesh();
  34742. delete mesh._shouldGenerateFlatShading;
  34743. }
  34744. // Update
  34745. mesh.computeWorldMatrix(true);
  34746. // Octree
  34747. var sceneOctree = scene.selectionOctree;
  34748. if (sceneOctree !== undefined && sceneOctree !== null) {
  34749. sceneOctree.addMesh(mesh);
  34750. }
  34751. };
  34752. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  34753. var epsilon = 1e-3;
  34754. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  34755. return;
  34756. }
  34757. var noInfluenceBoneIndex = 0.0;
  34758. if (parsedGeometry.skeletonId > -1) {
  34759. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  34760. if (!skeleton) {
  34761. return;
  34762. }
  34763. noInfluenceBoneIndex = skeleton.bones.length;
  34764. }
  34765. else {
  34766. return;
  34767. }
  34768. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34769. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34770. var matricesWeights = parsedGeometry.matricesWeights;
  34771. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  34772. var influencers = parsedGeometry.numBoneInfluencer;
  34773. var size = matricesWeights.length;
  34774. for (var i = 0; i < size; i += 4) {
  34775. var weight = 0.0;
  34776. var firstZeroWeight = -1;
  34777. for (var j = 0; j < 4; j++) {
  34778. var w = matricesWeights[i + j];
  34779. weight += w;
  34780. if (w < epsilon && firstZeroWeight < 0) {
  34781. firstZeroWeight = j;
  34782. }
  34783. }
  34784. if (matricesWeightsExtra) {
  34785. for (var j = 0; j < 4; j++) {
  34786. var w = matricesWeightsExtra[i + j];
  34787. weight += w;
  34788. if (w < epsilon && firstZeroWeight < 0) {
  34789. firstZeroWeight = j + 4;
  34790. }
  34791. }
  34792. }
  34793. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  34794. firstZeroWeight = influencers - 1;
  34795. }
  34796. if (weight > epsilon) {
  34797. var mweight = 1.0 / weight;
  34798. for (var j = 0; j < 4; j++) {
  34799. matricesWeights[i + j] *= mweight;
  34800. }
  34801. if (matricesWeightsExtra) {
  34802. for (var j = 0; j < 4; j++) {
  34803. matricesWeightsExtra[i + j] *= mweight;
  34804. }
  34805. }
  34806. }
  34807. else {
  34808. if (firstZeroWeight >= 4) {
  34809. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  34810. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  34811. }
  34812. else {
  34813. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  34814. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  34815. }
  34816. }
  34817. }
  34818. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  34819. if (parsedGeometry.matricesWeightsExtra) {
  34820. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  34821. }
  34822. };
  34823. /**
  34824. * Create a new geometry from persisted data (Using .babylon file format)
  34825. * @param parsedVertexData defines the persisted data
  34826. * @param scene defines the hosting scene
  34827. * @param rootUrl defines the root url to use to load assets (like delayed data)
  34828. * @returns the new geometry object
  34829. */
  34830. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34831. if (scene.getGeometryByID(parsedVertexData.id)) {
  34832. return null; // null since geometry could be something else than a box...
  34833. }
  34834. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  34835. if (BABYLON.Tags) {
  34836. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34837. }
  34838. if (parsedVertexData.delayLoadingFile) {
  34839. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34840. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34841. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34842. geometry._delayInfo = [];
  34843. if (parsedVertexData.hasUVs) {
  34844. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34845. }
  34846. if (parsedVertexData.hasUVs2) {
  34847. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34848. }
  34849. if (parsedVertexData.hasUVs3) {
  34850. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34851. }
  34852. if (parsedVertexData.hasUVs4) {
  34853. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34854. }
  34855. if (parsedVertexData.hasUVs5) {
  34856. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34857. }
  34858. if (parsedVertexData.hasUVs6) {
  34859. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34860. }
  34861. if (parsedVertexData.hasColors) {
  34862. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34863. }
  34864. if (parsedVertexData.hasMatricesIndices) {
  34865. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34866. }
  34867. if (parsedVertexData.hasMatricesWeights) {
  34868. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34869. }
  34870. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34871. }
  34872. else {
  34873. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34874. }
  34875. scene.pushGeometry(geometry, true);
  34876. return geometry;
  34877. };
  34878. return Geometry;
  34879. }());
  34880. BABYLON.Geometry = Geometry;
  34881. // Primitives
  34882. /// Abstract class
  34883. /**
  34884. * Abstract class used to provide common services for all typed geometries
  34885. */
  34886. var _PrimitiveGeometry = /** @class */ (function (_super) {
  34887. __extends(_PrimitiveGeometry, _super);
  34888. /**
  34889. * Creates a new typed geometry
  34890. * @param id defines the unique ID of the geometry
  34891. * @param scene defines the hosting scene
  34892. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34893. * @param mesh defines the hosting mesh (can be null)
  34894. */
  34895. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  34896. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  34897. if (mesh === void 0) { mesh = null; }
  34898. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  34899. _this._canBeRegenerated = _canBeRegenerated;
  34900. _this._beingRegenerated = true;
  34901. _this.regenerate();
  34902. _this._beingRegenerated = false;
  34903. return _this;
  34904. }
  34905. /**
  34906. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  34907. * @returns true if the geometry can be regenerated
  34908. */
  34909. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  34910. return this._canBeRegenerated;
  34911. };
  34912. /**
  34913. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  34914. */
  34915. _PrimitiveGeometry.prototype.regenerate = function () {
  34916. if (!this._canBeRegenerated) {
  34917. return;
  34918. }
  34919. this._beingRegenerated = true;
  34920. this.setAllVerticesData(this._regenerateVertexData(), false);
  34921. this._beingRegenerated = false;
  34922. };
  34923. /**
  34924. * Clone the geometry
  34925. * @param id defines the unique ID of the new geometry
  34926. * @returns the new geometry
  34927. */
  34928. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  34929. return _super.prototype.copy.call(this, id);
  34930. };
  34931. // overrides
  34932. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34933. if (!this._beingRegenerated) {
  34934. return;
  34935. }
  34936. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34937. };
  34938. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  34939. if (!this._beingRegenerated) {
  34940. return;
  34941. }
  34942. _super.prototype.setVerticesData.call(this, kind, data, false);
  34943. };
  34944. // to override
  34945. /** @ignore */
  34946. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  34947. throw new Error("Abstract method");
  34948. };
  34949. _PrimitiveGeometry.prototype.copy = function (id) {
  34950. throw new Error("Must be overriden in sub-classes.");
  34951. };
  34952. _PrimitiveGeometry.prototype.serialize = function () {
  34953. var serializationObject = _super.prototype.serialize.call(this);
  34954. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34955. return serializationObject;
  34956. };
  34957. return _PrimitiveGeometry;
  34958. }(Geometry));
  34959. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  34960. /**
  34961. * Creates a ribbon geometry
  34962. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  34963. */
  34964. var RibbonGeometry = /** @class */ (function (_super) {
  34965. __extends(RibbonGeometry, _super);
  34966. /**
  34967. * Creates a ribbon geometry
  34968. * @param id defines the unique ID of the geometry
  34969. * @param scene defines the hosting scene
  34970. * @param pathArray defines the array of paths to use
  34971. * @param closeArray defines if the last path and the first path must be joined
  34972. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  34973. * @param offset defines the offset between points
  34974. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34975. * @param mesh defines the hosting mesh (can be null)
  34976. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34977. */
  34978. function RibbonGeometry(id, scene,
  34979. /**
  34980. * Defines the array of paths to use
  34981. */
  34982. pathArray,
  34983. /**
  34984. * Defines if the last and first points of each path in your pathArray must be joined
  34985. */
  34986. closeArray,
  34987. /**
  34988. * Defines if the last and first points of each path in your pathArray must be joined
  34989. */
  34990. closePath,
  34991. /**
  34992. * Defines the offset between points
  34993. */
  34994. offset, canBeRegenerated, mesh,
  34995. /**
  34996. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34997. */
  34998. side) {
  34999. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35000. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35001. _this.pathArray = pathArray;
  35002. _this.closeArray = closeArray;
  35003. _this.closePath = closePath;
  35004. _this.offset = offset;
  35005. _this.side = side;
  35006. return _this;
  35007. }
  35008. /** @ignore */
  35009. RibbonGeometry.prototype._regenerateVertexData = function () {
  35010. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35011. };
  35012. RibbonGeometry.prototype.copy = function (id) {
  35013. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35014. };
  35015. return RibbonGeometry;
  35016. }(_PrimitiveGeometry));
  35017. BABYLON.RibbonGeometry = RibbonGeometry;
  35018. /**
  35019. * Creates a box geometry
  35020. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35021. */
  35022. var BoxGeometry = /** @class */ (function (_super) {
  35023. __extends(BoxGeometry, _super);
  35024. /**
  35025. * Creates a box geometry
  35026. * @param id defines the unique ID of the geometry
  35027. * @param scene defines the hosting scene
  35028. * @param size defines the zise of the box (width, height and depth are the same)
  35029. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35030. * @param mesh defines the hosting mesh (can be null)
  35031. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35032. */
  35033. function BoxGeometry(id, scene,
  35034. /**
  35035. * Defines the zise of the box (width, height and depth are the same)
  35036. */
  35037. size, canBeRegenerated, mesh,
  35038. /**
  35039. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35040. */
  35041. side) {
  35042. if (mesh === void 0) { mesh = null; }
  35043. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35044. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35045. _this.size = size;
  35046. _this.side = side;
  35047. return _this;
  35048. }
  35049. BoxGeometry.prototype._regenerateVertexData = function () {
  35050. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35051. };
  35052. BoxGeometry.prototype.copy = function (id) {
  35053. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35054. };
  35055. BoxGeometry.prototype.serialize = function () {
  35056. var serializationObject = _super.prototype.serialize.call(this);
  35057. serializationObject.size = this.size;
  35058. return serializationObject;
  35059. };
  35060. BoxGeometry.Parse = function (parsedBox, scene) {
  35061. if (scene.getGeometryByID(parsedBox.id)) {
  35062. return null; // null since geometry could be something else than a box...
  35063. }
  35064. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35065. if (BABYLON.Tags) {
  35066. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35067. }
  35068. scene.pushGeometry(box, true);
  35069. return box;
  35070. };
  35071. return BoxGeometry;
  35072. }(_PrimitiveGeometry));
  35073. BABYLON.BoxGeometry = BoxGeometry;
  35074. /**
  35075. * Creates a sphere geometry
  35076. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35077. */
  35078. var SphereGeometry = /** @class */ (function (_super) {
  35079. __extends(SphereGeometry, _super);
  35080. /**
  35081. * Create a new sphere geometry
  35082. * @param id defines the unique ID of the geometry
  35083. * @param scene defines the hosting scene
  35084. * @param segments defines the number of segments to use to create the sphere
  35085. * @param diameter defines the diameter of the sphere
  35086. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35087. * @param mesh defines the hosting mesh (can be null)
  35088. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35089. */
  35090. function SphereGeometry(id, scene,
  35091. /**
  35092. * Defines the number of segments to use to create the sphere
  35093. */
  35094. segments,
  35095. /**
  35096. * Defines the diameter of the sphere
  35097. */
  35098. diameter, canBeRegenerated, mesh,
  35099. /**
  35100. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35101. */
  35102. side) {
  35103. if (mesh === void 0) { mesh = null; }
  35104. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35105. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35106. _this.segments = segments;
  35107. _this.diameter = diameter;
  35108. _this.side = side;
  35109. return _this;
  35110. }
  35111. SphereGeometry.prototype._regenerateVertexData = function () {
  35112. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35113. };
  35114. SphereGeometry.prototype.copy = function (id) {
  35115. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35116. };
  35117. SphereGeometry.prototype.serialize = function () {
  35118. var serializationObject = _super.prototype.serialize.call(this);
  35119. serializationObject.segments = this.segments;
  35120. serializationObject.diameter = this.diameter;
  35121. return serializationObject;
  35122. };
  35123. SphereGeometry.Parse = function (parsedSphere, scene) {
  35124. if (scene.getGeometryByID(parsedSphere.id)) {
  35125. return null; // null since geometry could be something else than a sphere...
  35126. }
  35127. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35128. if (BABYLON.Tags) {
  35129. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35130. }
  35131. scene.pushGeometry(sphere, true);
  35132. return sphere;
  35133. };
  35134. return SphereGeometry;
  35135. }(_PrimitiveGeometry));
  35136. BABYLON.SphereGeometry = SphereGeometry;
  35137. /**
  35138. * Creates a disc geometry
  35139. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35140. */
  35141. var DiscGeometry = /** @class */ (function (_super) {
  35142. __extends(DiscGeometry, _super);
  35143. /**
  35144. * Creates a new disc geometry
  35145. * @param id defines the unique ID of the geometry
  35146. * @param scene defines the hosting scene
  35147. * @param radius defines the radius of the disc
  35148. * @param tessellation defines the tesselation factor to apply to the disc
  35149. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35150. * @param mesh defines the hosting mesh (can be null)
  35151. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35152. */
  35153. function DiscGeometry(id, scene,
  35154. /**
  35155. * Defines the radius of the disc
  35156. */
  35157. radius,
  35158. /**
  35159. * Defines the tesselation factor to apply to the disc
  35160. */
  35161. tessellation, canBeRegenerated, mesh,
  35162. /**
  35163. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35164. */
  35165. side) {
  35166. if (mesh === void 0) { mesh = null; }
  35167. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35168. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35169. _this.radius = radius;
  35170. _this.tessellation = tessellation;
  35171. _this.side = side;
  35172. return _this;
  35173. }
  35174. DiscGeometry.prototype._regenerateVertexData = function () {
  35175. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35176. };
  35177. DiscGeometry.prototype.copy = function (id) {
  35178. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35179. };
  35180. return DiscGeometry;
  35181. }(_PrimitiveGeometry));
  35182. BABYLON.DiscGeometry = DiscGeometry;
  35183. /**
  35184. * Creates a new cylinder geometry
  35185. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35186. */
  35187. var CylinderGeometry = /** @class */ (function (_super) {
  35188. __extends(CylinderGeometry, _super);
  35189. /**
  35190. * Creates a new cylinder geometry
  35191. * @param id defines the unique ID of the geometry
  35192. * @param scene defines the hosting scene
  35193. * @param height defines the height of the cylinder
  35194. * @param diameterTop defines the diameter of the cylinder's top cap
  35195. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35196. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35197. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35198. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35199. * @param mesh defines the hosting mesh (can be null)
  35200. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35201. */
  35202. function CylinderGeometry(id, scene,
  35203. /**
  35204. * Defines the height of the cylinder
  35205. */
  35206. height,
  35207. /**
  35208. * Defines the diameter of the cylinder's top cap
  35209. */
  35210. diameterTop,
  35211. /**
  35212. * Defines the diameter of the cylinder's bottom cap
  35213. */
  35214. diameterBottom,
  35215. /**
  35216. * Defines the tessellation factor to apply to the cylinder
  35217. */
  35218. tessellation,
  35219. /**
  35220. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35221. */
  35222. subdivisions, canBeRegenerated, mesh,
  35223. /**
  35224. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35225. */
  35226. side) {
  35227. if (subdivisions === void 0) { subdivisions = 1; }
  35228. if (mesh === void 0) { mesh = null; }
  35229. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35230. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35231. _this.height = height;
  35232. _this.diameterTop = diameterTop;
  35233. _this.diameterBottom = diameterBottom;
  35234. _this.tessellation = tessellation;
  35235. _this.subdivisions = subdivisions;
  35236. _this.side = side;
  35237. return _this;
  35238. }
  35239. CylinderGeometry.prototype._regenerateVertexData = function () {
  35240. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35241. };
  35242. CylinderGeometry.prototype.copy = function (id) {
  35243. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35244. };
  35245. CylinderGeometry.prototype.serialize = function () {
  35246. var serializationObject = _super.prototype.serialize.call(this);
  35247. serializationObject.height = this.height;
  35248. serializationObject.diameterTop = this.diameterTop;
  35249. serializationObject.diameterBottom = this.diameterBottom;
  35250. serializationObject.tessellation = this.tessellation;
  35251. return serializationObject;
  35252. };
  35253. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35254. if (scene.getGeometryByID(parsedCylinder.id)) {
  35255. return null; // null since geometry could be something else than a cylinder...
  35256. }
  35257. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35258. if (BABYLON.Tags) {
  35259. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35260. }
  35261. scene.pushGeometry(cylinder, true);
  35262. return cylinder;
  35263. };
  35264. return CylinderGeometry;
  35265. }(_PrimitiveGeometry));
  35266. BABYLON.CylinderGeometry = CylinderGeometry;
  35267. /**
  35268. * Creates a new torus geometry
  35269. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35270. */
  35271. var TorusGeometry = /** @class */ (function (_super) {
  35272. __extends(TorusGeometry, _super);
  35273. /**
  35274. * Creates a new torus geometry
  35275. * @param id defines the unique ID of the geometry
  35276. * @param scene defines the hosting scene
  35277. * @param diameter defines the diameter of the torus
  35278. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35279. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35280. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35281. * @param mesh defines the hosting mesh (can be null)
  35282. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35283. */
  35284. function TorusGeometry(id, scene,
  35285. /**
  35286. * Defines the diameter of the torus
  35287. */
  35288. diameter,
  35289. /**
  35290. * Defines the thickness of the torus (ie. internal diameter)
  35291. */
  35292. thickness,
  35293. /**
  35294. * Defines the tesselation factor to apply to the torus
  35295. */
  35296. tessellation, canBeRegenerated, mesh,
  35297. /**
  35298. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35299. */
  35300. side) {
  35301. if (mesh === void 0) { mesh = null; }
  35302. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35303. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35304. _this.diameter = diameter;
  35305. _this.thickness = thickness;
  35306. _this.tessellation = tessellation;
  35307. _this.side = side;
  35308. return _this;
  35309. }
  35310. TorusGeometry.prototype._regenerateVertexData = function () {
  35311. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35312. };
  35313. TorusGeometry.prototype.copy = function (id) {
  35314. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35315. };
  35316. TorusGeometry.prototype.serialize = function () {
  35317. var serializationObject = _super.prototype.serialize.call(this);
  35318. serializationObject.diameter = this.diameter;
  35319. serializationObject.thickness = this.thickness;
  35320. serializationObject.tessellation = this.tessellation;
  35321. return serializationObject;
  35322. };
  35323. TorusGeometry.Parse = function (parsedTorus, scene) {
  35324. if (scene.getGeometryByID(parsedTorus.id)) {
  35325. return null; // null since geometry could be something else than a torus...
  35326. }
  35327. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35328. if (BABYLON.Tags) {
  35329. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35330. }
  35331. scene.pushGeometry(torus, true);
  35332. return torus;
  35333. };
  35334. return TorusGeometry;
  35335. }(_PrimitiveGeometry));
  35336. BABYLON.TorusGeometry = TorusGeometry;
  35337. /**
  35338. * Creates a new ground geometry
  35339. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35340. */
  35341. var GroundGeometry = /** @class */ (function (_super) {
  35342. __extends(GroundGeometry, _super);
  35343. /**
  35344. * Creates a new ground geometry
  35345. * @param id defines the unique ID of the geometry
  35346. * @param scene defines the hosting scene
  35347. * @param width defines the width of the ground
  35348. * @param height defines the height of the ground
  35349. * @param subdivisions defines the subdivisions to apply to the ground
  35350. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35351. * @param mesh defines the hosting mesh (can be null)
  35352. */
  35353. function GroundGeometry(id, scene,
  35354. /**
  35355. * Defines the width of the ground
  35356. */
  35357. width,
  35358. /**
  35359. * Defines the height of the ground
  35360. */
  35361. height,
  35362. /**
  35363. * Defines the subdivisions to apply to the ground
  35364. */
  35365. subdivisions, canBeRegenerated, mesh) {
  35366. if (mesh === void 0) { mesh = null; }
  35367. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35368. _this.width = width;
  35369. _this.height = height;
  35370. _this.subdivisions = subdivisions;
  35371. return _this;
  35372. }
  35373. GroundGeometry.prototype._regenerateVertexData = function () {
  35374. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35375. };
  35376. GroundGeometry.prototype.copy = function (id) {
  35377. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35378. };
  35379. GroundGeometry.prototype.serialize = function () {
  35380. var serializationObject = _super.prototype.serialize.call(this);
  35381. serializationObject.width = this.width;
  35382. serializationObject.height = this.height;
  35383. serializationObject.subdivisions = this.subdivisions;
  35384. return serializationObject;
  35385. };
  35386. GroundGeometry.Parse = function (parsedGround, scene) {
  35387. if (scene.getGeometryByID(parsedGround.id)) {
  35388. return null; // null since geometry could be something else than a ground...
  35389. }
  35390. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35391. if (BABYLON.Tags) {
  35392. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35393. }
  35394. scene.pushGeometry(ground, true);
  35395. return ground;
  35396. };
  35397. return GroundGeometry;
  35398. }(_PrimitiveGeometry));
  35399. BABYLON.GroundGeometry = GroundGeometry;
  35400. /**
  35401. * Creates a tiled ground geometry
  35402. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35403. */
  35404. var TiledGroundGeometry = /** @class */ (function (_super) {
  35405. __extends(TiledGroundGeometry, _super);
  35406. /**
  35407. * Creates a tiled ground geometry
  35408. * @param id defines the unique ID of the geometry
  35409. * @param scene defines the hosting scene
  35410. * @param xmin defines the minimum value on X axis
  35411. * @param zmin defines the minimum value on Z axis
  35412. * @param xmax defines the maximum value on X axis
  35413. * @param zmax defines the maximum value on Z axis
  35414. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35415. * @param precision defines the precision to use when computing the tiles
  35416. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35417. * @param mesh defines the hosting mesh (can be null)
  35418. */
  35419. function TiledGroundGeometry(id, scene,
  35420. /**
  35421. * Defines the minimum value on X axis
  35422. */
  35423. xmin,
  35424. /**
  35425. * Defines the minimum value on Z axis
  35426. */
  35427. zmin,
  35428. /**
  35429. * Defines the maximum value on X axis
  35430. */
  35431. xmax,
  35432. /**
  35433. * Defines the maximum value on Z axis
  35434. */
  35435. zmax,
  35436. /**
  35437. * Defines the subdivisions to apply to the ground
  35438. */
  35439. subdivisions,
  35440. /**
  35441. * Defines the precision to use when computing the tiles
  35442. */
  35443. precision, canBeRegenerated, mesh) {
  35444. if (mesh === void 0) { mesh = null; }
  35445. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35446. _this.xmin = xmin;
  35447. _this.zmin = zmin;
  35448. _this.xmax = xmax;
  35449. _this.zmax = zmax;
  35450. _this.subdivisions = subdivisions;
  35451. _this.precision = precision;
  35452. return _this;
  35453. }
  35454. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35455. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35456. };
  35457. TiledGroundGeometry.prototype.copy = function (id) {
  35458. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35459. };
  35460. return TiledGroundGeometry;
  35461. }(_PrimitiveGeometry));
  35462. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35463. /**
  35464. * Creates a plane geometry
  35465. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35466. */
  35467. var PlaneGeometry = /** @class */ (function (_super) {
  35468. __extends(PlaneGeometry, _super);
  35469. /**
  35470. * Creates a plane geometry
  35471. * @param id defines the unique ID of the geometry
  35472. * @param scene defines the hosting scene
  35473. * @param size defines the size of the plane (width === height)
  35474. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35475. * @param mesh defines the hosting mesh (can be null)
  35476. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35477. */
  35478. function PlaneGeometry(id, scene,
  35479. /**
  35480. * Defines the size of the plane (width === height)
  35481. */
  35482. size, canBeRegenerated, mesh,
  35483. /**
  35484. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35485. */
  35486. side) {
  35487. if (mesh === void 0) { mesh = null; }
  35488. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35489. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35490. _this.size = size;
  35491. _this.side = side;
  35492. return _this;
  35493. }
  35494. PlaneGeometry.prototype._regenerateVertexData = function () {
  35495. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35496. };
  35497. PlaneGeometry.prototype.copy = function (id) {
  35498. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35499. };
  35500. PlaneGeometry.prototype.serialize = function () {
  35501. var serializationObject = _super.prototype.serialize.call(this);
  35502. serializationObject.size = this.size;
  35503. return serializationObject;
  35504. };
  35505. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35506. if (scene.getGeometryByID(parsedPlane.id)) {
  35507. return null; // null since geometry could be something else than a ground...
  35508. }
  35509. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35510. if (BABYLON.Tags) {
  35511. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35512. }
  35513. scene.pushGeometry(plane, true);
  35514. return plane;
  35515. };
  35516. return PlaneGeometry;
  35517. }(_PrimitiveGeometry));
  35518. BABYLON.PlaneGeometry = PlaneGeometry;
  35519. /**
  35520. * Creates a torus knot geometry
  35521. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35522. */
  35523. var TorusKnotGeometry = /** @class */ (function (_super) {
  35524. __extends(TorusKnotGeometry, _super);
  35525. /**
  35526. * Creates a torus knot geometry
  35527. * @param id defines the unique ID of the geometry
  35528. * @param scene defines the hosting scene
  35529. * @param radius defines the radius of the torus knot
  35530. * @param tube defines the thickness of the torus knot tube
  35531. * @param radialSegments defines the number of radial segments
  35532. * @param tubularSegments defines the number of tubular segments
  35533. * @param p defines the first number of windings
  35534. * @param q defines the second number of windings
  35535. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35536. * @param mesh defines the hosting mesh (can be null)
  35537. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35538. */
  35539. function TorusKnotGeometry(id, scene,
  35540. /**
  35541. * Defines the radius of the torus knot
  35542. */
  35543. radius,
  35544. /**
  35545. * Defines the thickness of the torus knot tube
  35546. */
  35547. tube,
  35548. /**
  35549. * Defines the number of radial segments
  35550. */
  35551. radialSegments,
  35552. /**
  35553. * Defines the number of tubular segments
  35554. */
  35555. tubularSegments,
  35556. /**
  35557. * Defines the first number of windings
  35558. */
  35559. p,
  35560. /**
  35561. * Defines the second number of windings
  35562. */
  35563. q, canBeRegenerated, mesh,
  35564. /**
  35565. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35566. */
  35567. side) {
  35568. if (mesh === void 0) { mesh = null; }
  35569. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35570. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35571. _this.radius = radius;
  35572. _this.tube = tube;
  35573. _this.radialSegments = radialSegments;
  35574. _this.tubularSegments = tubularSegments;
  35575. _this.p = p;
  35576. _this.q = q;
  35577. _this.side = side;
  35578. return _this;
  35579. }
  35580. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35581. 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 });
  35582. };
  35583. TorusKnotGeometry.prototype.copy = function (id) {
  35584. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35585. };
  35586. TorusKnotGeometry.prototype.serialize = function () {
  35587. var serializationObject = _super.prototype.serialize.call(this);
  35588. serializationObject.radius = this.radius;
  35589. serializationObject.tube = this.tube;
  35590. serializationObject.radialSegments = this.radialSegments;
  35591. serializationObject.tubularSegments = this.tubularSegments;
  35592. serializationObject.p = this.p;
  35593. serializationObject.q = this.q;
  35594. return serializationObject;
  35595. };
  35596. ;
  35597. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35598. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35599. return null; // null since geometry could be something else than a ground...
  35600. }
  35601. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35602. if (BABYLON.Tags) {
  35603. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35604. }
  35605. scene.pushGeometry(torusKnot, true);
  35606. return torusKnot;
  35607. };
  35608. return TorusKnotGeometry;
  35609. }(_PrimitiveGeometry));
  35610. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35611. //}
  35612. })(BABYLON || (BABYLON = {}));
  35613. //# sourceMappingURL=babylon.geometry.js.map
  35614. var BABYLON;
  35615. (function (BABYLON) {
  35616. /**
  35617. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35618. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35619. */
  35620. var PostProcessManager = /** @class */ (function () {
  35621. /**
  35622. * Creates a new instance of @see PostProcess
  35623. * @param scene The scene that the post process is associated with.
  35624. */
  35625. function PostProcessManager(scene) {
  35626. this._vertexBuffers = {};
  35627. this._scene = scene;
  35628. }
  35629. PostProcessManager.prototype._prepareBuffers = function () {
  35630. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35631. return;
  35632. }
  35633. // VBO
  35634. var vertices = [];
  35635. vertices.push(1, 1);
  35636. vertices.push(-1, 1);
  35637. vertices.push(-1, -1);
  35638. vertices.push(1, -1);
  35639. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35640. this._buildIndexBuffer();
  35641. };
  35642. PostProcessManager.prototype._buildIndexBuffer = function () {
  35643. // Indices
  35644. var indices = [];
  35645. indices.push(0);
  35646. indices.push(1);
  35647. indices.push(2);
  35648. indices.push(0);
  35649. indices.push(2);
  35650. indices.push(3);
  35651. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35652. };
  35653. /**
  35654. * Rebuilds the vertex buffers of the manager.
  35655. */
  35656. PostProcessManager.prototype._rebuild = function () {
  35657. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35658. if (!vb) {
  35659. return;
  35660. }
  35661. vb._rebuild();
  35662. this._buildIndexBuffer();
  35663. };
  35664. // Methods
  35665. /**
  35666. * Prepares a frame to be run through a post process.
  35667. * @param sourceTexture The input texture to the post procesess. (default: null)
  35668. * @param postProcesses An array of post processes to be run. (default: null)
  35669. * @returns True if the post processes were able to be run.
  35670. */
  35671. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35672. if (sourceTexture === void 0) { sourceTexture = null; }
  35673. if (postProcesses === void 0) { postProcesses = null; }
  35674. var camera = this._scene.activeCamera;
  35675. if (!camera) {
  35676. return false;
  35677. }
  35678. var postProcesses = postProcesses || camera._postProcesses;
  35679. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35680. return false;
  35681. }
  35682. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35683. return true;
  35684. };
  35685. /**
  35686. * Manually render a set of post processes to a texture.
  35687. * @param postProcesses An array of post processes to be run.
  35688. * @param targetTexture The target texture to render to.
  35689. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35690. */
  35691. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35692. if (targetTexture === void 0) { targetTexture = null; }
  35693. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35694. var engine = this._scene.getEngine();
  35695. for (var index = 0; index < postProcesses.length; index++) {
  35696. if (index < postProcesses.length - 1) {
  35697. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35698. }
  35699. else {
  35700. if (targetTexture) {
  35701. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35702. }
  35703. else {
  35704. engine.restoreDefaultFramebuffer();
  35705. }
  35706. }
  35707. var pp = postProcesses[index];
  35708. var effect = pp.apply();
  35709. if (effect) {
  35710. pp.onBeforeRenderObservable.notifyObservers(effect);
  35711. // VBOs
  35712. this._prepareBuffers();
  35713. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35714. // Draw order
  35715. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35716. pp.onAfterRenderObservable.notifyObservers(effect);
  35717. }
  35718. }
  35719. // Restore depth buffer
  35720. engine.setDepthBuffer(true);
  35721. engine.setDepthWrite(true);
  35722. };
  35723. /**
  35724. * Finalize the result of the output of the postprocesses.
  35725. * @param doNotPresent If true the result will not be displayed to the screen.
  35726. * @param targetTexture The target texture to render to.
  35727. * @param faceIndex The index of the face to bind the target texture to.
  35728. * @param postProcesses The array of post processes to render.
  35729. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  35730. */
  35731. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  35732. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35733. var camera = this._scene.activeCamera;
  35734. if (!camera) {
  35735. return;
  35736. }
  35737. postProcesses = postProcesses || camera._postProcesses;
  35738. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35739. return;
  35740. }
  35741. var engine = this._scene.getEngine();
  35742. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35743. if (index < len - 1) {
  35744. postProcesses[index + 1].activate(camera, targetTexture);
  35745. }
  35746. else {
  35747. if (targetTexture) {
  35748. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  35749. }
  35750. else {
  35751. engine.restoreDefaultFramebuffer();
  35752. }
  35753. }
  35754. if (doNotPresent) {
  35755. break;
  35756. }
  35757. var pp = postProcesses[index];
  35758. var effect = pp.apply();
  35759. if (effect) {
  35760. pp.onBeforeRenderObservable.notifyObservers(effect);
  35761. // VBOs
  35762. this._prepareBuffers();
  35763. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35764. // Draw order
  35765. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35766. pp.onAfterRenderObservable.notifyObservers(effect);
  35767. }
  35768. }
  35769. // Restore states
  35770. engine.setDepthBuffer(true);
  35771. engine.setDepthWrite(true);
  35772. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35773. };
  35774. /**
  35775. * Disposes of the post process manager.
  35776. */
  35777. PostProcessManager.prototype.dispose = function () {
  35778. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35779. if (buffer) {
  35780. buffer.dispose();
  35781. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35782. }
  35783. if (this._indexBuffer) {
  35784. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35785. this._indexBuffer = null;
  35786. }
  35787. };
  35788. return PostProcessManager;
  35789. }());
  35790. BABYLON.PostProcessManager = PostProcessManager;
  35791. })(BABYLON || (BABYLON = {}));
  35792. //# sourceMappingURL=babylon.postProcessManager.js.map
  35793. var BABYLON;
  35794. (function (BABYLON) {
  35795. /**
  35796. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  35797. */
  35798. var PerformanceMonitor = /** @class */ (function () {
  35799. /**
  35800. * constructor
  35801. * @param frameSampleSize The number of samples required to saturate the sliding window
  35802. */
  35803. function PerformanceMonitor(frameSampleSize) {
  35804. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  35805. this._enabled = true;
  35806. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  35807. }
  35808. /**
  35809. * Samples current frame
  35810. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  35811. */
  35812. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  35813. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  35814. if (!this._enabled)
  35815. return;
  35816. if (this._lastFrameTimeMs != null) {
  35817. var dt = timeMs - this._lastFrameTimeMs;
  35818. this._rollingFrameTime.add(dt);
  35819. }
  35820. this._lastFrameTimeMs = timeMs;
  35821. };
  35822. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  35823. /**
  35824. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  35825. * @return Average frame time in milliseconds
  35826. */
  35827. get: function () {
  35828. return this._rollingFrameTime.average;
  35829. },
  35830. enumerable: true,
  35831. configurable: true
  35832. });
  35833. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  35834. /**
  35835. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  35836. * @return Frame time variance in milliseconds squared
  35837. */
  35838. get: function () {
  35839. return this._rollingFrameTime.variance;
  35840. },
  35841. enumerable: true,
  35842. configurable: true
  35843. });
  35844. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  35845. /**
  35846. * Returns the frame time of the most recent frame
  35847. * @return Frame time in milliseconds
  35848. */
  35849. get: function () {
  35850. return this._rollingFrameTime.history(0);
  35851. },
  35852. enumerable: true,
  35853. configurable: true
  35854. });
  35855. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  35856. /**
  35857. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  35858. * @return Framerate in frames per second
  35859. */
  35860. get: function () {
  35861. return 1000.0 / this._rollingFrameTime.average;
  35862. },
  35863. enumerable: true,
  35864. configurable: true
  35865. });
  35866. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  35867. /**
  35868. * Returns the average framerate in frames per second using the most recent frame time
  35869. * @return Framerate in frames per second
  35870. */
  35871. get: function () {
  35872. var history = this._rollingFrameTime.history(0);
  35873. if (history === 0) {
  35874. return 0;
  35875. }
  35876. return 1000.0 / history;
  35877. },
  35878. enumerable: true,
  35879. configurable: true
  35880. });
  35881. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  35882. /**
  35883. * Returns true if enough samples have been taken to completely fill the sliding window
  35884. * @return true if saturated
  35885. */
  35886. get: function () {
  35887. return this._rollingFrameTime.isSaturated();
  35888. },
  35889. enumerable: true,
  35890. configurable: true
  35891. });
  35892. /**
  35893. * Enables contributions to the sliding window sample set
  35894. */
  35895. PerformanceMonitor.prototype.enable = function () {
  35896. this._enabled = true;
  35897. };
  35898. /**
  35899. * Disables contributions to the sliding window sample set
  35900. * Samples will not be interpolated over the disabled period
  35901. */
  35902. PerformanceMonitor.prototype.disable = function () {
  35903. this._enabled = false;
  35904. //clear last sample to avoid interpolating over the disabled period when next enabled
  35905. this._lastFrameTimeMs = null;
  35906. };
  35907. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  35908. /**
  35909. * Returns true if sampling is enabled
  35910. * @return true if enabled
  35911. */
  35912. get: function () {
  35913. return this._enabled;
  35914. },
  35915. enumerable: true,
  35916. configurable: true
  35917. });
  35918. /**
  35919. * Resets performance monitor
  35920. */
  35921. PerformanceMonitor.prototype.reset = function () {
  35922. //clear last sample to avoid interpolating over the disabled period when next enabled
  35923. this._lastFrameTimeMs = null;
  35924. //wipe record
  35925. this._rollingFrameTime.reset();
  35926. };
  35927. return PerformanceMonitor;
  35928. }());
  35929. BABYLON.PerformanceMonitor = PerformanceMonitor;
  35930. /**
  35931. * RollingAverage
  35932. *
  35933. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  35934. */
  35935. var RollingAverage = /** @class */ (function () {
  35936. /**
  35937. * constructor
  35938. * @param length The number of samples required to saturate the sliding window
  35939. */
  35940. function RollingAverage(length) {
  35941. this._samples = new Array(length);
  35942. this.reset();
  35943. }
  35944. /**
  35945. * Adds a sample to the sample set
  35946. * @param v The sample value
  35947. */
  35948. RollingAverage.prototype.add = function (v) {
  35949. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  35950. var delta;
  35951. //we need to check if we've already wrapped round
  35952. if (this.isSaturated()) {
  35953. //remove bottom of stack from mean
  35954. var bottomValue = this._samples[this._pos];
  35955. delta = bottomValue - this.average;
  35956. this.average -= delta / (this._sampleCount - 1);
  35957. this._m2 -= delta * (bottomValue - this.average);
  35958. }
  35959. else {
  35960. this._sampleCount++;
  35961. }
  35962. //add new value to mean
  35963. delta = v - this.average;
  35964. this.average += delta / (this._sampleCount);
  35965. this._m2 += delta * (v - this.average);
  35966. //set the new variance
  35967. this.variance = this._m2 / (this._sampleCount - 1);
  35968. this._samples[this._pos] = v;
  35969. this._pos++;
  35970. this._pos %= this._samples.length; //positive wrap around
  35971. };
  35972. /**
  35973. * Returns previously added values or null if outside of history or outside the sliding window domain
  35974. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  35975. * @return Value previously recorded with add() or null if outside of range
  35976. */
  35977. RollingAverage.prototype.history = function (i) {
  35978. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  35979. return 0;
  35980. }
  35981. var i0 = this._wrapPosition(this._pos - 1.0);
  35982. return this._samples[this._wrapPosition(i0 - i)];
  35983. };
  35984. /**
  35985. * Returns true if enough samples have been taken to completely fill the sliding window
  35986. * @return true if sample-set saturated
  35987. */
  35988. RollingAverage.prototype.isSaturated = function () {
  35989. return this._sampleCount >= this._samples.length;
  35990. };
  35991. /**
  35992. * Resets the rolling average (equivalent to 0 samples taken so far)
  35993. */
  35994. RollingAverage.prototype.reset = function () {
  35995. this.average = 0;
  35996. this.variance = 0;
  35997. this._sampleCount = 0;
  35998. this._pos = 0;
  35999. this._m2 = 0;
  36000. };
  36001. /**
  36002. * Wraps a value around the sample range boundaries
  36003. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36004. * @return Wrapped position in sample range
  36005. */
  36006. RollingAverage.prototype._wrapPosition = function (i) {
  36007. var max = this._samples.length;
  36008. return ((i % max) + max) % max;
  36009. };
  36010. return RollingAverage;
  36011. }());
  36012. BABYLON.RollingAverage = RollingAverage;
  36013. })(BABYLON || (BABYLON = {}));
  36014. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36015. var BABYLON;
  36016. (function (BABYLON) {
  36017. /**
  36018. * This groups together the common properties used for image processing either in direct forward pass
  36019. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36020. * or not.
  36021. */
  36022. var ImageProcessingConfiguration = /** @class */ (function () {
  36023. function ImageProcessingConfiguration() {
  36024. /**
  36025. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36026. */
  36027. this.colorCurves = new BABYLON.ColorCurves();
  36028. this._colorCurvesEnabled = false;
  36029. this._colorGradingEnabled = false;
  36030. this._colorGradingWithGreenDepth = true;
  36031. this._colorGradingBGR = true;
  36032. this._exposure = 1.0;
  36033. this._toneMappingEnabled = false;
  36034. this._contrast = 1.0;
  36035. /**
  36036. * Vignette stretch size.
  36037. */
  36038. this.vignetteStretch = 0;
  36039. /**
  36040. * Vignette centre X Offset.
  36041. */
  36042. this.vignetteCentreX = 0;
  36043. /**
  36044. * Vignette centre Y Offset.
  36045. */
  36046. this.vignetteCentreY = 0;
  36047. /**
  36048. * Vignette weight or intensity of the vignette effect.
  36049. */
  36050. this.vignetteWeight = 1.5;
  36051. /**
  36052. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36053. * if vignetteEnabled is set to true.
  36054. */
  36055. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36056. /**
  36057. * Camera field of view used by the Vignette effect.
  36058. */
  36059. this.vignetteCameraFov = 0.5;
  36060. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36061. this._vignetteEnabled = false;
  36062. this._applyByPostProcess = false;
  36063. this._isEnabled = true;
  36064. /**
  36065. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36066. * @type {BABYLON.Observable}
  36067. */
  36068. this.onUpdateParameters = new BABYLON.Observable();
  36069. }
  36070. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36071. /**
  36072. * Gets wether the color curves effect is enabled.
  36073. */
  36074. get: function () {
  36075. return this._colorCurvesEnabled;
  36076. },
  36077. /**
  36078. * Sets wether the color curves effect is enabled.
  36079. */
  36080. set: function (value) {
  36081. if (this._colorCurvesEnabled === value) {
  36082. return;
  36083. }
  36084. this._colorCurvesEnabled = value;
  36085. this._updateParameters();
  36086. },
  36087. enumerable: true,
  36088. configurable: true
  36089. });
  36090. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36091. /**
  36092. * Gets wether the color grading effect is enabled.
  36093. */
  36094. get: function () {
  36095. return this._colorGradingEnabled;
  36096. },
  36097. /**
  36098. * Sets wether the color grading effect is enabled.
  36099. */
  36100. set: function (value) {
  36101. if (this._colorGradingEnabled === value) {
  36102. return;
  36103. }
  36104. this._colorGradingEnabled = value;
  36105. this._updateParameters();
  36106. },
  36107. enumerable: true,
  36108. configurable: true
  36109. });
  36110. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36111. /**
  36112. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36113. */
  36114. get: function () {
  36115. return this._colorGradingWithGreenDepth;
  36116. },
  36117. /**
  36118. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36119. */
  36120. set: function (value) {
  36121. if (this._colorGradingWithGreenDepth === value) {
  36122. return;
  36123. }
  36124. this._colorGradingWithGreenDepth = value;
  36125. this._updateParameters();
  36126. },
  36127. enumerable: true,
  36128. configurable: true
  36129. });
  36130. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36131. /**
  36132. * Gets wether the color grading texture contains BGR values.
  36133. */
  36134. get: function () {
  36135. return this._colorGradingBGR;
  36136. },
  36137. /**
  36138. * Sets wether the color grading texture contains BGR values.
  36139. */
  36140. set: function (value) {
  36141. if (this._colorGradingBGR === value) {
  36142. return;
  36143. }
  36144. this._colorGradingBGR = value;
  36145. this._updateParameters();
  36146. },
  36147. enumerable: true,
  36148. configurable: true
  36149. });
  36150. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36151. /**
  36152. * Gets the Exposure used in the effect.
  36153. */
  36154. get: function () {
  36155. return this._exposure;
  36156. },
  36157. /**
  36158. * Sets the Exposure used in the effect.
  36159. */
  36160. set: function (value) {
  36161. if (this._exposure === value) {
  36162. return;
  36163. }
  36164. this._exposure = value;
  36165. this._updateParameters();
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36171. /**
  36172. * Gets wether the tone mapping effect is enabled.
  36173. */
  36174. get: function () {
  36175. return this._toneMappingEnabled;
  36176. },
  36177. /**
  36178. * Sets wether the tone mapping effect is enabled.
  36179. */
  36180. set: function (value) {
  36181. if (this._toneMappingEnabled === value) {
  36182. return;
  36183. }
  36184. this._toneMappingEnabled = value;
  36185. this._updateParameters();
  36186. },
  36187. enumerable: true,
  36188. configurable: true
  36189. });
  36190. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36191. /**
  36192. * Gets the contrast used in the effect.
  36193. */
  36194. get: function () {
  36195. return this._contrast;
  36196. },
  36197. /**
  36198. * Sets the contrast used in the effect.
  36199. */
  36200. set: function (value) {
  36201. if (this._contrast === value) {
  36202. return;
  36203. }
  36204. this._contrast = value;
  36205. this._updateParameters();
  36206. },
  36207. enumerable: true,
  36208. configurable: true
  36209. });
  36210. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36211. /**
  36212. * Gets the vignette blend mode allowing different kind of effect.
  36213. */
  36214. get: function () {
  36215. return this._vignetteBlendMode;
  36216. },
  36217. /**
  36218. * Sets the vignette blend mode allowing different kind of effect.
  36219. */
  36220. set: function (value) {
  36221. if (this._vignetteBlendMode === value) {
  36222. return;
  36223. }
  36224. this._vignetteBlendMode = value;
  36225. this._updateParameters();
  36226. },
  36227. enumerable: true,
  36228. configurable: true
  36229. });
  36230. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36231. /**
  36232. * Gets wether the vignette effect is enabled.
  36233. */
  36234. get: function () {
  36235. return this._vignetteEnabled;
  36236. },
  36237. /**
  36238. * Sets wether the vignette effect is enabled.
  36239. */
  36240. set: function (value) {
  36241. if (this._vignetteEnabled === value) {
  36242. return;
  36243. }
  36244. this._vignetteEnabled = value;
  36245. this._updateParameters();
  36246. },
  36247. enumerable: true,
  36248. configurable: true
  36249. });
  36250. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36251. /**
  36252. * Gets wether the image processing is applied through a post process or not.
  36253. */
  36254. get: function () {
  36255. return this._applyByPostProcess;
  36256. },
  36257. /**
  36258. * Sets wether the image processing is applied through a post process or not.
  36259. */
  36260. set: function (value) {
  36261. if (this._applyByPostProcess === value) {
  36262. return;
  36263. }
  36264. this._applyByPostProcess = value;
  36265. this._updateParameters();
  36266. },
  36267. enumerable: true,
  36268. configurable: true
  36269. });
  36270. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36271. /**
  36272. * Gets wether the image processing is enabled or not.
  36273. */
  36274. get: function () {
  36275. return this._isEnabled;
  36276. },
  36277. /**
  36278. * Sets wether the image processing is enabled or not.
  36279. */
  36280. set: function (value) {
  36281. if (this._isEnabled === value) {
  36282. return;
  36283. }
  36284. this._isEnabled = value;
  36285. this._updateParameters();
  36286. },
  36287. enumerable: true,
  36288. configurable: true
  36289. });
  36290. /**
  36291. * Method called each time the image processing information changes requires to recompile the effect.
  36292. */
  36293. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36294. this.onUpdateParameters.notifyObservers(this);
  36295. };
  36296. ImageProcessingConfiguration.prototype.getClassName = function () {
  36297. return "ImageProcessingConfiguration";
  36298. };
  36299. /**
  36300. * Prepare the list of uniforms associated with the Image Processing effects.
  36301. * @param uniformsList The list of uniforms used in the effect
  36302. * @param defines the list of defines currently in use
  36303. */
  36304. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36305. if (defines.EXPOSURE) {
  36306. uniforms.push("exposureLinear");
  36307. }
  36308. if (defines.CONTRAST) {
  36309. uniforms.push("contrast");
  36310. }
  36311. if (defines.COLORGRADING) {
  36312. uniforms.push("colorTransformSettings");
  36313. }
  36314. if (defines.VIGNETTE) {
  36315. uniforms.push("vInverseScreenSize");
  36316. uniforms.push("vignetteSettings1");
  36317. uniforms.push("vignetteSettings2");
  36318. }
  36319. if (defines.COLORCURVES) {
  36320. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36321. }
  36322. };
  36323. /**
  36324. * Prepare the list of samplers associated with the Image Processing effects.
  36325. * @param uniformsList The list of uniforms used in the effect
  36326. * @param defines the list of defines currently in use
  36327. */
  36328. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36329. if (defines.COLORGRADING) {
  36330. samplersList.push("txColorTransform");
  36331. }
  36332. };
  36333. /**
  36334. * Prepare the list of defines associated to the shader.
  36335. * @param defines the list of defines to complete
  36336. */
  36337. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36338. if (forPostProcess === void 0) { forPostProcess = false; }
  36339. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36340. defines.VIGNETTE = false;
  36341. defines.TONEMAPPING = false;
  36342. defines.CONTRAST = false;
  36343. defines.EXPOSURE = false;
  36344. defines.COLORCURVES = false;
  36345. defines.COLORGRADING = false;
  36346. defines.COLORGRADING3D = false;
  36347. defines.IMAGEPROCESSING = false;
  36348. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36349. return;
  36350. }
  36351. defines.VIGNETTE = this.vignetteEnabled;
  36352. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36353. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36354. defines.TONEMAPPING = this.toneMappingEnabled;
  36355. defines.CONTRAST = (this.contrast !== 1.0);
  36356. defines.EXPOSURE = (this.exposure !== 1.0);
  36357. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36358. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36359. if (defines.COLORGRADING) {
  36360. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36361. }
  36362. else {
  36363. defines.COLORGRADING3D = false;
  36364. }
  36365. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36366. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36367. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36368. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36369. };
  36370. /**
  36371. * Returns true if all the image processing information are ready.
  36372. */
  36373. ImageProcessingConfiguration.prototype.isReady = function () {
  36374. // Color Grading texure can not be none blocking.
  36375. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36376. };
  36377. /**
  36378. * Binds the image processing to the shader.
  36379. * @param effect The effect to bind to
  36380. */
  36381. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36382. if (aspectRatio === void 0) { aspectRatio = 1; }
  36383. // Color Curves
  36384. if (this._colorCurvesEnabled && this.colorCurves) {
  36385. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36386. }
  36387. // Vignette
  36388. if (this._vignetteEnabled) {
  36389. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36390. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36391. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36392. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36393. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36394. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36395. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36396. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36397. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36398. var vignettePower = -2.0 * this.vignetteWeight;
  36399. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36400. }
  36401. // Exposure
  36402. effect.setFloat("exposureLinear", this.exposure);
  36403. // Contrast
  36404. effect.setFloat("contrast", this.contrast);
  36405. // Color transform settings
  36406. if (this.colorGradingTexture) {
  36407. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36408. var textureSize = this.colorGradingTexture.getSize().height;
  36409. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36410. 0.5 / textureSize, // textureOffset
  36411. textureSize, // textureSize
  36412. this.colorGradingTexture.level // weight
  36413. );
  36414. }
  36415. };
  36416. /**
  36417. * Clones the current image processing instance.
  36418. * @return The cloned image processing
  36419. */
  36420. ImageProcessingConfiguration.prototype.clone = function () {
  36421. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36422. };
  36423. /**
  36424. * Serializes the current image processing instance to a json representation.
  36425. * @return a JSON representation
  36426. */
  36427. ImageProcessingConfiguration.prototype.serialize = function () {
  36428. return BABYLON.SerializationHelper.Serialize(this);
  36429. };
  36430. /**
  36431. * Parses the image processing from a json representation.
  36432. * @param source the JSON source to parse
  36433. * @return The parsed image processing
  36434. */
  36435. ImageProcessingConfiguration.Parse = function (source) {
  36436. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36437. };
  36438. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36439. /**
  36440. * Used to apply the vignette as a mix with the pixel color.
  36441. */
  36442. get: function () {
  36443. return this._VIGNETTEMODE_MULTIPLY;
  36444. },
  36445. enumerable: true,
  36446. configurable: true
  36447. });
  36448. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36449. /**
  36450. * Used to apply the vignette as a replacement of the pixel color.
  36451. */
  36452. get: function () {
  36453. return this._VIGNETTEMODE_OPAQUE;
  36454. },
  36455. enumerable: true,
  36456. configurable: true
  36457. });
  36458. // Static constants associated to the image processing.
  36459. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36460. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36461. __decorate([
  36462. BABYLON.serializeAsColorCurves()
  36463. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36464. __decorate([
  36465. BABYLON.serialize()
  36466. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36467. __decorate([
  36468. BABYLON.serializeAsTexture()
  36469. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36470. __decorate([
  36471. BABYLON.serialize()
  36472. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36473. __decorate([
  36474. BABYLON.serialize()
  36475. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36476. __decorate([
  36477. BABYLON.serialize()
  36478. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36479. __decorate([
  36480. BABYLON.serialize()
  36481. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36482. __decorate([
  36483. BABYLON.serialize()
  36484. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36485. __decorate([
  36486. BABYLON.serialize()
  36487. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36488. __decorate([
  36489. BABYLON.serialize()
  36490. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36491. __decorate([
  36492. BABYLON.serialize()
  36493. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36494. __decorate([
  36495. BABYLON.serialize()
  36496. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36497. __decorate([
  36498. BABYLON.serialize()
  36499. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36500. __decorate([
  36501. BABYLON.serializeAsColor4()
  36502. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36503. __decorate([
  36504. BABYLON.serialize()
  36505. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36506. __decorate([
  36507. BABYLON.serialize()
  36508. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36509. __decorate([
  36510. BABYLON.serialize()
  36511. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36512. __decorate([
  36513. BABYLON.serialize()
  36514. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36515. __decorate([
  36516. BABYLON.serialize()
  36517. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36518. return ImageProcessingConfiguration;
  36519. }());
  36520. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36521. })(BABYLON || (BABYLON = {}));
  36522. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36523. var BABYLON;
  36524. (function (BABYLON) {
  36525. /**
  36526. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36527. * It can help converting any input color in a desired output one. This can then be used to create effects
  36528. * from sepia, black and white to sixties or futuristic rendering...
  36529. *
  36530. * The only supported format is currently 3dl.
  36531. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36532. */
  36533. var ColorGradingTexture = /** @class */ (function (_super) {
  36534. __extends(ColorGradingTexture, _super);
  36535. /**
  36536. * Instantiates a ColorGradingTexture from the following parameters.
  36537. *
  36538. * @param url The location of the color gradind data (currently only supporting 3dl)
  36539. * @param scene The scene the texture will be used in
  36540. */
  36541. function ColorGradingTexture(url, scene) {
  36542. var _this = _super.call(this, scene) || this;
  36543. if (!url) {
  36544. return _this;
  36545. }
  36546. _this._engine = scene.getEngine();
  36547. _this._textureMatrix = BABYLON.Matrix.Identity();
  36548. _this.name = url;
  36549. _this.url = url;
  36550. _this.hasAlpha = false;
  36551. _this.isCube = false;
  36552. _this.is3D = _this._engine.webGLVersion > 1;
  36553. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36554. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36555. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36556. _this.anisotropicFilteringLevel = 1;
  36557. _this._texture = _this._getFromCache(url, true);
  36558. if (!_this._texture) {
  36559. if (!scene.useDelayedTextureLoading) {
  36560. _this.loadTexture();
  36561. }
  36562. else {
  36563. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36564. }
  36565. }
  36566. return _this;
  36567. }
  36568. /**
  36569. * Returns the texture matrix used in most of the material.
  36570. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36571. */
  36572. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36573. return this._textureMatrix;
  36574. };
  36575. /**
  36576. * Occurs when the file being loaded is a .3dl LUT file.
  36577. */
  36578. ColorGradingTexture.prototype.load3dlTexture = function () {
  36579. var engine = this._engine;
  36580. var texture;
  36581. if (engine.webGLVersion === 1) {
  36582. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36583. }
  36584. else {
  36585. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36586. }
  36587. this._texture = texture;
  36588. var callback = function (text) {
  36589. if (typeof text !== "string") {
  36590. return;
  36591. }
  36592. var data = null;
  36593. var tempData = null;
  36594. var line;
  36595. var lines = text.split('\n');
  36596. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36597. var maxColor = 0;
  36598. for (var i = 0; i < lines.length; i++) {
  36599. line = lines[i];
  36600. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36601. continue;
  36602. if (line.indexOf('#') === 0)
  36603. continue;
  36604. var words = line.split(" ");
  36605. if (size === 0) {
  36606. // Number of space + one
  36607. size = words.length;
  36608. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36609. tempData = new Float32Array(size * size * size * 4);
  36610. continue;
  36611. }
  36612. if (size != 0) {
  36613. var r = Math.max(parseInt(words[0]), 0);
  36614. var g = Math.max(parseInt(words[1]), 0);
  36615. var b = Math.max(parseInt(words[2]), 0);
  36616. maxColor = Math.max(r, maxColor);
  36617. maxColor = Math.max(g, maxColor);
  36618. maxColor = Math.max(b, maxColor);
  36619. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36620. if (tempData) {
  36621. tempData[pixelStorageIndex + 0] = r;
  36622. tempData[pixelStorageIndex + 1] = g;
  36623. tempData[pixelStorageIndex + 2] = b;
  36624. }
  36625. pixelIndexSlice++;
  36626. if (pixelIndexSlice % size == 0) {
  36627. pixelIndexH++;
  36628. pixelIndexSlice = 0;
  36629. if (pixelIndexH % size == 0) {
  36630. pixelIndexW++;
  36631. pixelIndexH = 0;
  36632. }
  36633. }
  36634. }
  36635. }
  36636. if (tempData && data) {
  36637. for (var i = 0; i < tempData.length; i++) {
  36638. if (i > 0 && (i + 1) % 4 === 0) {
  36639. data[i] = 255;
  36640. }
  36641. else {
  36642. var value = tempData[i];
  36643. data[i] = (value / maxColor * 255);
  36644. }
  36645. }
  36646. }
  36647. if (texture.is3D) {
  36648. texture.updateSize(size, size, size);
  36649. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36650. }
  36651. else {
  36652. texture.updateSize(size * size, size);
  36653. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36654. }
  36655. };
  36656. var scene = this.getScene();
  36657. if (scene) {
  36658. scene._loadFile(this.url, callback);
  36659. }
  36660. else {
  36661. this._engine._loadFile(this.url, callback);
  36662. }
  36663. return this._texture;
  36664. };
  36665. /**
  36666. * Starts the loading process of the texture.
  36667. */
  36668. ColorGradingTexture.prototype.loadTexture = function () {
  36669. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36670. this.load3dlTexture();
  36671. }
  36672. };
  36673. /**
  36674. * Clones the color gradind texture.
  36675. */
  36676. ColorGradingTexture.prototype.clone = function () {
  36677. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36678. // Base texture
  36679. newTexture.level = this.level;
  36680. return newTexture;
  36681. };
  36682. /**
  36683. * Called during delayed load for textures.
  36684. */
  36685. ColorGradingTexture.prototype.delayLoad = function () {
  36686. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36687. return;
  36688. }
  36689. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36690. this._texture = this._getFromCache(this.url, true);
  36691. if (!this._texture) {
  36692. this.loadTexture();
  36693. }
  36694. };
  36695. /**
  36696. * Parses a color grading texture serialized by Babylon.
  36697. * @param parsedTexture The texture information being parsedTexture
  36698. * @param scene The scene to load the texture in
  36699. * @param rootUrl The root url of the data assets to load
  36700. * @return A color gradind texture
  36701. */
  36702. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36703. var texture = null;
  36704. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36705. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36706. texture.name = parsedTexture.name;
  36707. texture.level = parsedTexture.level;
  36708. }
  36709. return texture;
  36710. };
  36711. /**
  36712. * Serializes the LUT texture to json format.
  36713. */
  36714. ColorGradingTexture.prototype.serialize = function () {
  36715. if (!this.name) {
  36716. return null;
  36717. }
  36718. var serializationObject = {};
  36719. serializationObject.name = this.name;
  36720. serializationObject.level = this.level;
  36721. serializationObject.customType = "BABYLON.ColorGradingTexture";
  36722. return serializationObject;
  36723. };
  36724. /**
  36725. * Empty line regex stored for GC.
  36726. */
  36727. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  36728. return ColorGradingTexture;
  36729. }(BABYLON.BaseTexture));
  36730. BABYLON.ColorGradingTexture = ColorGradingTexture;
  36731. })(BABYLON || (BABYLON = {}));
  36732. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  36733. var BABYLON;
  36734. (function (BABYLON) {
  36735. /**
  36736. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36737. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36738. * 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;
  36739. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36740. */
  36741. var ColorCurves = /** @class */ (function () {
  36742. function ColorCurves() {
  36743. this._dirty = true;
  36744. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  36745. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  36746. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36747. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  36748. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36749. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  36750. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  36751. this._globalHue = 30;
  36752. this._globalDensity = 0;
  36753. this._globalSaturation = 0;
  36754. this._globalExposure = 0;
  36755. this._highlightsHue = 30;
  36756. this._highlightsDensity = 0;
  36757. this._highlightsSaturation = 0;
  36758. this._highlightsExposure = 0;
  36759. this._midtonesHue = 30;
  36760. this._midtonesDensity = 0;
  36761. this._midtonesSaturation = 0;
  36762. this._midtonesExposure = 0;
  36763. this._shadowsHue = 30;
  36764. this._shadowsDensity = 0;
  36765. this._shadowsSaturation = 0;
  36766. this._shadowsExposure = 0;
  36767. }
  36768. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  36769. /**
  36770. * Gets the global Hue value.
  36771. * 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).
  36772. */
  36773. get: function () {
  36774. return this._globalHue;
  36775. },
  36776. /**
  36777. * Sets the global Hue value.
  36778. * 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).
  36779. */
  36780. set: function (value) {
  36781. this._globalHue = value;
  36782. this._dirty = true;
  36783. },
  36784. enumerable: true,
  36785. configurable: true
  36786. });
  36787. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  36788. /**
  36789. * Gets the global Density value.
  36790. * 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.
  36791. * Values less than zero provide a filter of opposite hue.
  36792. */
  36793. get: function () {
  36794. return this._globalDensity;
  36795. },
  36796. /**
  36797. * Sets the global Density value.
  36798. * 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.
  36799. * Values less than zero provide a filter of opposite hue.
  36800. */
  36801. set: function (value) {
  36802. this._globalDensity = value;
  36803. this._dirty = true;
  36804. },
  36805. enumerable: true,
  36806. configurable: true
  36807. });
  36808. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  36809. /**
  36810. * Gets the global Saturation value.
  36811. * 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.
  36812. */
  36813. get: function () {
  36814. return this._globalSaturation;
  36815. },
  36816. /**
  36817. * Sets the global Saturation value.
  36818. * 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.
  36819. */
  36820. set: function (value) {
  36821. this._globalSaturation = value;
  36822. this._dirty = true;
  36823. },
  36824. enumerable: true,
  36825. configurable: true
  36826. });
  36827. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  36828. /**
  36829. * Gets the highlights Hue value.
  36830. * 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).
  36831. */
  36832. get: function () {
  36833. return this._highlightsHue;
  36834. },
  36835. /**
  36836. * Sets the highlights Hue value.
  36837. * 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).
  36838. */
  36839. set: function (value) {
  36840. this._highlightsHue = value;
  36841. this._dirty = true;
  36842. },
  36843. enumerable: true,
  36844. configurable: true
  36845. });
  36846. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  36847. /**
  36848. * Gets the highlights Density value.
  36849. * 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.
  36850. * Values less than zero provide a filter of opposite hue.
  36851. */
  36852. get: function () {
  36853. return this._highlightsDensity;
  36854. },
  36855. /**
  36856. * Sets the highlights Density value.
  36857. * 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.
  36858. * Values less than zero provide a filter of opposite hue.
  36859. */
  36860. set: function (value) {
  36861. this._highlightsDensity = value;
  36862. this._dirty = true;
  36863. },
  36864. enumerable: true,
  36865. configurable: true
  36866. });
  36867. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  36868. /**
  36869. * Gets the highlights Saturation value.
  36870. * 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.
  36871. */
  36872. get: function () {
  36873. return this._highlightsSaturation;
  36874. },
  36875. /**
  36876. * Sets the highlights Saturation value.
  36877. * 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.
  36878. */
  36879. set: function (value) {
  36880. this._highlightsSaturation = value;
  36881. this._dirty = true;
  36882. },
  36883. enumerable: true,
  36884. configurable: true
  36885. });
  36886. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  36887. /**
  36888. * Gets the highlights Exposure value.
  36889. * 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.
  36890. */
  36891. get: function () {
  36892. return this._highlightsExposure;
  36893. },
  36894. /**
  36895. * Sets the highlights Exposure value.
  36896. * 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.
  36897. */
  36898. set: function (value) {
  36899. this._highlightsExposure = value;
  36900. this._dirty = true;
  36901. },
  36902. enumerable: true,
  36903. configurable: true
  36904. });
  36905. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  36906. /**
  36907. * Gets the midtones Hue value.
  36908. * 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).
  36909. */
  36910. get: function () {
  36911. return this._midtonesHue;
  36912. },
  36913. /**
  36914. * Sets the midtones Hue value.
  36915. * 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).
  36916. */
  36917. set: function (value) {
  36918. this._midtonesHue = value;
  36919. this._dirty = true;
  36920. },
  36921. enumerable: true,
  36922. configurable: true
  36923. });
  36924. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  36925. /**
  36926. * Gets the midtones Density value.
  36927. * 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.
  36928. * Values less than zero provide a filter of opposite hue.
  36929. */
  36930. get: function () {
  36931. return this._midtonesDensity;
  36932. },
  36933. /**
  36934. * Sets the midtones Density value.
  36935. * 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.
  36936. * Values less than zero provide a filter of opposite hue.
  36937. */
  36938. set: function (value) {
  36939. this._midtonesDensity = value;
  36940. this._dirty = true;
  36941. },
  36942. enumerable: true,
  36943. configurable: true
  36944. });
  36945. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  36946. /**
  36947. * Gets the midtones Saturation value.
  36948. * 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.
  36949. */
  36950. get: function () {
  36951. return this._midtonesSaturation;
  36952. },
  36953. /**
  36954. * Sets the midtones Saturation value.
  36955. * 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.
  36956. */
  36957. set: function (value) {
  36958. this._midtonesSaturation = value;
  36959. this._dirty = true;
  36960. },
  36961. enumerable: true,
  36962. configurable: true
  36963. });
  36964. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  36965. /**
  36966. * Gets the midtones Exposure value.
  36967. * 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.
  36968. */
  36969. get: function () {
  36970. return this._midtonesExposure;
  36971. },
  36972. /**
  36973. * Sets the midtones Exposure value.
  36974. * 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.
  36975. */
  36976. set: function (value) {
  36977. this._midtonesExposure = value;
  36978. this._dirty = true;
  36979. },
  36980. enumerable: true,
  36981. configurable: true
  36982. });
  36983. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  36984. /**
  36985. * Gets the shadows Hue value.
  36986. * 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).
  36987. */
  36988. get: function () {
  36989. return this._shadowsHue;
  36990. },
  36991. /**
  36992. * Sets the shadows Hue value.
  36993. * 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).
  36994. */
  36995. set: function (value) {
  36996. this._shadowsHue = value;
  36997. this._dirty = true;
  36998. },
  36999. enumerable: true,
  37000. configurable: true
  37001. });
  37002. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37003. /**
  37004. * Gets the shadows Density value.
  37005. * 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.
  37006. * Values less than zero provide a filter of opposite hue.
  37007. */
  37008. get: function () {
  37009. return this._shadowsDensity;
  37010. },
  37011. /**
  37012. * Sets the shadows Density value.
  37013. * 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.
  37014. * Values less than zero provide a filter of opposite hue.
  37015. */
  37016. set: function (value) {
  37017. this._shadowsDensity = value;
  37018. this._dirty = true;
  37019. },
  37020. enumerable: true,
  37021. configurable: true
  37022. });
  37023. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37024. /**
  37025. * Gets the shadows Saturation value.
  37026. * 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.
  37027. */
  37028. get: function () {
  37029. return this._shadowsSaturation;
  37030. },
  37031. /**
  37032. * Sets the shadows Saturation value.
  37033. * 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.
  37034. */
  37035. set: function (value) {
  37036. this._shadowsSaturation = value;
  37037. this._dirty = true;
  37038. },
  37039. enumerable: true,
  37040. configurable: true
  37041. });
  37042. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37043. /**
  37044. * Gets the shadows Exposure value.
  37045. * 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.
  37046. */
  37047. get: function () {
  37048. return this._shadowsExposure;
  37049. },
  37050. /**
  37051. * Sets the shadows Exposure value.
  37052. * 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.
  37053. */
  37054. set: function (value) {
  37055. this._shadowsExposure = value;
  37056. this._dirty = true;
  37057. },
  37058. enumerable: true,
  37059. configurable: true
  37060. });
  37061. ColorCurves.prototype.getClassName = function () {
  37062. return "ColorCurves";
  37063. };
  37064. /**
  37065. * Binds the color curves to the shader.
  37066. * @param colorCurves The color curve to bind
  37067. * @param effect The effect to bind to
  37068. */
  37069. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37070. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37071. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37072. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37073. if (colorCurves._dirty) {
  37074. colorCurves._dirty = false;
  37075. // Fill in global info.
  37076. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37077. // Compute highlights info.
  37078. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37079. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37080. // Compute midtones info.
  37081. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37082. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37083. // Compute shadows info.
  37084. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37085. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37086. // Compute deltas (neutral is midtones).
  37087. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37088. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37089. }
  37090. if (effect) {
  37091. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37092. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37093. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37094. }
  37095. };
  37096. /**
  37097. * Prepare the list of uniforms associated with the ColorCurves effects.
  37098. * @param uniformsList The list of uniforms used in the effect
  37099. */
  37100. ColorCurves.PrepareUniforms = function (uniformsList) {
  37101. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37102. };
  37103. /**
  37104. * Returns color grading data based on a hue, density, saturation and exposure value.
  37105. * @param filterHue The hue of the color filter.
  37106. * @param filterDensity The density of the color filter.
  37107. * @param saturation The saturation.
  37108. * @param exposure The exposure.
  37109. * @param result The result data container.
  37110. */
  37111. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37112. if (hue == null) {
  37113. return;
  37114. }
  37115. hue = ColorCurves.clamp(hue, 0, 360);
  37116. density = ColorCurves.clamp(density, -100, 100);
  37117. saturation = ColorCurves.clamp(saturation, -100, 100);
  37118. exposure = ColorCurves.clamp(exposure, -100, 100);
  37119. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37120. // so that the maximum filter density is only 50% control. This provides fine control
  37121. // for small values and reasonable range.
  37122. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37123. density *= 0.5;
  37124. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37125. if (density < 0) {
  37126. density *= -1;
  37127. hue = (hue + 180) % 360;
  37128. }
  37129. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37130. result.scaleToRef(2, result);
  37131. result.a = 1 + 0.01 * saturation;
  37132. };
  37133. /**
  37134. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37135. * @param value The input slider value in range [-100,100].
  37136. * @returns Adjusted value.
  37137. */
  37138. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37139. value /= 100;
  37140. var x = Math.abs(value);
  37141. x = Math.pow(x, 2);
  37142. if (value < 0) {
  37143. x *= -1;
  37144. }
  37145. x *= 100;
  37146. return x;
  37147. };
  37148. /**
  37149. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37150. * @param hue The hue (H) input.
  37151. * @param saturation The saturation (S) input.
  37152. * @param brightness The brightness (B) input.
  37153. * @result An RGBA color represented as Vector4.
  37154. */
  37155. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37156. var h = ColorCurves.clamp(hue, 0, 360);
  37157. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37158. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37159. if (s === 0) {
  37160. result.r = v;
  37161. result.g = v;
  37162. result.b = v;
  37163. }
  37164. else {
  37165. // sector 0 to 5
  37166. h /= 60;
  37167. var i = Math.floor(h);
  37168. // fractional part of h
  37169. var f = h - i;
  37170. var p = v * (1 - s);
  37171. var q = v * (1 - s * f);
  37172. var t = v * (1 - s * (1 - f));
  37173. switch (i) {
  37174. case 0:
  37175. result.r = v;
  37176. result.g = t;
  37177. result.b = p;
  37178. break;
  37179. case 1:
  37180. result.r = q;
  37181. result.g = v;
  37182. result.b = p;
  37183. break;
  37184. case 2:
  37185. result.r = p;
  37186. result.g = v;
  37187. result.b = t;
  37188. break;
  37189. case 3:
  37190. result.r = p;
  37191. result.g = q;
  37192. result.b = v;
  37193. break;
  37194. case 4:
  37195. result.r = t;
  37196. result.g = p;
  37197. result.b = v;
  37198. break;
  37199. default:// case 5:
  37200. result.r = v;
  37201. result.g = p;
  37202. result.b = q;
  37203. break;
  37204. }
  37205. }
  37206. result.a = 1;
  37207. };
  37208. /**
  37209. * Returns a value clamped between min and max
  37210. * @param value The value to clamp
  37211. * @param min The minimum of value
  37212. * @param max The maximum of value
  37213. * @returns The clamped value.
  37214. */
  37215. ColorCurves.clamp = function (value, min, max) {
  37216. return Math.min(Math.max(value, min), max);
  37217. };
  37218. /**
  37219. * Clones the current color curve instance.
  37220. * @return The cloned curves
  37221. */
  37222. ColorCurves.prototype.clone = function () {
  37223. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37224. };
  37225. /**
  37226. * Serializes the current color curve instance to a json representation.
  37227. * @return a JSON representation
  37228. */
  37229. ColorCurves.prototype.serialize = function () {
  37230. return BABYLON.SerializationHelper.Serialize(this);
  37231. };
  37232. /**
  37233. * Parses the color curve from a json representation.
  37234. * @param source the JSON source to parse
  37235. * @return The parsed curves
  37236. */
  37237. ColorCurves.Parse = function (source) {
  37238. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37239. };
  37240. __decorate([
  37241. BABYLON.serialize()
  37242. ], ColorCurves.prototype, "_globalHue", void 0);
  37243. __decorate([
  37244. BABYLON.serialize()
  37245. ], ColorCurves.prototype, "_globalDensity", void 0);
  37246. __decorate([
  37247. BABYLON.serialize()
  37248. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37249. __decorate([
  37250. BABYLON.serialize()
  37251. ], ColorCurves.prototype, "_globalExposure", void 0);
  37252. __decorate([
  37253. BABYLON.serialize()
  37254. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37255. __decorate([
  37256. BABYLON.serialize()
  37257. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37258. __decorate([
  37259. BABYLON.serialize()
  37260. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37261. __decorate([
  37262. BABYLON.serialize()
  37263. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37264. __decorate([
  37265. BABYLON.serialize()
  37266. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37267. __decorate([
  37268. BABYLON.serialize()
  37269. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37270. __decorate([
  37271. BABYLON.serialize()
  37272. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37273. __decorate([
  37274. BABYLON.serialize()
  37275. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37276. return ColorCurves;
  37277. }());
  37278. BABYLON.ColorCurves = ColorCurves;
  37279. })(BABYLON || (BABYLON = {}));
  37280. //# sourceMappingURL=babylon.colorCurves.js.map
  37281. //# sourceMappingURL=babylon.behavior.js.map
  37282. var BABYLON;
  37283. (function (BABYLON) {
  37284. /**
  37285. * "Static Class" containing the most commonly used helper while dealing with material for
  37286. * rendering purpose.
  37287. *
  37288. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37289. *
  37290. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37291. */
  37292. var MaterialHelper = /** @class */ (function () {
  37293. function MaterialHelper() {
  37294. }
  37295. /**
  37296. * Bind the current view position to an effect.
  37297. * @param effect The effect to be bound
  37298. * @param scene The scene the eyes position is used from
  37299. */
  37300. MaterialHelper.BindEyePosition = function (effect, scene) {
  37301. if (scene._forcedViewPosition) {
  37302. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37303. return;
  37304. }
  37305. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37306. };
  37307. /**
  37308. * Helps preparing the defines values about the UVs in used in the effect.
  37309. * UVs are shared as much as we can accross chanels in the shaders.
  37310. * @param texture The texture we are preparing the UVs for
  37311. * @param defines The defines to update
  37312. * @param key The chanel key "diffuse", "specular"... used in the shader
  37313. */
  37314. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37315. defines._needUVs = true;
  37316. defines[key] = true;
  37317. if (texture.getTextureMatrix().isIdentity(true)) {
  37318. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37319. if (texture.coordinatesIndex === 0) {
  37320. defines["MAINUV1"] = true;
  37321. }
  37322. else {
  37323. defines["MAINUV2"] = true;
  37324. }
  37325. }
  37326. else {
  37327. defines[key + "DIRECTUV"] = 0;
  37328. }
  37329. };
  37330. /**
  37331. * Binds a texture matrix value to its corrsponding uniform
  37332. * @param texture The texture to bind the matrix for
  37333. * @param uniformBuffer The uniform buffer receivin the data
  37334. * @param key The chanel key "diffuse", "specular"... used in the shader
  37335. */
  37336. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37337. var matrix = texture.getTextureMatrix();
  37338. if (!matrix.isIdentity(true)) {
  37339. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37340. }
  37341. };
  37342. /**
  37343. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37344. * @param mesh defines the current mesh
  37345. * @param scene defines the current scene
  37346. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37347. * @param pointsCloud defines if point cloud rendering has to be turned on
  37348. * @param fogEnabled defines if fog has to be turned on
  37349. * @param alphaTest defines if alpha testing has to be turned on
  37350. * @param defines defines the current list of defines
  37351. */
  37352. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37353. if (defines._areMiscDirty) {
  37354. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37355. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37356. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37357. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37358. defines["ALPHATEST"] = alphaTest;
  37359. }
  37360. };
  37361. /**
  37362. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37363. * @param scene defines the current scene
  37364. * @param engine defines the current engine
  37365. * @param defines specifies the list of active defines
  37366. * @param useInstances defines if instances have to be turned on
  37367. */
  37368. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  37369. var changed = false;
  37370. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  37371. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  37372. changed = true;
  37373. }
  37374. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37375. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37376. changed = true;
  37377. }
  37378. if (defines["INSTANCES"] !== useInstances) {
  37379. defines["INSTANCES"] = useInstances;
  37380. changed = true;
  37381. }
  37382. if (changed) {
  37383. defines.markAsUnprocessed();
  37384. }
  37385. };
  37386. /**
  37387. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37388. * @param mesh The mesh containing the geometry data we will draw
  37389. * @param defines The defines to update
  37390. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37391. * @param useBones Precise whether bones should be used or not (override mesh info)
  37392. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37393. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37394. * @returns false if defines are considered not dirty and have not been checked
  37395. */
  37396. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37397. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37398. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37399. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37400. return false;
  37401. }
  37402. defines._normals = defines._needNormals;
  37403. defines._uvs = defines._needUVs;
  37404. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37405. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37406. defines["TANGENT"] = true;
  37407. }
  37408. if (defines._needUVs) {
  37409. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37410. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37411. }
  37412. else {
  37413. defines["UV1"] = false;
  37414. defines["UV2"] = false;
  37415. }
  37416. if (useVertexColor) {
  37417. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37418. defines["VERTEXCOLOR"] = hasVertexColors;
  37419. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37420. }
  37421. if (useBones) {
  37422. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37423. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37424. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37425. }
  37426. else {
  37427. defines["NUM_BONE_INFLUENCERS"] = 0;
  37428. defines["BonesPerMesh"] = 0;
  37429. }
  37430. }
  37431. if (useMorphTargets) {
  37432. var manager = mesh.morphTargetManager;
  37433. if (manager) {
  37434. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37435. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37436. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37437. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37438. }
  37439. else {
  37440. defines["MORPHTARGETS_TANGENT"] = false;
  37441. defines["MORPHTARGETS_NORMAL"] = false;
  37442. defines["MORPHTARGETS"] = false;
  37443. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37444. }
  37445. }
  37446. return true;
  37447. };
  37448. /**
  37449. * Prepares the defines related to the light information passed in parameter
  37450. * @param scene The scene we are intending to draw
  37451. * @param mesh The mesh the effect is compiling for
  37452. * @param defines The defines to update
  37453. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37454. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37455. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37456. * @returns true if normals will be required for the rest of the effect
  37457. */
  37458. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37459. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37460. if (disableLighting === void 0) { disableLighting = false; }
  37461. if (!defines._areLightsDirty) {
  37462. return defines._needNormals;
  37463. }
  37464. var lightIndex = 0;
  37465. var needNormals = false;
  37466. var needRebuild = false;
  37467. var lightmapMode = false;
  37468. var shadowEnabled = false;
  37469. var specularEnabled = false;
  37470. if (scene.lightsEnabled && !disableLighting) {
  37471. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37472. var light = _a[_i];
  37473. needNormals = true;
  37474. if (defines["LIGHT" + lightIndex] === undefined) {
  37475. needRebuild = true;
  37476. }
  37477. defines["LIGHT" + lightIndex] = true;
  37478. defines["SPOTLIGHT" + lightIndex] = false;
  37479. defines["HEMILIGHT" + lightIndex] = false;
  37480. defines["POINTLIGHT" + lightIndex] = false;
  37481. defines["DIRLIGHT" + lightIndex] = false;
  37482. var type;
  37483. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37484. type = "SPOTLIGHT" + lightIndex;
  37485. var spotLight = light;
  37486. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37487. }
  37488. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37489. type = "HEMILIGHT" + lightIndex;
  37490. }
  37491. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37492. type = "POINTLIGHT" + lightIndex;
  37493. }
  37494. else {
  37495. type = "DIRLIGHT" + lightIndex;
  37496. }
  37497. defines[type] = true;
  37498. // Specular
  37499. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37500. specularEnabled = true;
  37501. }
  37502. // Shadows
  37503. defines["SHADOW" + lightIndex] = false;
  37504. defines["SHADOWPCF" + lightIndex] = false;
  37505. defines["SHADOWESM" + lightIndex] = false;
  37506. defines["SHADOWCUBE" + lightIndex] = false;
  37507. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37508. var shadowGenerator = light.getShadowGenerator();
  37509. if (shadowGenerator) {
  37510. shadowEnabled = true;
  37511. shadowGenerator.prepareDefines(defines, lightIndex);
  37512. }
  37513. }
  37514. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37515. lightmapMode = true;
  37516. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37517. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37518. }
  37519. else {
  37520. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37521. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37522. }
  37523. lightIndex++;
  37524. if (lightIndex === maxSimultaneousLights)
  37525. break;
  37526. }
  37527. }
  37528. defines["SPECULARTERM"] = specularEnabled;
  37529. defines["SHADOWS"] = shadowEnabled;
  37530. // Resetting all other lights if any
  37531. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37532. if (defines["LIGHT" + index] !== undefined) {
  37533. defines["LIGHT" + index] = false;
  37534. defines["HEMILIGHT" + lightIndex] = false;
  37535. defines["POINTLIGHT" + lightIndex] = false;
  37536. defines["DIRLIGHT" + lightIndex] = false;
  37537. defines["SPOTLIGHT" + lightIndex] = false;
  37538. defines["SHADOW" + lightIndex] = false;
  37539. }
  37540. }
  37541. var caps = scene.getEngine().getCaps();
  37542. if (defines["SHADOWFLOAT"] === undefined) {
  37543. needRebuild = true;
  37544. }
  37545. defines["SHADOWFLOAT"] = shadowEnabled &&
  37546. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37547. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37548. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37549. if (needRebuild) {
  37550. defines.rebuild();
  37551. }
  37552. return needNormals;
  37553. };
  37554. /**
  37555. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37556. * that won t be acctive due to defines being turned off.
  37557. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37558. * @param samplersList The samplers list
  37559. * @param defines The defines helping in the list generation
  37560. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37561. */
  37562. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37563. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37564. var uniformsList;
  37565. var uniformBuffersList = null;
  37566. if (uniformsListOrOptions.uniformsNames) {
  37567. var options = uniformsListOrOptions;
  37568. uniformsList = options.uniformsNames;
  37569. uniformBuffersList = options.uniformBuffersNames;
  37570. samplersList = options.samplers;
  37571. defines = options.defines;
  37572. maxSimultaneousLights = options.maxSimultaneousLights;
  37573. }
  37574. else {
  37575. uniformsList = uniformsListOrOptions;
  37576. if (!samplersList) {
  37577. samplersList = [];
  37578. }
  37579. }
  37580. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37581. if (!defines["LIGHT" + lightIndex]) {
  37582. break;
  37583. }
  37584. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37585. if (uniformBuffersList) {
  37586. uniformBuffersList.push("Light" + lightIndex);
  37587. }
  37588. samplersList.push("shadowSampler" + lightIndex);
  37589. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37590. samplersList.push("projectionLightSampler" + lightIndex);
  37591. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37592. }
  37593. }
  37594. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37595. uniformsList.push("morphTargetInfluences");
  37596. }
  37597. };
  37598. /**
  37599. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37600. * @param defines The defines to update while falling back
  37601. * @param fallbacks The authorized effect fallbacks
  37602. * @param maxSimultaneousLights The maximum number of lights allowed
  37603. * @param rank the current rank of the Effect
  37604. * @returns The newly affected rank
  37605. */
  37606. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37607. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37608. if (rank === void 0) { rank = 0; }
  37609. var lightFallbackRank = 0;
  37610. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37611. if (!defines["LIGHT" + lightIndex]) {
  37612. break;
  37613. }
  37614. if (lightIndex > 0) {
  37615. lightFallbackRank = rank + lightIndex;
  37616. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37617. }
  37618. if (!defines["SHADOWS"]) {
  37619. if (defines["SHADOW" + lightIndex]) {
  37620. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37621. }
  37622. if (defines["SHADOWPCF" + lightIndex]) {
  37623. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37624. }
  37625. if (defines["SHADOWESM" + lightIndex]) {
  37626. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37627. }
  37628. }
  37629. }
  37630. return lightFallbackRank++;
  37631. };
  37632. /**
  37633. * Prepares the list of attributes required for morph targets according to the effect defines.
  37634. * @param attribs The current list of supported attribs
  37635. * @param mesh The mesh to prepare the morph targets attributes for
  37636. * @param defines The current Defines of the effect
  37637. */
  37638. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37639. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37640. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37641. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37642. var manager = mesh.morphTargetManager;
  37643. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37644. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37645. for (var index = 0; index < influencers; index++) {
  37646. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37647. if (normal) {
  37648. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37649. }
  37650. if (tangent) {
  37651. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37652. }
  37653. if (attribs.length > maxAttributesCount) {
  37654. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37655. }
  37656. }
  37657. }
  37658. };
  37659. /**
  37660. * Prepares the list of attributes required for bones according to the effect defines.
  37661. * @param attribs The current list of supported attribs
  37662. * @param mesh The mesh to prepare the bones attributes for
  37663. * @param defines The current Defines of the effect
  37664. * @param fallbacks The current efffect fallback strategy
  37665. */
  37666. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37667. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37668. fallbacks.addCPUSkinningFallback(0, mesh);
  37669. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37670. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37671. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37672. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37673. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37674. }
  37675. }
  37676. };
  37677. /**
  37678. * Prepares the list of attributes required for instances according to the effect defines.
  37679. * @param attribs The current list of supported attribs
  37680. * @param defines The current Defines of the effect
  37681. */
  37682. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37683. if (defines["INSTANCES"]) {
  37684. attribs.push("world0");
  37685. attribs.push("world1");
  37686. attribs.push("world2");
  37687. attribs.push("world3");
  37688. }
  37689. };
  37690. /**
  37691. * Binds the light shadow information to the effect for the given mesh.
  37692. * @param light The light containing the generator
  37693. * @param scene The scene the lights belongs to
  37694. * @param mesh The mesh we are binding the information to render
  37695. * @param lightIndex The light index in the effect used to render the mesh
  37696. * @param effect The effect we are binding the data to
  37697. */
  37698. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37699. if (light.shadowEnabled && mesh.receiveShadows) {
  37700. var shadowGenerator = light.getShadowGenerator();
  37701. if (shadowGenerator) {
  37702. shadowGenerator.bindShadowLight(lightIndex, effect);
  37703. }
  37704. }
  37705. };
  37706. /**
  37707. * Binds the light information to the effect.
  37708. * @param light The light containing the generator
  37709. * @param effect The effect we are binding the data to
  37710. * @param lightIndex The light index in the effect used to render
  37711. */
  37712. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  37713. light.transferToEffect(effect, lightIndex + "");
  37714. };
  37715. /**
  37716. * Binds the lights information from the scene to the effect for the given mesh.
  37717. * @param scene The scene the lights belongs to
  37718. * @param mesh The mesh we are binding the information to render
  37719. * @param effect The effect we are binding the data to
  37720. * @param defines The generated defines for the effect
  37721. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  37722. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  37723. */
  37724. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  37725. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37726. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  37727. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  37728. for (var i = 0; i < len; i++) {
  37729. var light = mesh._lightSources[i];
  37730. var iAsString = i.toString();
  37731. var scaledIntensity = light.getScaledIntensity();
  37732. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  37733. MaterialHelper.BindLightProperties(light, effect, i);
  37734. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  37735. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  37736. if (defines["SPECULARTERM"]) {
  37737. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  37738. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  37739. }
  37740. // Shadows
  37741. if (scene.shadowsEnabled) {
  37742. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  37743. }
  37744. light._uniformBuffer.update();
  37745. }
  37746. };
  37747. /**
  37748. * Binds the fog information from the scene to the effect for the given mesh.
  37749. * @param scene The scene the lights belongs to
  37750. * @param mesh The mesh we are binding the information to render
  37751. * @param effect The effect we are binding the data to
  37752. */
  37753. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  37754. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  37755. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  37756. effect.setColor3("vFogColor", scene.fogColor);
  37757. }
  37758. };
  37759. /**
  37760. * Binds the bones information from the mesh to the effect.
  37761. * @param mesh The mesh we are binding the information to render
  37762. * @param effect The effect we are binding the data to
  37763. */
  37764. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  37765. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37766. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  37767. if (matrices && effect) {
  37768. effect.setMatrices("mBones", matrices);
  37769. }
  37770. }
  37771. };
  37772. /**
  37773. * Binds the morph targets information from the mesh to the effect.
  37774. * @param abstractMesh The mesh we are binding the information to render
  37775. * @param effect The effect we are binding the data to
  37776. */
  37777. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  37778. var manager = abstractMesh.morphTargetManager;
  37779. if (!abstractMesh || !manager) {
  37780. return;
  37781. }
  37782. effect.setFloatArray("morphTargetInfluences", manager.influences);
  37783. };
  37784. /**
  37785. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  37786. * @param defines The generated defines used in the effect
  37787. * @param effect The effect we are binding the data to
  37788. * @param scene The scene we are willing to render with logarithmic scale for
  37789. */
  37790. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  37791. if (defines["LOGARITHMICDEPTH"]) {
  37792. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  37793. }
  37794. };
  37795. /**
  37796. * Binds the clip plane information from the scene to the effect.
  37797. * @param scene The scene the clip plane information are extracted from
  37798. * @param effect The effect we are binding the data to
  37799. */
  37800. MaterialHelper.BindClipPlane = function (effect, scene) {
  37801. if (scene.clipPlane) {
  37802. var clipPlane = scene.clipPlane;
  37803. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  37804. }
  37805. };
  37806. return MaterialHelper;
  37807. }());
  37808. BABYLON.MaterialHelper = MaterialHelper;
  37809. })(BABYLON || (BABYLON = {}));
  37810. //# sourceMappingURL=babylon.materialHelper.js.map
  37811. var BABYLON;
  37812. (function (BABYLON) {
  37813. var PushMaterial = /** @class */ (function (_super) {
  37814. __extends(PushMaterial, _super);
  37815. function PushMaterial(name, scene) {
  37816. var _this = _super.call(this, name, scene) || this;
  37817. _this.storeEffectOnSubMeshes = true;
  37818. return _this;
  37819. }
  37820. PushMaterial.prototype.getEffect = function () {
  37821. return this._activeEffect;
  37822. };
  37823. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  37824. if (!mesh) {
  37825. return false;
  37826. }
  37827. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  37828. return true;
  37829. }
  37830. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  37831. };
  37832. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37833. this._activeEffect.setMatrix("world", world);
  37834. };
  37835. PushMaterial.prototype.bind = function (world, mesh) {
  37836. if (!mesh) {
  37837. return;
  37838. }
  37839. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  37840. };
  37841. PushMaterial.prototype._afterBind = function (mesh, effect) {
  37842. if (effect === void 0) { effect = null; }
  37843. _super.prototype._afterBind.call(this, mesh);
  37844. this.getScene()._cachedEffect = effect;
  37845. };
  37846. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  37847. if (visibility === void 0) { visibility = 1; }
  37848. return scene.isCachedMaterialInvalid(this, effect, visibility);
  37849. };
  37850. return PushMaterial;
  37851. }(BABYLON.Material));
  37852. BABYLON.PushMaterial = PushMaterial;
  37853. })(BABYLON || (BABYLON = {}));
  37854. //# sourceMappingURL=babylon.pushMaterial.js.map
  37855. var BABYLON;
  37856. (function (BABYLON) {
  37857. var StandardMaterialDefines = /** @class */ (function (_super) {
  37858. __extends(StandardMaterialDefines, _super);
  37859. function StandardMaterialDefines() {
  37860. var _this = _super.call(this) || this;
  37861. _this.MAINUV1 = false;
  37862. _this.MAINUV2 = false;
  37863. _this.DIFFUSE = false;
  37864. _this.DIFFUSEDIRECTUV = 0;
  37865. _this.AMBIENT = false;
  37866. _this.AMBIENTDIRECTUV = 0;
  37867. _this.OPACITY = false;
  37868. _this.OPACITYDIRECTUV = 0;
  37869. _this.OPACITYRGB = false;
  37870. _this.REFLECTION = false;
  37871. _this.EMISSIVE = false;
  37872. _this.EMISSIVEDIRECTUV = 0;
  37873. _this.SPECULAR = false;
  37874. _this.SPECULARDIRECTUV = 0;
  37875. _this.BUMP = false;
  37876. _this.BUMPDIRECTUV = 0;
  37877. _this.PARALLAX = false;
  37878. _this.PARALLAXOCCLUSION = false;
  37879. _this.SPECULAROVERALPHA = false;
  37880. _this.CLIPPLANE = false;
  37881. _this.ALPHATEST = false;
  37882. _this.DEPTHPREPASS = false;
  37883. _this.ALPHAFROMDIFFUSE = false;
  37884. _this.POINTSIZE = false;
  37885. _this.FOG = false;
  37886. _this.SPECULARTERM = false;
  37887. _this.DIFFUSEFRESNEL = false;
  37888. _this.OPACITYFRESNEL = false;
  37889. _this.REFLECTIONFRESNEL = false;
  37890. _this.REFRACTIONFRESNEL = false;
  37891. _this.EMISSIVEFRESNEL = false;
  37892. _this.FRESNEL = false;
  37893. _this.NORMAL = false;
  37894. _this.UV1 = false;
  37895. _this.UV2 = false;
  37896. _this.VERTEXCOLOR = false;
  37897. _this.VERTEXALPHA = false;
  37898. _this.NUM_BONE_INFLUENCERS = 0;
  37899. _this.BonesPerMesh = 0;
  37900. _this.INSTANCES = false;
  37901. _this.GLOSSINESS = false;
  37902. _this.ROUGHNESS = false;
  37903. _this.EMISSIVEASILLUMINATION = false;
  37904. _this.LINKEMISSIVEWITHDIFFUSE = false;
  37905. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  37906. _this.LIGHTMAP = false;
  37907. _this.LIGHTMAPDIRECTUV = 0;
  37908. _this.USELIGHTMAPASSHADOWMAP = false;
  37909. _this.REFLECTIONMAP_3D = false;
  37910. _this.REFLECTIONMAP_SPHERICAL = false;
  37911. _this.REFLECTIONMAP_PLANAR = false;
  37912. _this.REFLECTIONMAP_CUBIC = false;
  37913. _this.REFLECTIONMAP_PROJECTION = false;
  37914. _this.REFLECTIONMAP_SKYBOX = false;
  37915. _this.REFLECTIONMAP_EXPLICIT = false;
  37916. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37917. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37918. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37919. _this.INVERTCUBICMAP = false;
  37920. _this.LOGARITHMICDEPTH = false;
  37921. _this.REFRACTION = false;
  37922. _this.REFRACTIONMAP_3D = false;
  37923. _this.REFLECTIONOVERALPHA = false;
  37924. _this.TWOSIDEDLIGHTING = false;
  37925. _this.SHADOWFLOAT = false;
  37926. _this.MORPHTARGETS = false;
  37927. _this.MORPHTARGETS_NORMAL = false;
  37928. _this.MORPHTARGETS_TANGENT = false;
  37929. _this.NUM_MORPH_INFLUENCERS = 0;
  37930. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  37931. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  37932. _this.IMAGEPROCESSING = false;
  37933. _this.VIGNETTE = false;
  37934. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37935. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37936. _this.TONEMAPPING = false;
  37937. _this.CONTRAST = false;
  37938. _this.COLORCURVES = false;
  37939. _this.COLORGRADING = false;
  37940. _this.COLORGRADING3D = false;
  37941. _this.SAMPLER3DGREENDEPTH = false;
  37942. _this.SAMPLER3DBGRMAP = false;
  37943. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37944. _this.EXPOSURE = false;
  37945. _this.rebuild();
  37946. return _this;
  37947. }
  37948. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  37949. var modes = [
  37950. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  37951. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  37952. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  37953. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  37954. ];
  37955. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  37956. var mode = modes_1[_i];
  37957. this[mode] = (mode === modeToEnable);
  37958. }
  37959. };
  37960. return StandardMaterialDefines;
  37961. }(BABYLON.MaterialDefines));
  37962. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  37963. var StandardMaterial = /** @class */ (function (_super) {
  37964. __extends(StandardMaterial, _super);
  37965. function StandardMaterial(name, scene) {
  37966. var _this = _super.call(this, name, scene) || this;
  37967. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37968. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  37969. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  37970. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37971. _this.specularPower = 64;
  37972. _this._useAlphaFromDiffuseTexture = false;
  37973. _this._useEmissiveAsIllumination = false;
  37974. _this._linkEmissiveWithDiffuse = false;
  37975. _this._useSpecularOverAlpha = false;
  37976. _this._useReflectionOverAlpha = false;
  37977. _this._disableLighting = false;
  37978. _this._useParallax = false;
  37979. _this._useParallaxOcclusion = false;
  37980. _this.parallaxScaleBias = 0.05;
  37981. _this._roughness = 0;
  37982. _this.indexOfRefraction = 0.98;
  37983. _this.invertRefractionY = true;
  37984. _this._useLightmapAsShadowmap = false;
  37985. _this._useReflectionFresnelFromSpecular = false;
  37986. _this._useGlossinessFromSpecularMapAlpha = false;
  37987. _this._maxSimultaneousLights = 4;
  37988. /**
  37989. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37990. */
  37991. _this._invertNormalMapX = false;
  37992. /**
  37993. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37994. */
  37995. _this._invertNormalMapY = false;
  37996. /**
  37997. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37998. */
  37999. _this._twoSidedLighting = false;
  38000. _this._renderTargets = new BABYLON.SmartArray(16);
  38001. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38002. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38003. // Setup the default processing configuration to the scene.
  38004. _this._attachImageProcessingConfiguration(null);
  38005. _this.getRenderTargetTextures = function () {
  38006. _this._renderTargets.reset();
  38007. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38008. _this._renderTargets.push(_this._reflectionTexture);
  38009. }
  38010. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38011. _this._renderTargets.push(_this._refractionTexture);
  38012. }
  38013. return _this._renderTargets;
  38014. };
  38015. return _this;
  38016. }
  38017. ;
  38018. ;
  38019. ;
  38020. ;
  38021. ;
  38022. ;
  38023. ;
  38024. ;
  38025. ;
  38026. ;
  38027. ;
  38028. ;
  38029. ;
  38030. ;
  38031. ;
  38032. ;
  38033. ;
  38034. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38035. /**
  38036. * Gets the image processing configuration used either in this material.
  38037. */
  38038. get: function () {
  38039. return this._imageProcessingConfiguration;
  38040. },
  38041. /**
  38042. * Sets the Default image processing configuration used either in the this material.
  38043. *
  38044. * If sets to null, the scene one is in use.
  38045. */
  38046. set: function (value) {
  38047. this._attachImageProcessingConfiguration(value);
  38048. // Ensure the effect will be rebuilt.
  38049. this._markAllSubMeshesAsTexturesDirty();
  38050. },
  38051. enumerable: true,
  38052. configurable: true
  38053. });
  38054. /**
  38055. * Attaches a new image processing configuration to the Standard Material.
  38056. * @param configuration
  38057. */
  38058. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38059. var _this = this;
  38060. if (configuration === this._imageProcessingConfiguration) {
  38061. return;
  38062. }
  38063. // Detaches observer.
  38064. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38065. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38066. }
  38067. // Pick the scene configuration if needed.
  38068. if (!configuration) {
  38069. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38070. }
  38071. else {
  38072. this._imageProcessingConfiguration = configuration;
  38073. }
  38074. // Attaches observer.
  38075. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38076. _this._markAllSubMeshesAsImageProcessingDirty();
  38077. });
  38078. };
  38079. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38080. /**
  38081. * Gets wether the color curves effect is enabled.
  38082. */
  38083. get: function () {
  38084. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38085. },
  38086. /**
  38087. * Sets wether the color curves effect is enabled.
  38088. */
  38089. set: function (value) {
  38090. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38091. },
  38092. enumerable: true,
  38093. configurable: true
  38094. });
  38095. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38096. /**
  38097. * Gets wether the color grading effect is enabled.
  38098. */
  38099. get: function () {
  38100. return this.imageProcessingConfiguration.colorGradingEnabled;
  38101. },
  38102. /**
  38103. * Gets wether the color grading effect is enabled.
  38104. */
  38105. set: function (value) {
  38106. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38107. },
  38108. enumerable: true,
  38109. configurable: true
  38110. });
  38111. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38112. /**
  38113. * Gets wether tonemapping is enabled or not.
  38114. */
  38115. get: function () {
  38116. return this._imageProcessingConfiguration.toneMappingEnabled;
  38117. },
  38118. /**
  38119. * Sets wether tonemapping is enabled or not
  38120. */
  38121. set: function (value) {
  38122. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38123. },
  38124. enumerable: true,
  38125. configurable: true
  38126. });
  38127. ;
  38128. ;
  38129. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38130. /**
  38131. * The camera exposure used on this material.
  38132. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38133. * This corresponds to a photographic exposure.
  38134. */
  38135. get: function () {
  38136. return this._imageProcessingConfiguration.exposure;
  38137. },
  38138. /**
  38139. * The camera exposure used on this material.
  38140. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38141. * This corresponds to a photographic exposure.
  38142. */
  38143. set: function (value) {
  38144. this._imageProcessingConfiguration.exposure = value;
  38145. },
  38146. enumerable: true,
  38147. configurable: true
  38148. });
  38149. ;
  38150. ;
  38151. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38152. /**
  38153. * Gets The camera contrast used on this material.
  38154. */
  38155. get: function () {
  38156. return this._imageProcessingConfiguration.contrast;
  38157. },
  38158. /**
  38159. * Sets The camera contrast used on this material.
  38160. */
  38161. set: function (value) {
  38162. this._imageProcessingConfiguration.contrast = value;
  38163. },
  38164. enumerable: true,
  38165. configurable: true
  38166. });
  38167. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38168. /**
  38169. * Gets the Color Grading 2D Lookup Texture.
  38170. */
  38171. get: function () {
  38172. return this._imageProcessingConfiguration.colorGradingTexture;
  38173. },
  38174. /**
  38175. * Sets the Color Grading 2D Lookup Texture.
  38176. */
  38177. set: function (value) {
  38178. this._imageProcessingConfiguration.colorGradingTexture = value;
  38179. },
  38180. enumerable: true,
  38181. configurable: true
  38182. });
  38183. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38184. /**
  38185. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38186. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38187. * 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;
  38188. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38189. */
  38190. get: function () {
  38191. return this._imageProcessingConfiguration.colorCurves;
  38192. },
  38193. /**
  38194. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38195. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38196. * 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;
  38197. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38198. */
  38199. set: function (value) {
  38200. this._imageProcessingConfiguration.colorCurves = value;
  38201. },
  38202. enumerable: true,
  38203. configurable: true
  38204. });
  38205. StandardMaterial.prototype.getClassName = function () {
  38206. return "StandardMaterial";
  38207. };
  38208. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38209. get: function () {
  38210. return this._useLogarithmicDepth;
  38211. },
  38212. set: function (value) {
  38213. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38214. this._markAllSubMeshesAsMiscDirty();
  38215. },
  38216. enumerable: true,
  38217. configurable: true
  38218. });
  38219. StandardMaterial.prototype.needAlphaBlending = function () {
  38220. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38221. };
  38222. StandardMaterial.prototype.needAlphaTesting = function () {
  38223. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38224. };
  38225. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38226. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38227. };
  38228. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38229. return this._diffuseTexture;
  38230. };
  38231. /**
  38232. * Child classes can use it to update shaders
  38233. */
  38234. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38235. if (useInstances === void 0) { useInstances = false; }
  38236. if (subMesh.effect && this.isFrozen) {
  38237. if (this._wasPreviouslyReady && subMesh.effect) {
  38238. return true;
  38239. }
  38240. }
  38241. if (!subMesh._materialDefines) {
  38242. subMesh._materialDefines = new StandardMaterialDefines();
  38243. }
  38244. var scene = this.getScene();
  38245. var defines = subMesh._materialDefines;
  38246. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38247. if (defines._renderId === scene.getRenderId()) {
  38248. return true;
  38249. }
  38250. }
  38251. var engine = scene.getEngine();
  38252. // Lights
  38253. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38254. // Textures
  38255. if (defines._areTexturesDirty) {
  38256. defines._needUVs = false;
  38257. defines.MAINUV1 = false;
  38258. defines.MAINUV2 = false;
  38259. if (scene.texturesEnabled) {
  38260. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38261. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38262. return false;
  38263. }
  38264. else {
  38265. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38266. }
  38267. }
  38268. else {
  38269. defines.DIFFUSE = false;
  38270. }
  38271. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38272. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38273. return false;
  38274. }
  38275. else {
  38276. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38277. }
  38278. }
  38279. else {
  38280. defines.AMBIENT = false;
  38281. }
  38282. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38283. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38284. return false;
  38285. }
  38286. else {
  38287. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38288. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38289. }
  38290. }
  38291. else {
  38292. defines.OPACITY = false;
  38293. }
  38294. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38295. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38296. return false;
  38297. }
  38298. else {
  38299. defines._needNormals = true;
  38300. defines.REFLECTION = true;
  38301. defines.ROUGHNESS = (this._roughness > 0);
  38302. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38303. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38304. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38305. switch (this._reflectionTexture.coordinatesMode) {
  38306. case BABYLON.Texture.CUBIC_MODE:
  38307. case BABYLON.Texture.INVCUBIC_MODE:
  38308. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38309. break;
  38310. case BABYLON.Texture.EXPLICIT_MODE:
  38311. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38312. break;
  38313. case BABYLON.Texture.PLANAR_MODE:
  38314. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38315. break;
  38316. case BABYLON.Texture.PROJECTION_MODE:
  38317. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38318. break;
  38319. case BABYLON.Texture.SKYBOX_MODE:
  38320. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38321. break;
  38322. case BABYLON.Texture.SPHERICAL_MODE:
  38323. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38324. break;
  38325. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38326. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38327. break;
  38328. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38329. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38330. break;
  38331. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38332. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38333. break;
  38334. }
  38335. }
  38336. }
  38337. else {
  38338. defines.REFLECTION = false;
  38339. }
  38340. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38341. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38342. return false;
  38343. }
  38344. else {
  38345. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38346. }
  38347. }
  38348. else {
  38349. defines.EMISSIVE = false;
  38350. }
  38351. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38352. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38353. return false;
  38354. }
  38355. else {
  38356. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38357. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38358. }
  38359. }
  38360. else {
  38361. defines.LIGHTMAP = false;
  38362. }
  38363. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38364. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38365. return false;
  38366. }
  38367. else {
  38368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38369. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38370. }
  38371. }
  38372. else {
  38373. defines.SPECULAR = false;
  38374. }
  38375. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38376. // Bump texure can not be not blocking.
  38377. if (!this._bumpTexture.isReady()) {
  38378. return false;
  38379. }
  38380. else {
  38381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38382. defines.PARALLAX = this._useParallax;
  38383. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38384. }
  38385. }
  38386. else {
  38387. defines.BUMP = false;
  38388. }
  38389. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38390. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38391. return false;
  38392. }
  38393. else {
  38394. defines._needUVs = true;
  38395. defines.REFRACTION = true;
  38396. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38397. }
  38398. }
  38399. else {
  38400. defines.REFRACTION = false;
  38401. }
  38402. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38403. }
  38404. else {
  38405. defines.DIFFUSE = false;
  38406. defines.AMBIENT = false;
  38407. defines.OPACITY = false;
  38408. defines.REFLECTION = false;
  38409. defines.EMISSIVE = false;
  38410. defines.LIGHTMAP = false;
  38411. defines.BUMP = false;
  38412. defines.REFRACTION = false;
  38413. }
  38414. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38415. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38416. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38417. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38418. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38419. }
  38420. if (defines._areImageProcessingDirty) {
  38421. if (!this._imageProcessingConfiguration.isReady()) {
  38422. return false;
  38423. }
  38424. this._imageProcessingConfiguration.prepareDefines(defines);
  38425. }
  38426. if (defines._areFresnelDirty) {
  38427. if (StandardMaterial.FresnelEnabled) {
  38428. // Fresnel
  38429. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38430. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38431. this._reflectionFresnelParameters) {
  38432. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38433. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38434. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38435. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38436. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38437. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38438. defines._needNormals = true;
  38439. defines.FRESNEL = true;
  38440. }
  38441. }
  38442. else {
  38443. defines.FRESNEL = false;
  38444. }
  38445. }
  38446. // Misc.
  38447. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38448. // Attribs
  38449. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38450. // Values that need to be evaluated on every frame
  38451. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38452. // Get correct effect
  38453. if (defines.isDirty) {
  38454. defines.markAsProcessed();
  38455. scene.resetCachedMaterial();
  38456. // Fallbacks
  38457. var fallbacks = new BABYLON.EffectFallbacks();
  38458. if (defines.REFLECTION) {
  38459. fallbacks.addFallback(0, "REFLECTION");
  38460. }
  38461. if (defines.SPECULAR) {
  38462. fallbacks.addFallback(0, "SPECULAR");
  38463. }
  38464. if (defines.BUMP) {
  38465. fallbacks.addFallback(0, "BUMP");
  38466. }
  38467. if (defines.PARALLAX) {
  38468. fallbacks.addFallback(1, "PARALLAX");
  38469. }
  38470. if (defines.PARALLAXOCCLUSION) {
  38471. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38472. }
  38473. if (defines.SPECULAROVERALPHA) {
  38474. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38475. }
  38476. if (defines.FOG) {
  38477. fallbacks.addFallback(1, "FOG");
  38478. }
  38479. if (defines.POINTSIZE) {
  38480. fallbacks.addFallback(0, "POINTSIZE");
  38481. }
  38482. if (defines.LOGARITHMICDEPTH) {
  38483. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38484. }
  38485. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38486. if (defines.SPECULARTERM) {
  38487. fallbacks.addFallback(0, "SPECULARTERM");
  38488. }
  38489. if (defines.DIFFUSEFRESNEL) {
  38490. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38491. }
  38492. if (defines.OPACITYFRESNEL) {
  38493. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38494. }
  38495. if (defines.REFLECTIONFRESNEL) {
  38496. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38497. }
  38498. if (defines.EMISSIVEFRESNEL) {
  38499. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38500. }
  38501. if (defines.FRESNEL) {
  38502. fallbacks.addFallback(4, "FRESNEL");
  38503. }
  38504. //Attributes
  38505. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38506. if (defines.NORMAL) {
  38507. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38508. }
  38509. if (defines.UV1) {
  38510. attribs.push(BABYLON.VertexBuffer.UVKind);
  38511. }
  38512. if (defines.UV2) {
  38513. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38514. }
  38515. if (defines.VERTEXCOLOR) {
  38516. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38517. }
  38518. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38519. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38520. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38521. var shaderName = "default";
  38522. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38523. "vFogInfos", "vFogColor", "pointSize",
  38524. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38525. "mBones",
  38526. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38527. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38528. "logarithmicDepthConstant", "vTangentSpaceParams"
  38529. ];
  38530. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38531. var uniformBuffers = ["Material", "Scene"];
  38532. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38533. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38534. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38535. uniformsNames: uniforms,
  38536. uniformBuffersNames: uniformBuffers,
  38537. samplers: samplers,
  38538. defines: defines,
  38539. maxSimultaneousLights: this._maxSimultaneousLights
  38540. });
  38541. if (this.customShaderNameResolve) {
  38542. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38543. }
  38544. var join = defines.toString();
  38545. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38546. attributes: attribs,
  38547. uniformsNames: uniforms,
  38548. uniformBuffersNames: uniformBuffers,
  38549. samplers: samplers,
  38550. defines: join,
  38551. fallbacks: fallbacks,
  38552. onCompiled: this.onCompiled,
  38553. onError: this.onError,
  38554. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38555. }, engine), defines);
  38556. this.buildUniformLayout();
  38557. }
  38558. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38559. return false;
  38560. }
  38561. defines._renderId = scene.getRenderId();
  38562. this._wasPreviouslyReady = true;
  38563. return true;
  38564. };
  38565. StandardMaterial.prototype.buildUniformLayout = function () {
  38566. // Order is important !
  38567. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38568. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38569. this._uniformBuffer.addUniform("opacityParts", 4);
  38570. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38571. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38572. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38573. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38574. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38575. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38576. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38577. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38578. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38579. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38580. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38581. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38582. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38583. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38584. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38585. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38586. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38587. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38588. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38589. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38590. this._uniformBuffer.addUniform("specularMatrix", 16);
  38591. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38592. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38593. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38594. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38595. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38596. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38597. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38598. this._uniformBuffer.addUniform("pointSize", 1);
  38599. this._uniformBuffer.create();
  38600. };
  38601. StandardMaterial.prototype.unbind = function () {
  38602. if (this._activeEffect) {
  38603. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38604. this._activeEffect.setTexture("reflection2DSampler", null);
  38605. }
  38606. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38607. this._activeEffect.setTexture("refraction2DSampler", null);
  38608. }
  38609. }
  38610. _super.prototype.unbind.call(this);
  38611. };
  38612. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38613. var scene = this.getScene();
  38614. var defines = subMesh._materialDefines;
  38615. if (!defines) {
  38616. return;
  38617. }
  38618. var effect = subMesh.effect;
  38619. if (!effect) {
  38620. return;
  38621. }
  38622. this._activeEffect = effect;
  38623. // Matrices
  38624. this.bindOnlyWorldMatrix(world);
  38625. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38626. // Bones
  38627. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38628. if (mustRebind) {
  38629. this._uniformBuffer.bindToEffect(effect, "Material");
  38630. this.bindViewProjection(effect);
  38631. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38632. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38633. // Fresnel
  38634. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38635. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38636. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38637. }
  38638. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38639. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38640. }
  38641. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38642. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38643. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38644. }
  38645. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38646. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38647. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38648. }
  38649. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38650. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38651. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38652. }
  38653. }
  38654. // Textures
  38655. if (scene.texturesEnabled) {
  38656. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38657. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38658. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38659. }
  38660. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38661. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38662. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38663. }
  38664. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38665. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38666. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38667. }
  38668. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38669. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38670. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38671. }
  38672. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38673. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38674. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38675. }
  38676. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38677. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38678. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38679. }
  38680. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38681. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38682. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38683. }
  38684. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38685. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38686. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38687. if (scene._mirroredCameraPosition) {
  38688. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38689. }
  38690. else {
  38691. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38692. }
  38693. }
  38694. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38695. var depth = 1.0;
  38696. if (!this._refractionTexture.isCube) {
  38697. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  38698. if (this._refractionTexture.depth) {
  38699. depth = this._refractionTexture.depth;
  38700. }
  38701. }
  38702. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  38703. }
  38704. }
  38705. // Point size
  38706. if (this.pointsCloud) {
  38707. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38708. }
  38709. if (defines.SPECULARTERM) {
  38710. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  38711. }
  38712. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  38713. // Diffuse
  38714. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  38715. }
  38716. // Textures
  38717. if (scene.texturesEnabled) {
  38718. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38719. effect.setTexture("diffuseSampler", this._diffuseTexture);
  38720. }
  38721. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38722. effect.setTexture("ambientSampler", this._ambientTexture);
  38723. }
  38724. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38725. effect.setTexture("opacitySampler", this._opacityTexture);
  38726. }
  38727. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38728. if (this._reflectionTexture.isCube) {
  38729. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  38730. }
  38731. else {
  38732. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  38733. }
  38734. }
  38735. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38736. effect.setTexture("emissiveSampler", this._emissiveTexture);
  38737. }
  38738. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38739. effect.setTexture("lightmapSampler", this._lightmapTexture);
  38740. }
  38741. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38742. effect.setTexture("specularSampler", this._specularTexture);
  38743. }
  38744. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38745. effect.setTexture("bumpSampler", this._bumpTexture);
  38746. }
  38747. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38748. var depth = 1.0;
  38749. if (this._refractionTexture.isCube) {
  38750. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  38751. }
  38752. else {
  38753. effect.setTexture("refraction2DSampler", this._refractionTexture);
  38754. }
  38755. }
  38756. }
  38757. // Clip plane
  38758. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  38759. // Colors
  38760. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  38761. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  38762. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38763. }
  38764. if (mustRebind || !this.isFrozen) {
  38765. // Lights
  38766. if (scene.lightsEnabled && !this._disableLighting) {
  38767. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  38768. }
  38769. // View
  38770. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  38771. this.bindView(effect);
  38772. }
  38773. // Fog
  38774. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  38775. // Morph targets
  38776. if (defines.NUM_MORPH_INFLUENCERS) {
  38777. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  38778. }
  38779. // Log. depth
  38780. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  38781. // image processing
  38782. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  38783. this._imageProcessingConfiguration.bind(this._activeEffect);
  38784. }
  38785. }
  38786. this._uniformBuffer.update();
  38787. this._afterBind(mesh, this._activeEffect);
  38788. };
  38789. StandardMaterial.prototype.getAnimatables = function () {
  38790. var results = [];
  38791. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  38792. results.push(this._diffuseTexture);
  38793. }
  38794. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38795. results.push(this._ambientTexture);
  38796. }
  38797. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38798. results.push(this._opacityTexture);
  38799. }
  38800. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38801. results.push(this._reflectionTexture);
  38802. }
  38803. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38804. results.push(this._emissiveTexture);
  38805. }
  38806. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  38807. results.push(this._specularTexture);
  38808. }
  38809. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38810. results.push(this._bumpTexture);
  38811. }
  38812. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38813. results.push(this._lightmapTexture);
  38814. }
  38815. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38816. results.push(this._refractionTexture);
  38817. }
  38818. return results;
  38819. };
  38820. StandardMaterial.prototype.getActiveTextures = function () {
  38821. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38822. if (this._diffuseTexture) {
  38823. activeTextures.push(this._diffuseTexture);
  38824. }
  38825. if (this._ambientTexture) {
  38826. activeTextures.push(this._ambientTexture);
  38827. }
  38828. if (this._opacityTexture) {
  38829. activeTextures.push(this._opacityTexture);
  38830. }
  38831. if (this._reflectionTexture) {
  38832. activeTextures.push(this._reflectionTexture);
  38833. }
  38834. if (this._emissiveTexture) {
  38835. activeTextures.push(this._emissiveTexture);
  38836. }
  38837. if (this._specularTexture) {
  38838. activeTextures.push(this._specularTexture);
  38839. }
  38840. if (this._bumpTexture) {
  38841. activeTextures.push(this._bumpTexture);
  38842. }
  38843. if (this._lightmapTexture) {
  38844. activeTextures.push(this._lightmapTexture);
  38845. }
  38846. if (this._refractionTexture) {
  38847. activeTextures.push(this._refractionTexture);
  38848. }
  38849. return activeTextures;
  38850. };
  38851. StandardMaterial.prototype.hasTexture = function (texture) {
  38852. if (_super.prototype.hasTexture.call(this, texture)) {
  38853. return true;
  38854. }
  38855. if (this._diffuseTexture === texture) {
  38856. return true;
  38857. }
  38858. if (this._ambientTexture === texture) {
  38859. return true;
  38860. }
  38861. if (this._opacityTexture === texture) {
  38862. return true;
  38863. }
  38864. if (this._reflectionTexture === texture) {
  38865. return true;
  38866. }
  38867. if (this._emissiveTexture === texture) {
  38868. return true;
  38869. }
  38870. if (this._specularTexture === texture) {
  38871. return true;
  38872. }
  38873. if (this._bumpTexture === texture) {
  38874. return true;
  38875. }
  38876. if (this._lightmapTexture === texture) {
  38877. return true;
  38878. }
  38879. if (this._refractionTexture === texture) {
  38880. return true;
  38881. }
  38882. return false;
  38883. };
  38884. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38885. if (forceDisposeTextures) {
  38886. if (this._diffuseTexture) {
  38887. this._diffuseTexture.dispose();
  38888. }
  38889. if (this._ambientTexture) {
  38890. this._ambientTexture.dispose();
  38891. }
  38892. if (this._opacityTexture) {
  38893. this._opacityTexture.dispose();
  38894. }
  38895. if (this._reflectionTexture) {
  38896. this._reflectionTexture.dispose();
  38897. }
  38898. if (this._emissiveTexture) {
  38899. this._emissiveTexture.dispose();
  38900. }
  38901. if (this._specularTexture) {
  38902. this._specularTexture.dispose();
  38903. }
  38904. if (this._bumpTexture) {
  38905. this._bumpTexture.dispose();
  38906. }
  38907. if (this._lightmapTexture) {
  38908. this._lightmapTexture.dispose();
  38909. }
  38910. if (this._refractionTexture) {
  38911. this._refractionTexture.dispose();
  38912. }
  38913. }
  38914. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38915. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38916. }
  38917. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38918. };
  38919. StandardMaterial.prototype.clone = function (name) {
  38920. var _this = this;
  38921. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  38922. result.name = name;
  38923. result.id = name;
  38924. return result;
  38925. };
  38926. StandardMaterial.prototype.serialize = function () {
  38927. return BABYLON.SerializationHelper.Serialize(this);
  38928. };
  38929. // Statics
  38930. StandardMaterial.Parse = function (source, scene, rootUrl) {
  38931. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  38932. };
  38933. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  38934. get: function () {
  38935. return StandardMaterial._DiffuseTextureEnabled;
  38936. },
  38937. set: function (value) {
  38938. if (StandardMaterial._DiffuseTextureEnabled === value) {
  38939. return;
  38940. }
  38941. StandardMaterial._DiffuseTextureEnabled = value;
  38942. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38943. },
  38944. enumerable: true,
  38945. configurable: true
  38946. });
  38947. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  38948. get: function () {
  38949. return StandardMaterial._AmbientTextureEnabled;
  38950. },
  38951. set: function (value) {
  38952. if (StandardMaterial._AmbientTextureEnabled === value) {
  38953. return;
  38954. }
  38955. StandardMaterial._AmbientTextureEnabled = value;
  38956. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38957. },
  38958. enumerable: true,
  38959. configurable: true
  38960. });
  38961. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  38962. get: function () {
  38963. return StandardMaterial._OpacityTextureEnabled;
  38964. },
  38965. set: function (value) {
  38966. if (StandardMaterial._OpacityTextureEnabled === value) {
  38967. return;
  38968. }
  38969. StandardMaterial._OpacityTextureEnabled = value;
  38970. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38971. },
  38972. enumerable: true,
  38973. configurable: true
  38974. });
  38975. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  38976. get: function () {
  38977. return StandardMaterial._ReflectionTextureEnabled;
  38978. },
  38979. set: function (value) {
  38980. if (StandardMaterial._ReflectionTextureEnabled === value) {
  38981. return;
  38982. }
  38983. StandardMaterial._ReflectionTextureEnabled = value;
  38984. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38985. },
  38986. enumerable: true,
  38987. configurable: true
  38988. });
  38989. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  38990. get: function () {
  38991. return StandardMaterial._EmissiveTextureEnabled;
  38992. },
  38993. set: function (value) {
  38994. if (StandardMaterial._EmissiveTextureEnabled === value) {
  38995. return;
  38996. }
  38997. StandardMaterial._EmissiveTextureEnabled = value;
  38998. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38999. },
  39000. enumerable: true,
  39001. configurable: true
  39002. });
  39003. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39004. get: function () {
  39005. return StandardMaterial._SpecularTextureEnabled;
  39006. },
  39007. set: function (value) {
  39008. if (StandardMaterial._SpecularTextureEnabled === value) {
  39009. return;
  39010. }
  39011. StandardMaterial._SpecularTextureEnabled = value;
  39012. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39013. },
  39014. enumerable: true,
  39015. configurable: true
  39016. });
  39017. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39018. get: function () {
  39019. return StandardMaterial._BumpTextureEnabled;
  39020. },
  39021. set: function (value) {
  39022. if (StandardMaterial._BumpTextureEnabled === value) {
  39023. return;
  39024. }
  39025. StandardMaterial._BumpTextureEnabled = value;
  39026. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39027. },
  39028. enumerable: true,
  39029. configurable: true
  39030. });
  39031. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39032. get: function () {
  39033. return StandardMaterial._LightmapTextureEnabled;
  39034. },
  39035. set: function (value) {
  39036. if (StandardMaterial._LightmapTextureEnabled === value) {
  39037. return;
  39038. }
  39039. StandardMaterial._LightmapTextureEnabled = value;
  39040. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39041. },
  39042. enumerable: true,
  39043. configurable: true
  39044. });
  39045. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39046. get: function () {
  39047. return StandardMaterial._RefractionTextureEnabled;
  39048. },
  39049. set: function (value) {
  39050. if (StandardMaterial._RefractionTextureEnabled === value) {
  39051. return;
  39052. }
  39053. StandardMaterial._RefractionTextureEnabled = value;
  39054. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39055. },
  39056. enumerable: true,
  39057. configurable: true
  39058. });
  39059. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39060. get: function () {
  39061. return StandardMaterial._ColorGradingTextureEnabled;
  39062. },
  39063. set: function (value) {
  39064. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39065. return;
  39066. }
  39067. StandardMaterial._ColorGradingTextureEnabled = value;
  39068. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39069. },
  39070. enumerable: true,
  39071. configurable: true
  39072. });
  39073. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39074. get: function () {
  39075. return StandardMaterial._FresnelEnabled;
  39076. },
  39077. set: function (value) {
  39078. if (StandardMaterial._FresnelEnabled === value) {
  39079. return;
  39080. }
  39081. StandardMaterial._FresnelEnabled = value;
  39082. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39083. },
  39084. enumerable: true,
  39085. configurable: true
  39086. });
  39087. // Flags used to enable or disable a type of texture for all Standard Materials
  39088. StandardMaterial._DiffuseTextureEnabled = true;
  39089. StandardMaterial._AmbientTextureEnabled = true;
  39090. StandardMaterial._OpacityTextureEnabled = true;
  39091. StandardMaterial._ReflectionTextureEnabled = true;
  39092. StandardMaterial._EmissiveTextureEnabled = true;
  39093. StandardMaterial._SpecularTextureEnabled = true;
  39094. StandardMaterial._BumpTextureEnabled = true;
  39095. StandardMaterial._LightmapTextureEnabled = true;
  39096. StandardMaterial._RefractionTextureEnabled = true;
  39097. StandardMaterial._ColorGradingTextureEnabled = true;
  39098. StandardMaterial._FresnelEnabled = true;
  39099. __decorate([
  39100. BABYLON.serializeAsTexture("diffuseTexture")
  39101. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39102. __decorate([
  39103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39104. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39105. __decorate([
  39106. BABYLON.serializeAsTexture("ambientTexture")
  39107. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39108. __decorate([
  39109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39110. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39111. __decorate([
  39112. BABYLON.serializeAsTexture("opacityTexture")
  39113. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39114. __decorate([
  39115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39116. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39117. __decorate([
  39118. BABYLON.serializeAsTexture("reflectionTexture")
  39119. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39120. __decorate([
  39121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39122. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39123. __decorate([
  39124. BABYLON.serializeAsTexture("emissiveTexture")
  39125. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39126. __decorate([
  39127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39128. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39129. __decorate([
  39130. BABYLON.serializeAsTexture("specularTexture")
  39131. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39132. __decorate([
  39133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39134. ], StandardMaterial.prototype, "specularTexture", void 0);
  39135. __decorate([
  39136. BABYLON.serializeAsTexture("bumpTexture")
  39137. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39138. __decorate([
  39139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39140. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39141. __decorate([
  39142. BABYLON.serializeAsTexture("lightmapTexture")
  39143. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39144. __decorate([
  39145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39146. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39147. __decorate([
  39148. BABYLON.serializeAsTexture("refractionTexture")
  39149. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39150. __decorate([
  39151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39152. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39153. __decorate([
  39154. BABYLON.serializeAsColor3("ambient")
  39155. ], StandardMaterial.prototype, "ambientColor", void 0);
  39156. __decorate([
  39157. BABYLON.serializeAsColor3("diffuse")
  39158. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39159. __decorate([
  39160. BABYLON.serializeAsColor3("specular")
  39161. ], StandardMaterial.prototype, "specularColor", void 0);
  39162. __decorate([
  39163. BABYLON.serializeAsColor3("emissive")
  39164. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39165. __decorate([
  39166. BABYLON.serialize()
  39167. ], StandardMaterial.prototype, "specularPower", void 0);
  39168. __decorate([
  39169. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39170. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39171. __decorate([
  39172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39173. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39174. __decorate([
  39175. BABYLON.serialize("useEmissiveAsIllumination")
  39176. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39177. __decorate([
  39178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39179. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39180. __decorate([
  39181. BABYLON.serialize("linkEmissiveWithDiffuse")
  39182. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39183. __decorate([
  39184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39185. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39186. __decorate([
  39187. BABYLON.serialize("useSpecularOverAlpha")
  39188. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39189. __decorate([
  39190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39191. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39192. __decorate([
  39193. BABYLON.serialize("useReflectionOverAlpha")
  39194. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39195. __decorate([
  39196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39197. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39198. __decorate([
  39199. BABYLON.serialize("disableLighting")
  39200. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39201. __decorate([
  39202. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39203. ], StandardMaterial.prototype, "disableLighting", void 0);
  39204. __decorate([
  39205. BABYLON.serialize("useParallax")
  39206. ], StandardMaterial.prototype, "_useParallax", void 0);
  39207. __decorate([
  39208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39209. ], StandardMaterial.prototype, "useParallax", void 0);
  39210. __decorate([
  39211. BABYLON.serialize("useParallaxOcclusion")
  39212. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39213. __decorate([
  39214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39215. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39216. __decorate([
  39217. BABYLON.serialize()
  39218. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39219. __decorate([
  39220. BABYLON.serialize("roughness")
  39221. ], StandardMaterial.prototype, "_roughness", void 0);
  39222. __decorate([
  39223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39224. ], StandardMaterial.prototype, "roughness", void 0);
  39225. __decorate([
  39226. BABYLON.serialize()
  39227. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39228. __decorate([
  39229. BABYLON.serialize()
  39230. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39231. __decorate([
  39232. BABYLON.serialize("useLightmapAsShadowmap")
  39233. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39234. __decorate([
  39235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39236. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39237. __decorate([
  39238. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39239. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39240. __decorate([
  39241. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39242. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39243. __decorate([
  39244. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39245. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39246. __decorate([
  39247. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39248. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39249. __decorate([
  39250. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39251. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39252. __decorate([
  39253. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39254. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39255. __decorate([
  39256. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39257. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39258. __decorate([
  39259. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39260. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39261. __decorate([
  39262. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39263. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39264. __decorate([
  39265. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39266. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39267. __decorate([
  39268. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39269. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39270. __decorate([
  39271. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39272. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39273. __decorate([
  39274. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39275. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39276. __decorate([
  39277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39278. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39279. __decorate([
  39280. BABYLON.serialize("maxSimultaneousLights")
  39281. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39282. __decorate([
  39283. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39284. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39285. __decorate([
  39286. BABYLON.serialize("invertNormalMapX")
  39287. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39288. __decorate([
  39289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39290. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39291. __decorate([
  39292. BABYLON.serialize("invertNormalMapY")
  39293. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39294. __decorate([
  39295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39296. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39297. __decorate([
  39298. BABYLON.serialize("twoSidedLighting")
  39299. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39300. __decorate([
  39301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39302. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39303. __decorate([
  39304. BABYLON.serialize()
  39305. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39306. return StandardMaterial;
  39307. }(BABYLON.PushMaterial));
  39308. BABYLON.StandardMaterial = StandardMaterial;
  39309. })(BABYLON || (BABYLON = {}));
  39310. //# sourceMappingURL=babylon.standardMaterial.js.map
  39311. var BABYLON;
  39312. (function (BABYLON) {
  39313. /**
  39314. * Manages the defines for the PBR Material.
  39315. */
  39316. var PBRMaterialDefines = /** @class */ (function (_super) {
  39317. __extends(PBRMaterialDefines, _super);
  39318. /**
  39319. * Initializes the PBR Material defines.
  39320. */
  39321. function PBRMaterialDefines() {
  39322. var _this = _super.call(this) || this;
  39323. _this.PBR = true;
  39324. _this.MAINUV1 = false;
  39325. _this.MAINUV2 = false;
  39326. _this.UV1 = false;
  39327. _this.UV2 = false;
  39328. _this.ALBEDO = false;
  39329. _this.ALBEDODIRECTUV = 0;
  39330. _this.VERTEXCOLOR = false;
  39331. _this.AMBIENT = false;
  39332. _this.AMBIENTDIRECTUV = 0;
  39333. _this.AMBIENTINGRAYSCALE = false;
  39334. _this.OPACITY = false;
  39335. _this.VERTEXALPHA = false;
  39336. _this.OPACITYDIRECTUV = 0;
  39337. _this.OPACITYRGB = false;
  39338. _this.ALPHATEST = false;
  39339. _this.DEPTHPREPASS = false;
  39340. _this.ALPHABLEND = false;
  39341. _this.ALPHAFROMALBEDO = false;
  39342. _this.ALPHATESTVALUE = 0.5;
  39343. _this.SPECULAROVERALPHA = false;
  39344. _this.RADIANCEOVERALPHA = false;
  39345. _this.ALPHAFRESNEL = false;
  39346. _this.LINEARALPHAFRESNEL = false;
  39347. _this.PREMULTIPLYALPHA = false;
  39348. _this.EMISSIVE = false;
  39349. _this.EMISSIVEDIRECTUV = 0;
  39350. _this.REFLECTIVITY = false;
  39351. _this.REFLECTIVITYDIRECTUV = 0;
  39352. _this.SPECULARTERM = false;
  39353. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39354. _this.MICROSURFACEAUTOMATIC = false;
  39355. _this.LODBASEDMICROSFURACE = false;
  39356. _this.MICROSURFACEMAP = false;
  39357. _this.MICROSURFACEMAPDIRECTUV = 0;
  39358. _this.METALLICWORKFLOW = false;
  39359. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39360. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39361. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39362. _this.AOSTOREINMETALMAPRED = false;
  39363. _this.ENVIRONMENTBRDF = false;
  39364. _this.NORMAL = false;
  39365. _this.TANGENT = false;
  39366. _this.BUMP = false;
  39367. _this.BUMPDIRECTUV = 0;
  39368. _this.PARALLAX = false;
  39369. _this.PARALLAXOCCLUSION = false;
  39370. _this.NORMALXYSCALE = true;
  39371. _this.LIGHTMAP = false;
  39372. _this.LIGHTMAPDIRECTUV = 0;
  39373. _this.USELIGHTMAPASSHADOWMAP = false;
  39374. _this.REFLECTION = false;
  39375. _this.REFLECTIONMAP_3D = false;
  39376. _this.REFLECTIONMAP_SPHERICAL = false;
  39377. _this.REFLECTIONMAP_PLANAR = false;
  39378. _this.REFLECTIONMAP_CUBIC = false;
  39379. _this.REFLECTIONMAP_PROJECTION = false;
  39380. _this.REFLECTIONMAP_SKYBOX = false;
  39381. _this.REFLECTIONMAP_EXPLICIT = false;
  39382. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39383. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39384. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39385. _this.INVERTCUBICMAP = false;
  39386. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39387. _this.USESPHERICALINVERTEX = false;
  39388. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39389. _this.LODINREFLECTIONALPHA = false;
  39390. _this.GAMMAREFLECTION = false;
  39391. _this.RADIANCEOCCLUSION = false;
  39392. _this.HORIZONOCCLUSION = false;
  39393. _this.REFRACTION = false;
  39394. _this.REFRACTIONMAP_3D = false;
  39395. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39396. _this.LODINREFRACTIONALPHA = false;
  39397. _this.GAMMAREFRACTION = false;
  39398. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39399. _this.INSTANCES = false;
  39400. _this.NUM_BONE_INFLUENCERS = 0;
  39401. _this.BonesPerMesh = 0;
  39402. _this.NONUNIFORMSCALING = false;
  39403. _this.MORPHTARGETS = false;
  39404. _this.MORPHTARGETS_NORMAL = false;
  39405. _this.MORPHTARGETS_TANGENT = false;
  39406. _this.NUM_MORPH_INFLUENCERS = 0;
  39407. _this.IMAGEPROCESSING = false;
  39408. _this.VIGNETTE = false;
  39409. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39410. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39411. _this.TONEMAPPING = false;
  39412. _this.CONTRAST = false;
  39413. _this.COLORCURVES = false;
  39414. _this.COLORGRADING = false;
  39415. _this.COLORGRADING3D = false;
  39416. _this.SAMPLER3DGREENDEPTH = false;
  39417. _this.SAMPLER3DBGRMAP = false;
  39418. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39419. _this.EXPOSURE = false;
  39420. _this.USEPHYSICALLIGHTFALLOFF = false;
  39421. _this.TWOSIDEDLIGHTING = false;
  39422. _this.SHADOWFLOAT = false;
  39423. _this.CLIPPLANE = false;
  39424. _this.POINTSIZE = false;
  39425. _this.FOG = false;
  39426. _this.LOGARITHMICDEPTH = false;
  39427. _this.FORCENORMALFORWARD = false;
  39428. _this.rebuild();
  39429. return _this;
  39430. }
  39431. /**
  39432. * Resets the PBR Material defines.
  39433. */
  39434. PBRMaterialDefines.prototype.reset = function () {
  39435. _super.prototype.reset.call(this);
  39436. this.ALPHATESTVALUE = 0.5;
  39437. this.PBR = true;
  39438. };
  39439. return PBRMaterialDefines;
  39440. }(BABYLON.MaterialDefines));
  39441. /**
  39442. * The Physically based material base class of BJS.
  39443. *
  39444. * This offers the main features of a standard PBR material.
  39445. * For more information, please refer to the documentation :
  39446. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39447. */
  39448. var PBRBaseMaterial = /** @class */ (function (_super) {
  39449. __extends(PBRBaseMaterial, _super);
  39450. /**
  39451. * Instantiates a new PBRMaterial instance.
  39452. *
  39453. * @param name The material name
  39454. * @param scene The scene the material will be use in.
  39455. */
  39456. function PBRBaseMaterial(name, scene) {
  39457. var _this = _super.call(this, name, scene) || this;
  39458. /**
  39459. * Intensity of the direct lights e.g. the four lights available in your scene.
  39460. * This impacts both the direct diffuse and specular highlights.
  39461. */
  39462. _this._directIntensity = 1.0;
  39463. /**
  39464. * Intensity of the emissive part of the material.
  39465. * This helps controlling the emissive effect without modifying the emissive color.
  39466. */
  39467. _this._emissiveIntensity = 1.0;
  39468. /**
  39469. * Intensity of the environment e.g. how much the environment will light the object
  39470. * either through harmonics for rough material or through the refelction for shiny ones.
  39471. */
  39472. _this._environmentIntensity = 1.0;
  39473. /**
  39474. * This is a special control allowing the reduction of the specular highlights coming from the
  39475. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39476. */
  39477. _this._specularIntensity = 1.0;
  39478. /**
  39479. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39480. */
  39481. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39482. /**
  39483. * Debug Control allowing disabling the bump map on this material.
  39484. */
  39485. _this._disableBumpMap = false;
  39486. /**
  39487. * AKA Occlusion Texture Intensity in other nomenclature.
  39488. */
  39489. _this._ambientTextureStrength = 1.0;
  39490. /**
  39491. * The color of a material in ambient lighting.
  39492. */
  39493. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39494. /**
  39495. * AKA Diffuse Color in other nomenclature.
  39496. */
  39497. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39498. /**
  39499. * AKA Specular Color in other nomenclature.
  39500. */
  39501. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39502. /**
  39503. * The color applied when light is reflected from a material.
  39504. */
  39505. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39506. /**
  39507. * The color applied when light is emitted from a material.
  39508. */
  39509. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39510. /**
  39511. * AKA Glossiness in other nomenclature.
  39512. */
  39513. _this._microSurface = 0.9;
  39514. /**
  39515. * source material index of refraction (IOR)' / 'destination material IOR.
  39516. */
  39517. _this._indexOfRefraction = 0.66;
  39518. /**
  39519. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39520. */
  39521. _this._invertRefractionY = false;
  39522. /**
  39523. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39524. * Materials half opaque for instance using refraction could benefit from this control.
  39525. */
  39526. _this._linkRefractionWithTransparency = false;
  39527. /**
  39528. * Specifies that the material will use the light map as a show map.
  39529. */
  39530. _this._useLightmapAsShadowmap = false;
  39531. /**
  39532. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39533. * makes the reflect vector face the model (under horizon).
  39534. */
  39535. _this._useHorizonOcclusion = true;
  39536. /**
  39537. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39538. * too much the area relying on ambient texture to define their ambient occlusion.
  39539. */
  39540. _this._useRadianceOcclusion = true;
  39541. /**
  39542. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39543. */
  39544. _this._useAlphaFromAlbedoTexture = false;
  39545. /**
  39546. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39547. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39548. */
  39549. _this._useSpecularOverAlpha = true;
  39550. /**
  39551. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39552. */
  39553. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39554. /**
  39555. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39556. */
  39557. _this._useRoughnessFromMetallicTextureAlpha = true;
  39558. /**
  39559. * Specifies if the metallic texture contains the roughness information in its green channel.
  39560. */
  39561. _this._useRoughnessFromMetallicTextureGreen = false;
  39562. /**
  39563. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39564. */
  39565. _this._useMetallnessFromMetallicTextureBlue = false;
  39566. /**
  39567. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39568. */
  39569. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39570. /**
  39571. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39572. */
  39573. _this._useAmbientInGrayScale = false;
  39574. /**
  39575. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39576. * The material will try to infer what glossiness each pixel should be.
  39577. */
  39578. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39579. /**
  39580. * BJS is using an harcoded light falloff based on a manually sets up range.
  39581. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39582. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39583. */
  39584. _this._usePhysicalLightFalloff = true;
  39585. /**
  39586. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39587. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39588. */
  39589. _this._useRadianceOverAlpha = true;
  39590. /**
  39591. * Allows using the bump map in parallax mode.
  39592. */
  39593. _this._useParallax = false;
  39594. /**
  39595. * Allows using the bump map in parallax occlusion mode.
  39596. */
  39597. _this._useParallaxOcclusion = false;
  39598. /**
  39599. * Controls the scale bias of the parallax mode.
  39600. */
  39601. _this._parallaxScaleBias = 0.05;
  39602. /**
  39603. * If sets to true, disables all the lights affecting the material.
  39604. */
  39605. _this._disableLighting = false;
  39606. /**
  39607. * Number of Simultaneous lights allowed on the material.
  39608. */
  39609. _this._maxSimultaneousLights = 4;
  39610. /**
  39611. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39612. */
  39613. _this._invertNormalMapX = false;
  39614. /**
  39615. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39616. */
  39617. _this._invertNormalMapY = false;
  39618. /**
  39619. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39620. */
  39621. _this._twoSidedLighting = false;
  39622. /**
  39623. * Defines the alpha limits in alpha test mode.
  39624. */
  39625. _this._alphaCutOff = 0.4;
  39626. /**
  39627. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39628. */
  39629. _this._forceAlphaTest = false;
  39630. /**
  39631. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39632. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39633. */
  39634. _this._useAlphaFresnel = false;
  39635. /**
  39636. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39637. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39638. */
  39639. _this._useLinearAlphaFresnel = false;
  39640. /**
  39641. * The transparency mode of the material.
  39642. */
  39643. _this._transparencyMode = null;
  39644. /**
  39645. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39646. * from cos thetav and roughness:
  39647. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39648. */
  39649. _this._environmentBRDFTexture = null;
  39650. /**
  39651. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39652. */
  39653. _this._forceIrradianceInFragment = false;
  39654. /**
  39655. * Force normal to face away from face.
  39656. */
  39657. _this._forceNormalForward = false;
  39658. /**
  39659. * Force metallic workflow.
  39660. */
  39661. _this._forceMetallicWorkflow = false;
  39662. /**
  39663. * Stores the available render targets.
  39664. */
  39665. _this._renderTargets = new BABYLON.SmartArray(16);
  39666. /**
  39667. * Sets the global ambient color for the material used in lighting calculations.
  39668. */
  39669. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39670. // Setup the default processing configuration to the scene.
  39671. _this._attachImageProcessingConfiguration(null);
  39672. _this.getRenderTargetTextures = function () {
  39673. _this._renderTargets.reset();
  39674. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39675. _this._renderTargets.push(_this._reflectionTexture);
  39676. }
  39677. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39678. _this._renderTargets.push(_this._refractionTexture);
  39679. }
  39680. return _this._renderTargets;
  39681. };
  39682. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39683. return _this;
  39684. }
  39685. /**
  39686. * Attaches a new image processing configuration to the PBR Material.
  39687. * @param configuration
  39688. */
  39689. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39690. var _this = this;
  39691. if (configuration === this._imageProcessingConfiguration) {
  39692. return;
  39693. }
  39694. // Detaches observer.
  39695. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39696. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39697. }
  39698. // Pick the scene configuration if needed.
  39699. if (!configuration) {
  39700. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39701. }
  39702. else {
  39703. this._imageProcessingConfiguration = configuration;
  39704. }
  39705. // Attaches observer.
  39706. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39707. _this._markAllSubMeshesAsImageProcessingDirty();
  39708. });
  39709. };
  39710. /**
  39711. * Gets the name of the material class.
  39712. */
  39713. PBRBaseMaterial.prototype.getClassName = function () {
  39714. return "PBRBaseMaterial";
  39715. };
  39716. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  39717. /**
  39718. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39719. */
  39720. get: function () {
  39721. return this._useLogarithmicDepth;
  39722. },
  39723. /**
  39724. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39725. */
  39726. set: function (value) {
  39727. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39728. },
  39729. enumerable: true,
  39730. configurable: true
  39731. });
  39732. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  39733. /**
  39734. * Gets the current transparency mode.
  39735. */
  39736. get: function () {
  39737. return this._transparencyMode;
  39738. },
  39739. /**
  39740. * Sets the transparency mode of the material.
  39741. */
  39742. set: function (value) {
  39743. if (this._transparencyMode === value) {
  39744. return;
  39745. }
  39746. this._transparencyMode = value;
  39747. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  39748. this._markAllSubMeshesAsTexturesAndMiscDirty();
  39749. },
  39750. enumerable: true,
  39751. configurable: true
  39752. });
  39753. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  39754. /**
  39755. * Returns true if alpha blending should be disabled.
  39756. */
  39757. get: function () {
  39758. return (this._linkRefractionWithTransparency ||
  39759. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  39760. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39761. },
  39762. enumerable: true,
  39763. configurable: true
  39764. });
  39765. /**
  39766. * Specifies whether or not this material should be rendered in alpha blend mode.
  39767. */
  39768. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  39769. if (this._disableAlphaBlending) {
  39770. return false;
  39771. }
  39772. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  39773. };
  39774. /**
  39775. * Specifies if the mesh will require alpha blending.
  39776. * @param mesh - BJS mesh.
  39777. */
  39778. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  39779. if (this._disableAlphaBlending) {
  39780. return false;
  39781. }
  39782. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  39783. };
  39784. /**
  39785. * Specifies whether or not this material should be rendered in alpha test mode.
  39786. */
  39787. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  39788. if (this._forceAlphaTest) {
  39789. return true;
  39790. }
  39791. if (this._linkRefractionWithTransparency) {
  39792. return false;
  39793. }
  39794. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39795. };
  39796. /**
  39797. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  39798. */
  39799. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  39800. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39801. };
  39802. /**
  39803. * Gets the texture used for the alpha test.
  39804. */
  39805. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  39806. return this._albedoTexture;
  39807. };
  39808. /**
  39809. * Specifies that the submesh is ready to be used.
  39810. * @param mesh - BJS mesh.
  39811. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  39812. * @param useInstances - Specifies that instances should be used.
  39813. * @returns - boolean indicating that the submesh is ready or not.
  39814. */
  39815. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39816. var _this = this;
  39817. if (subMesh.effect && this.isFrozen) {
  39818. if (this._wasPreviouslyReady) {
  39819. return true;
  39820. }
  39821. }
  39822. if (!subMesh._materialDefines) {
  39823. subMesh._materialDefines = new PBRMaterialDefines();
  39824. }
  39825. var scene = this.getScene();
  39826. var defines = subMesh._materialDefines;
  39827. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39828. if (defines._renderId === scene.getRenderId()) {
  39829. return true;
  39830. }
  39831. }
  39832. var engine = scene.getEngine();
  39833. // Lights
  39834. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39835. defines._needNormals = true;
  39836. // Textures
  39837. if (defines._areTexturesDirty) {
  39838. defines._needUVs = false;
  39839. if (scene.texturesEnabled) {
  39840. if (scene.getEngine().getCaps().textureLOD) {
  39841. defines.LODBASEDMICROSFURACE = true;
  39842. }
  39843. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39844. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  39845. return false;
  39846. }
  39847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  39848. }
  39849. else {
  39850. defines.ALBEDO = false;
  39851. }
  39852. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39853. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39854. return false;
  39855. }
  39856. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39857. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  39858. }
  39859. else {
  39860. defines.AMBIENT = false;
  39861. }
  39862. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39863. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39864. return false;
  39865. }
  39866. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39867. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39868. }
  39869. else {
  39870. defines.OPACITY = false;
  39871. }
  39872. var reflectionTexture = this._getReflectionTexture();
  39873. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39874. if (!reflectionTexture.isReadyOrNotBlocking()) {
  39875. return false;
  39876. }
  39877. defines.REFLECTION = true;
  39878. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  39879. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  39880. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  39881. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  39882. defines.INVERTCUBICMAP = true;
  39883. }
  39884. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  39885. switch (reflectionTexture.coordinatesMode) {
  39886. case BABYLON.Texture.CUBIC_MODE:
  39887. case BABYLON.Texture.INVCUBIC_MODE:
  39888. defines.REFLECTIONMAP_CUBIC = true;
  39889. break;
  39890. case BABYLON.Texture.EXPLICIT_MODE:
  39891. defines.REFLECTIONMAP_EXPLICIT = true;
  39892. break;
  39893. case BABYLON.Texture.PLANAR_MODE:
  39894. defines.REFLECTIONMAP_PLANAR = true;
  39895. break;
  39896. case BABYLON.Texture.PROJECTION_MODE:
  39897. defines.REFLECTIONMAP_PROJECTION = true;
  39898. break;
  39899. case BABYLON.Texture.SKYBOX_MODE:
  39900. defines.REFLECTIONMAP_SKYBOX = true;
  39901. break;
  39902. case BABYLON.Texture.SPHERICAL_MODE:
  39903. defines.REFLECTIONMAP_SPHERICAL = true;
  39904. break;
  39905. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39906. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  39907. break;
  39908. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39909. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  39910. break;
  39911. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39912. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  39913. break;
  39914. }
  39915. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  39916. if (reflectionTexture.sphericalPolynomial) {
  39917. defines.USESPHERICALFROMREFLECTIONMAP = true;
  39918. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  39919. defines.USESPHERICALINVERTEX = false;
  39920. }
  39921. else {
  39922. defines.USESPHERICALINVERTEX = true;
  39923. }
  39924. }
  39925. }
  39926. }
  39927. else {
  39928. defines.REFLECTION = false;
  39929. defines.REFLECTIONMAP_3D = false;
  39930. defines.REFLECTIONMAP_SPHERICAL = false;
  39931. defines.REFLECTIONMAP_PLANAR = false;
  39932. defines.REFLECTIONMAP_CUBIC = false;
  39933. defines.REFLECTIONMAP_PROJECTION = false;
  39934. defines.REFLECTIONMAP_SKYBOX = false;
  39935. defines.REFLECTIONMAP_EXPLICIT = false;
  39936. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39937. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39938. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39939. defines.INVERTCUBICMAP = false;
  39940. defines.USESPHERICALFROMREFLECTIONMAP = false;
  39941. defines.USESPHERICALINVERTEX = false;
  39942. defines.REFLECTIONMAP_OPPOSITEZ = false;
  39943. defines.LODINREFLECTIONALPHA = false;
  39944. defines.GAMMAREFLECTION = false;
  39945. }
  39946. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39947. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39948. return false;
  39949. }
  39950. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39951. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39952. }
  39953. else {
  39954. defines.LIGHTMAP = false;
  39955. }
  39956. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39957. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39958. return false;
  39959. }
  39960. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39961. }
  39962. else {
  39963. defines.EMISSIVE = false;
  39964. }
  39965. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39966. if (this._metallicTexture) {
  39967. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  39968. return false;
  39969. }
  39970. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  39971. defines.METALLICWORKFLOW = true;
  39972. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  39973. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  39974. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  39975. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  39976. }
  39977. else if (this._reflectivityTexture) {
  39978. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  39979. return false;
  39980. }
  39981. defines.METALLICWORKFLOW = false;
  39982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  39983. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  39984. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  39985. }
  39986. else {
  39987. defines.METALLICWORKFLOW = false;
  39988. defines.REFLECTIVITY = false;
  39989. }
  39990. if (this._microSurfaceTexture) {
  39991. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  39992. return false;
  39993. }
  39994. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  39995. }
  39996. else {
  39997. defines.MICROSURFACEMAP = false;
  39998. }
  39999. }
  40000. else {
  40001. defines.REFLECTIVITY = false;
  40002. defines.MICROSURFACEMAP = false;
  40003. }
  40004. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40005. // Bump texure can not be none blocking.
  40006. if (!this._bumpTexture.isReady()) {
  40007. return false;
  40008. }
  40009. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40010. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40011. defines.PARALLAX = true;
  40012. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40013. }
  40014. else {
  40015. defines.PARALLAX = false;
  40016. }
  40017. }
  40018. else {
  40019. defines.BUMP = false;
  40020. }
  40021. var refractionTexture = this._getRefractionTexture();
  40022. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40023. if (!refractionTexture.isReadyOrNotBlocking()) {
  40024. return false;
  40025. }
  40026. defines.REFRACTION = true;
  40027. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40028. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40029. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40030. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40031. if (this._linkRefractionWithTransparency) {
  40032. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40033. }
  40034. }
  40035. else {
  40036. defines.REFRACTION = false;
  40037. }
  40038. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40039. // This is blocking.
  40040. if (!this._environmentBRDFTexture.isReady()) {
  40041. return false;
  40042. }
  40043. defines.ENVIRONMENTBRDF = true;
  40044. }
  40045. else {
  40046. defines.ENVIRONMENTBRDF = false;
  40047. }
  40048. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40049. defines.ALPHAFROMALBEDO = true;
  40050. }
  40051. else {
  40052. defines.ALPHAFROMALBEDO = false;
  40053. }
  40054. }
  40055. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40056. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40057. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40058. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40059. defines.METALLICWORKFLOW = true;
  40060. }
  40061. else {
  40062. defines.METALLICWORKFLOW = false;
  40063. }
  40064. if (!this.backFaceCulling && this._twoSidedLighting) {
  40065. defines.TWOSIDEDLIGHTING = true;
  40066. }
  40067. else {
  40068. defines.TWOSIDEDLIGHTING = false;
  40069. }
  40070. defines.ALPHATESTVALUE = this._alphaCutOff;
  40071. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40072. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40073. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40074. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40075. }
  40076. if (defines._areImageProcessingDirty) {
  40077. if (!this._imageProcessingConfiguration.isReady()) {
  40078. return false;
  40079. }
  40080. this._imageProcessingConfiguration.prepareDefines(defines);
  40081. }
  40082. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40083. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40084. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40085. // Misc.
  40086. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40087. // Values that need to be evaluated on every frame
  40088. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  40089. // Attribs
  40090. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  40091. var bufferMesh = null;
  40092. if (mesh instanceof BABYLON.InstancedMesh) {
  40093. bufferMesh = mesh.sourceMesh;
  40094. }
  40095. else if (mesh instanceof BABYLON.Mesh) {
  40096. bufferMesh = mesh;
  40097. }
  40098. if (bufferMesh) {
  40099. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40100. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  40101. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  40102. var normals = normalVertexBuffer.getData();
  40103. var vertexBufferOffset = normalVertexBuffer.getOffset();
  40104. var strideSize = normalVertexBuffer.getStrideSize();
  40105. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  40106. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  40107. defines.NORMAL = false;
  40108. }
  40109. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40110. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  40111. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  40112. var tangents = tangentVertexBuffer.getData();
  40113. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  40114. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  40115. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  40116. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  40117. defines.TANGENT = false;
  40118. }
  40119. }
  40120. }
  40121. else {
  40122. if (!scene.getEngine().getCaps().standardDerivatives) {
  40123. bufferMesh.createNormals(true);
  40124. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40125. }
  40126. }
  40127. }
  40128. }
  40129. // Get correct effect
  40130. if (defines.isDirty) {
  40131. defines.markAsProcessed();
  40132. scene.resetCachedMaterial();
  40133. // Fallbacks
  40134. var fallbacks = new BABYLON.EffectFallbacks();
  40135. var fallbackRank = 0;
  40136. if (defines.USESPHERICALINVERTEX) {
  40137. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40138. }
  40139. if (defines.FOG) {
  40140. fallbacks.addFallback(fallbackRank, "FOG");
  40141. }
  40142. if (defines.POINTSIZE) {
  40143. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40144. }
  40145. if (defines.LOGARITHMICDEPTH) {
  40146. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40147. }
  40148. if (defines.PARALLAX) {
  40149. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40150. }
  40151. if (defines.PARALLAXOCCLUSION) {
  40152. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40153. }
  40154. if (defines.ENVIRONMENTBRDF) {
  40155. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40156. }
  40157. if (defines.TANGENT) {
  40158. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40159. }
  40160. if (defines.BUMP) {
  40161. fallbacks.addFallback(fallbackRank++, "BUMP");
  40162. }
  40163. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40164. if (defines.SPECULARTERM) {
  40165. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40166. }
  40167. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40168. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40169. }
  40170. if (defines.LIGHTMAP) {
  40171. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40172. }
  40173. if (defines.NORMAL) {
  40174. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40175. }
  40176. if (defines.AMBIENT) {
  40177. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40178. }
  40179. if (defines.EMISSIVE) {
  40180. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40181. }
  40182. if (defines.VERTEXCOLOR) {
  40183. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40184. }
  40185. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40186. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40187. }
  40188. if (defines.MORPHTARGETS) {
  40189. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40190. }
  40191. //Attributes
  40192. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40193. if (defines.NORMAL) {
  40194. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40195. }
  40196. if (defines.TANGENT) {
  40197. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40198. }
  40199. if (defines.UV1) {
  40200. attribs.push(BABYLON.VertexBuffer.UVKind);
  40201. }
  40202. if (defines.UV2) {
  40203. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40204. }
  40205. if (defines.VERTEXCOLOR) {
  40206. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40207. }
  40208. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40209. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40210. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40211. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40212. "vFogInfos", "vFogColor", "pointSize",
  40213. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40214. "mBones",
  40215. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40216. "vLightingIntensity",
  40217. "logarithmicDepthConstant",
  40218. "vSphericalX", "vSphericalY", "vSphericalZ",
  40219. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40220. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40221. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40222. "vTangentSpaceParams"
  40223. ];
  40224. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40225. "bumpSampler", "lightmapSampler", "opacitySampler",
  40226. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40227. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40228. "microSurfaceSampler", "environmentBrdfSampler"];
  40229. var uniformBuffers = ["Material", "Scene"];
  40230. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40231. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40232. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40233. uniformsNames: uniforms,
  40234. uniformBuffersNames: uniformBuffers,
  40235. samplers: samplers,
  40236. defines: defines,
  40237. maxSimultaneousLights: this._maxSimultaneousLights
  40238. });
  40239. var onCompiled = function (effect) {
  40240. if (_this.onCompiled) {
  40241. _this.onCompiled(effect);
  40242. }
  40243. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  40244. };
  40245. var join = defines.toString();
  40246. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  40247. attributes: attribs,
  40248. uniformsNames: uniforms,
  40249. uniformBuffersNames: uniformBuffers,
  40250. samplers: samplers,
  40251. defines: join,
  40252. fallbacks: fallbacks,
  40253. onCompiled: onCompiled,
  40254. onError: this.onError,
  40255. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40256. }, engine), defines);
  40257. this.buildUniformLayout();
  40258. }
  40259. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40260. return false;
  40261. }
  40262. defines._renderId = scene.getRenderId();
  40263. this._wasPreviouslyReady = true;
  40264. return true;
  40265. };
  40266. /**
  40267. * Initializes the uniform buffer layout for the shader.
  40268. */
  40269. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40270. // Order is important !
  40271. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40272. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40273. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40274. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40275. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40276. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40277. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40278. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40279. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40280. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40281. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40282. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40283. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40284. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40285. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40286. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40287. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40288. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40289. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40290. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40291. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40292. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40293. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40294. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40295. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40296. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40297. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40298. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40299. this._uniformBuffer.addUniform("pointSize", 1);
  40300. this._uniformBuffer.create();
  40301. };
  40302. /**
  40303. * Unbinds the textures.
  40304. */
  40305. PBRBaseMaterial.prototype.unbind = function () {
  40306. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40307. this._uniformBuffer.setTexture("reflectionSampler", null);
  40308. }
  40309. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40310. this._uniformBuffer.setTexture("refractionSampler", null);
  40311. }
  40312. _super.prototype.unbind.call(this);
  40313. };
  40314. /**
  40315. * Binds to the world matrix.
  40316. * @param world - The world matrix.
  40317. */
  40318. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40319. this._activeEffect.setMatrix("world", world);
  40320. };
  40321. /**
  40322. * Binds the submesh data.
  40323. * @param world - The world matrix.
  40324. * @param mesh - The BJS mesh.
  40325. * @param subMesh - A submesh of the BJS mesh.
  40326. */
  40327. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40328. var scene = this.getScene();
  40329. var defines = subMesh._materialDefines;
  40330. if (!defines) {
  40331. return;
  40332. }
  40333. var effect = subMesh.effect;
  40334. if (!effect) {
  40335. return;
  40336. }
  40337. this._activeEffect = effect;
  40338. // Matrices
  40339. this.bindOnlyWorldMatrix(world);
  40340. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40341. // Bones
  40342. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40343. var reflectionTexture = null;
  40344. if (mustRebind) {
  40345. this._uniformBuffer.bindToEffect(effect, "Material");
  40346. this.bindViewProjection(effect);
  40347. reflectionTexture = this._getReflectionTexture();
  40348. var refractionTexture = this._getRefractionTexture();
  40349. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40350. // Texture uniforms
  40351. if (scene.texturesEnabled) {
  40352. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40353. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40354. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40355. }
  40356. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40357. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40358. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40359. }
  40360. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40361. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40362. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40363. }
  40364. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40365. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40366. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40367. var polynomials = reflectionTexture.sphericalPolynomial;
  40368. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40369. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40370. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40371. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40372. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40373. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40374. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40375. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40376. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40377. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40378. }
  40379. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40380. }
  40381. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40382. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40383. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40384. }
  40385. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40386. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40387. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40388. }
  40389. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40390. if (this._metallicTexture) {
  40391. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40392. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40393. }
  40394. else if (this._reflectivityTexture) {
  40395. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40396. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40397. }
  40398. if (this._microSurfaceTexture) {
  40399. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40400. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40401. }
  40402. }
  40403. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40404. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40405. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40406. if (scene._mirroredCameraPosition) {
  40407. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40408. }
  40409. else {
  40410. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40411. }
  40412. }
  40413. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40414. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40415. var depth = 1.0;
  40416. if (!refractionTexture.isCube) {
  40417. if (refractionTexture.depth) {
  40418. depth = refractionTexture.depth;
  40419. }
  40420. }
  40421. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40422. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40423. }
  40424. }
  40425. // Point size
  40426. if (this.pointsCloud) {
  40427. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40428. }
  40429. // Colors
  40430. if (defines.METALLICWORKFLOW) {
  40431. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40432. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40433. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40434. }
  40435. else {
  40436. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40437. }
  40438. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40439. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40440. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40441. // Misc
  40442. this._lightingInfos.x = this._directIntensity;
  40443. this._lightingInfos.y = this._emissiveIntensity;
  40444. this._lightingInfos.z = this._environmentIntensity;
  40445. this._lightingInfos.w = this._specularIntensity;
  40446. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40447. }
  40448. // Textures
  40449. if (scene.texturesEnabled) {
  40450. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40451. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40452. }
  40453. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40454. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40455. }
  40456. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40457. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40458. }
  40459. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40460. if (defines.LODBASEDMICROSFURACE) {
  40461. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40462. }
  40463. else {
  40464. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40465. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40466. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40467. }
  40468. }
  40469. if (defines.ENVIRONMENTBRDF) {
  40470. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40471. }
  40472. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40473. if (defines.LODBASEDMICROSFURACE) {
  40474. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40475. }
  40476. else {
  40477. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40478. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40479. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40480. }
  40481. }
  40482. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40483. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40484. }
  40485. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40486. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40487. }
  40488. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40489. if (this._metallicTexture) {
  40490. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40491. }
  40492. else if (this._reflectivityTexture) {
  40493. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40494. }
  40495. if (this._microSurfaceTexture) {
  40496. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40497. }
  40498. }
  40499. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40500. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40501. }
  40502. }
  40503. // Clip plane
  40504. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40505. // Colors
  40506. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40507. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40508. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40509. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40510. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40511. }
  40512. if (mustRebind || !this.isFrozen) {
  40513. // Lights
  40514. if (scene.lightsEnabled && !this._disableLighting) {
  40515. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40516. }
  40517. // View
  40518. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40519. this.bindView(effect);
  40520. }
  40521. // Fog
  40522. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40523. // Morph targets
  40524. if (defines.NUM_MORPH_INFLUENCERS) {
  40525. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40526. }
  40527. // image processing
  40528. this._imageProcessingConfiguration.bind(this._activeEffect);
  40529. // Log. depth
  40530. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40531. }
  40532. this._uniformBuffer.update();
  40533. this._afterBind(mesh);
  40534. };
  40535. /**
  40536. * Returns the animatable textures.
  40537. * @returns - Array of animatable textures.
  40538. */
  40539. PBRBaseMaterial.prototype.getAnimatables = function () {
  40540. var results = [];
  40541. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40542. results.push(this._albedoTexture);
  40543. }
  40544. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40545. results.push(this._ambientTexture);
  40546. }
  40547. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40548. results.push(this._opacityTexture);
  40549. }
  40550. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40551. results.push(this._reflectionTexture);
  40552. }
  40553. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40554. results.push(this._emissiveTexture);
  40555. }
  40556. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40557. results.push(this._metallicTexture);
  40558. }
  40559. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40560. results.push(this._reflectivityTexture);
  40561. }
  40562. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40563. results.push(this._bumpTexture);
  40564. }
  40565. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40566. results.push(this._lightmapTexture);
  40567. }
  40568. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40569. results.push(this._refractionTexture);
  40570. }
  40571. return results;
  40572. };
  40573. /**
  40574. * Returns the texture used for reflections.
  40575. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40576. */
  40577. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40578. if (this._reflectionTexture) {
  40579. return this._reflectionTexture;
  40580. }
  40581. return this.getScene().environmentTexture;
  40582. };
  40583. /**
  40584. * Returns the texture used for refraction or null if none is used.
  40585. * @returns - Refection texture if present. If no refraction texture and refraction
  40586. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40587. */
  40588. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40589. if (this._refractionTexture) {
  40590. return this._refractionTexture;
  40591. }
  40592. if (this._linkRefractionWithTransparency) {
  40593. return this.getScene().environmentTexture;
  40594. }
  40595. return null;
  40596. };
  40597. /**
  40598. * Disposes the resources of the material.
  40599. * @param forceDisposeEffect - Forces the disposal of effects.
  40600. * @param forceDisposeTextures - Forces the disposal of all textures.
  40601. */
  40602. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40603. if (forceDisposeTextures) {
  40604. if (this._albedoTexture) {
  40605. this._albedoTexture.dispose();
  40606. }
  40607. if (this._ambientTexture) {
  40608. this._ambientTexture.dispose();
  40609. }
  40610. if (this._opacityTexture) {
  40611. this._opacityTexture.dispose();
  40612. }
  40613. if (this._reflectionTexture) {
  40614. this._reflectionTexture.dispose();
  40615. }
  40616. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40617. this._environmentBRDFTexture.dispose();
  40618. }
  40619. if (this._emissiveTexture) {
  40620. this._emissiveTexture.dispose();
  40621. }
  40622. if (this._metallicTexture) {
  40623. this._metallicTexture.dispose();
  40624. }
  40625. if (this._reflectivityTexture) {
  40626. this._reflectivityTexture.dispose();
  40627. }
  40628. if (this._bumpTexture) {
  40629. this._bumpTexture.dispose();
  40630. }
  40631. if (this._lightmapTexture) {
  40632. this._lightmapTexture.dispose();
  40633. }
  40634. if (this._refractionTexture) {
  40635. this._refractionTexture.dispose();
  40636. }
  40637. }
  40638. this._renderTargets.dispose();
  40639. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40640. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40641. }
  40642. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40643. };
  40644. /**
  40645. * Stores the reflectivity values based on metallic roughness workflow.
  40646. */
  40647. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  40648. __decorate([
  40649. BABYLON.serializeAsImageProcessingConfiguration()
  40650. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  40651. __decorate([
  40652. BABYLON.serialize()
  40653. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  40654. __decorate([
  40655. BABYLON.serialize()
  40656. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  40657. return PBRBaseMaterial;
  40658. }(BABYLON.PushMaterial));
  40659. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  40660. })(BABYLON || (BABYLON = {}));
  40661. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  40662. var BABYLON;
  40663. (function (BABYLON) {
  40664. /**
  40665. * The Physically based simple base material of BJS.
  40666. *
  40667. * This enables better naming and convention enforcements on top of the pbrMaterial.
  40668. * It is used as the base class for both the specGloss and metalRough conventions.
  40669. */
  40670. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  40671. __extends(PBRBaseSimpleMaterial, _super);
  40672. /**
  40673. * Instantiates a new PBRMaterial instance.
  40674. *
  40675. * @param name The material name
  40676. * @param scene The scene the material will be use in.
  40677. */
  40678. function PBRBaseSimpleMaterial(name, scene) {
  40679. var _this = _super.call(this, name, scene) || this;
  40680. /**
  40681. * Number of Simultaneous lights allowed on the material.
  40682. */
  40683. _this.maxSimultaneousLights = 4;
  40684. /**
  40685. * If sets to true, disables all the lights affecting the material.
  40686. */
  40687. _this.disableLighting = false;
  40688. /**
  40689. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40690. */
  40691. _this.invertNormalMapX = false;
  40692. /**
  40693. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40694. */
  40695. _this.invertNormalMapY = false;
  40696. /**
  40697. * Emissivie color used to self-illuminate the model.
  40698. */
  40699. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40700. /**
  40701. * Occlusion Channel Strenght.
  40702. */
  40703. _this.occlusionStrength = 1.0;
  40704. _this.useLightmapAsShadowmap = false;
  40705. _this._useAlphaFromAlbedoTexture = true;
  40706. _this._useAmbientInGrayScale = true;
  40707. return _this;
  40708. }
  40709. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  40710. /**
  40711. * Gets the current double sided mode.
  40712. */
  40713. get: function () {
  40714. return this._twoSidedLighting;
  40715. },
  40716. /**
  40717. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40718. */
  40719. set: function (value) {
  40720. if (this._twoSidedLighting === value) {
  40721. return;
  40722. }
  40723. this._twoSidedLighting = value;
  40724. this.backFaceCulling = !value;
  40725. this._markAllSubMeshesAsTexturesDirty();
  40726. },
  40727. enumerable: true,
  40728. configurable: true
  40729. });
  40730. /**
  40731. * Return the active textures of the material.
  40732. */
  40733. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  40734. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40735. if (this.environmentTexture) {
  40736. activeTextures.push(this.environmentTexture);
  40737. }
  40738. if (this.normalTexture) {
  40739. activeTextures.push(this.normalTexture);
  40740. }
  40741. if (this.emissiveTexture) {
  40742. activeTextures.push(this.emissiveTexture);
  40743. }
  40744. if (this.occlusionTexture) {
  40745. activeTextures.push(this.occlusionTexture);
  40746. }
  40747. if (this.lightmapTexture) {
  40748. activeTextures.push(this.lightmapTexture);
  40749. }
  40750. return activeTextures;
  40751. };
  40752. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  40753. if (_super.prototype.hasTexture.call(this, texture)) {
  40754. return true;
  40755. }
  40756. if (this.lightmapTexture === texture) {
  40757. return true;
  40758. }
  40759. return false;
  40760. };
  40761. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  40762. return "PBRBaseSimpleMaterial";
  40763. };
  40764. __decorate([
  40765. BABYLON.serialize(),
  40766. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40767. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  40768. __decorate([
  40769. BABYLON.serialize(),
  40770. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40771. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  40772. __decorate([
  40773. BABYLON.serializeAsTexture(),
  40774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  40775. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  40776. __decorate([
  40777. BABYLON.serialize(),
  40778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40779. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  40780. __decorate([
  40781. BABYLON.serialize(),
  40782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40783. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  40784. __decorate([
  40785. BABYLON.serializeAsTexture(),
  40786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  40787. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  40788. __decorate([
  40789. BABYLON.serializeAsColor3("emissive"),
  40790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40791. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  40792. __decorate([
  40793. BABYLON.serializeAsTexture(),
  40794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40795. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  40796. __decorate([
  40797. BABYLON.serialize(),
  40798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  40799. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  40800. __decorate([
  40801. BABYLON.serializeAsTexture(),
  40802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  40803. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  40804. __decorate([
  40805. BABYLON.serialize(),
  40806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  40807. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  40808. __decorate([
  40809. BABYLON.serialize()
  40810. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  40811. __decorate([
  40812. BABYLON.serializeAsTexture(),
  40813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40814. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  40815. __decorate([
  40816. BABYLON.serialize(),
  40817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40818. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40819. return PBRBaseSimpleMaterial;
  40820. }(BABYLON.PBRBaseMaterial));
  40821. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  40822. })(BABYLON || (BABYLON = {}));
  40823. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  40824. var BABYLON;
  40825. (function (BABYLON) {
  40826. /**
  40827. * The Physically based material of BJS.
  40828. *
  40829. * This offers the main features of a standard PBR material.
  40830. * For more information, please refer to the documentation :
  40831. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40832. */
  40833. var PBRMaterial = /** @class */ (function (_super) {
  40834. __extends(PBRMaterial, _super);
  40835. /**
  40836. * Instantiates a new PBRMaterial instance.
  40837. *
  40838. * @param name The material name
  40839. * @param scene The scene the material will be use in.
  40840. */
  40841. function PBRMaterial(name, scene) {
  40842. var _this = _super.call(this, name, scene) || this;
  40843. /**
  40844. * Intensity of the direct lights e.g. the four lights available in your scene.
  40845. * This impacts both the direct diffuse and specular highlights.
  40846. */
  40847. _this.directIntensity = 1.0;
  40848. /**
  40849. * Intensity of the emissive part of the material.
  40850. * This helps controlling the emissive effect without modifying the emissive color.
  40851. */
  40852. _this.emissiveIntensity = 1.0;
  40853. /**
  40854. * Intensity of the environment e.g. how much the environment will light the object
  40855. * either through harmonics for rough material or through the refelction for shiny ones.
  40856. */
  40857. _this.environmentIntensity = 1.0;
  40858. /**
  40859. * This is a special control allowing the reduction of the specular highlights coming from the
  40860. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40861. */
  40862. _this.specularIntensity = 1.0;
  40863. /**
  40864. * Debug Control allowing disabling the bump map on this material.
  40865. */
  40866. _this.disableBumpMap = false;
  40867. /**
  40868. * AKA Occlusion Texture Intensity in other nomenclature.
  40869. */
  40870. _this.ambientTextureStrength = 1.0;
  40871. /**
  40872. * The color of a material in ambient lighting.
  40873. */
  40874. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  40875. /**
  40876. * AKA Diffuse Color in other nomenclature.
  40877. */
  40878. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  40879. /**
  40880. * AKA Specular Color in other nomenclature.
  40881. */
  40882. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40883. /**
  40884. * The color reflected from the material.
  40885. */
  40886. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  40887. /**
  40888. * The color emitted from the material.
  40889. */
  40890. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40891. /**
  40892. * AKA Glossiness in other nomenclature.
  40893. */
  40894. _this.microSurface = 1.0;
  40895. /**
  40896. * source material index of refraction (IOR)' / 'destination material IOR.
  40897. */
  40898. _this.indexOfRefraction = 0.66;
  40899. /**
  40900. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40901. */
  40902. _this.invertRefractionY = false;
  40903. /**
  40904. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40905. * Materials half opaque for instance using refraction could benefit from this control.
  40906. */
  40907. _this.linkRefractionWithTransparency = false;
  40908. _this.useLightmapAsShadowmap = false;
  40909. /**
  40910. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40911. */
  40912. _this.useAlphaFromAlbedoTexture = false;
  40913. /**
  40914. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40915. */
  40916. _this.forceAlphaTest = false;
  40917. /**
  40918. * Defines the alpha limits in alpha test mode.
  40919. */
  40920. _this.alphaCutOff = 0.4;
  40921. /**
  40922. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40923. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40924. */
  40925. _this.useSpecularOverAlpha = true;
  40926. /**
  40927. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40928. */
  40929. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  40930. /**
  40931. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40932. */
  40933. _this.useRoughnessFromMetallicTextureAlpha = true;
  40934. /**
  40935. * Specifies if the metallic texture contains the roughness information in its green channel.
  40936. */
  40937. _this.useRoughnessFromMetallicTextureGreen = false;
  40938. /**
  40939. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40940. */
  40941. _this.useMetallnessFromMetallicTextureBlue = false;
  40942. /**
  40943. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40944. */
  40945. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  40946. /**
  40947. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40948. */
  40949. _this.useAmbientInGrayScale = false;
  40950. /**
  40951. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40952. * The material will try to infer what glossiness each pixel should be.
  40953. */
  40954. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  40955. /**
  40956. * BJS is using an harcoded light falloff based on a manually sets up range.
  40957. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40958. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40959. */
  40960. _this.usePhysicalLightFalloff = true;
  40961. /**
  40962. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40963. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40964. */
  40965. _this.useRadianceOverAlpha = true;
  40966. /**
  40967. * Allows using the bump map in parallax mode.
  40968. */
  40969. _this.useParallax = false;
  40970. /**
  40971. * Allows using the bump map in parallax occlusion mode.
  40972. */
  40973. _this.useParallaxOcclusion = false;
  40974. /**
  40975. * Controls the scale bias of the parallax mode.
  40976. */
  40977. _this.parallaxScaleBias = 0.05;
  40978. /**
  40979. * If sets to true, disables all the lights affecting the material.
  40980. */
  40981. _this.disableLighting = false;
  40982. /**
  40983. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40984. */
  40985. _this.forceIrradianceInFragment = false;
  40986. /**
  40987. * Number of Simultaneous lights allowed on the material.
  40988. */
  40989. _this.maxSimultaneousLights = 4;
  40990. /**
  40991. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40992. */
  40993. _this.invertNormalMapX = false;
  40994. /**
  40995. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40996. */
  40997. _this.invertNormalMapY = false;
  40998. /**
  40999. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41000. */
  41001. _this.twoSidedLighting = false;
  41002. /**
  41003. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41004. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41005. */
  41006. _this.useAlphaFresnel = false;
  41007. /**
  41008. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41009. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41010. */
  41011. _this.useLinearAlphaFresnel = false;
  41012. /**
  41013. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41014. * And/Or occlude the blended part.
  41015. */
  41016. _this.environmentBRDFTexture = null;
  41017. /**
  41018. * Force normal to face away from face.
  41019. */
  41020. _this.forceNormalForward = false;
  41021. /**
  41022. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41023. * makes the reflect vector face the model (under horizon).
  41024. */
  41025. _this.useHorizonOcclusion = true;
  41026. /**
  41027. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41028. * too much the area relying on ambient texture to define their ambient occlusion.
  41029. */
  41030. _this.useRadianceOcclusion = true;
  41031. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41032. return _this;
  41033. }
  41034. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41035. /**
  41036. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41037. */
  41038. get: function () {
  41039. return this._PBRMATERIAL_OPAQUE;
  41040. },
  41041. enumerable: true,
  41042. configurable: true
  41043. });
  41044. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41045. /**
  41046. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41047. */
  41048. get: function () {
  41049. return this._PBRMATERIAL_ALPHATEST;
  41050. },
  41051. enumerable: true,
  41052. configurable: true
  41053. });
  41054. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41055. /**
  41056. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41057. */
  41058. get: function () {
  41059. return this._PBRMATERIAL_ALPHABLEND;
  41060. },
  41061. enumerable: true,
  41062. configurable: true
  41063. });
  41064. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41065. /**
  41066. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41067. * They are also discarded below the alpha cutoff threshold to improve performances.
  41068. */
  41069. get: function () {
  41070. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41071. },
  41072. enumerable: true,
  41073. configurable: true
  41074. });
  41075. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41076. /**
  41077. * Gets the image processing configuration used either in this material.
  41078. */
  41079. get: function () {
  41080. return this._imageProcessingConfiguration;
  41081. },
  41082. /**
  41083. * Sets the Default image processing configuration used either in the this material.
  41084. *
  41085. * If sets to null, the scene one is in use.
  41086. */
  41087. set: function (value) {
  41088. this._attachImageProcessingConfiguration(value);
  41089. // Ensure the effect will be rebuilt.
  41090. this._markAllSubMeshesAsTexturesDirty();
  41091. },
  41092. enumerable: true,
  41093. configurable: true
  41094. });
  41095. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41096. /**
  41097. * Gets wether the color curves effect is enabled.
  41098. */
  41099. get: function () {
  41100. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41101. },
  41102. /**
  41103. * Sets wether the color curves effect is enabled.
  41104. */
  41105. set: function (value) {
  41106. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41107. },
  41108. enumerable: true,
  41109. configurable: true
  41110. });
  41111. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41112. /**
  41113. * Gets wether the color grading effect is enabled.
  41114. */
  41115. get: function () {
  41116. return this.imageProcessingConfiguration.colorGradingEnabled;
  41117. },
  41118. /**
  41119. * Gets wether the color grading effect is enabled.
  41120. */
  41121. set: function (value) {
  41122. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41128. /**
  41129. * Gets wether tonemapping is enabled or not.
  41130. */
  41131. get: function () {
  41132. return this._imageProcessingConfiguration.toneMappingEnabled;
  41133. },
  41134. /**
  41135. * Sets wether tonemapping is enabled or not
  41136. */
  41137. set: function (value) {
  41138. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41139. },
  41140. enumerable: true,
  41141. configurable: true
  41142. });
  41143. ;
  41144. ;
  41145. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41146. /**
  41147. * The camera exposure used on this material.
  41148. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41149. * This corresponds to a photographic exposure.
  41150. */
  41151. get: function () {
  41152. return this._imageProcessingConfiguration.exposure;
  41153. },
  41154. /**
  41155. * The camera exposure used on this material.
  41156. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41157. * This corresponds to a photographic exposure.
  41158. */
  41159. set: function (value) {
  41160. this._imageProcessingConfiguration.exposure = value;
  41161. },
  41162. enumerable: true,
  41163. configurable: true
  41164. });
  41165. ;
  41166. ;
  41167. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41168. /**
  41169. * Gets The camera contrast used on this material.
  41170. */
  41171. get: function () {
  41172. return this._imageProcessingConfiguration.contrast;
  41173. },
  41174. /**
  41175. * Sets The camera contrast used on this material.
  41176. */
  41177. set: function (value) {
  41178. this._imageProcessingConfiguration.contrast = value;
  41179. },
  41180. enumerable: true,
  41181. configurable: true
  41182. });
  41183. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41184. /**
  41185. * Gets the Color Grading 2D Lookup Texture.
  41186. */
  41187. get: function () {
  41188. return this._imageProcessingConfiguration.colorGradingTexture;
  41189. },
  41190. /**
  41191. * Sets the Color Grading 2D Lookup Texture.
  41192. */
  41193. set: function (value) {
  41194. this._imageProcessingConfiguration.colorGradingTexture = value;
  41195. },
  41196. enumerable: true,
  41197. configurable: true
  41198. });
  41199. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41200. /**
  41201. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41202. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41203. * 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;
  41204. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41205. */
  41206. get: function () {
  41207. return this._imageProcessingConfiguration.colorCurves;
  41208. },
  41209. /**
  41210. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41211. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41212. * 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;
  41213. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41214. */
  41215. set: function (value) {
  41216. this._imageProcessingConfiguration.colorCurves = value;
  41217. },
  41218. enumerable: true,
  41219. configurable: true
  41220. });
  41221. /**
  41222. * Returns the name of this material class.
  41223. */
  41224. PBRMaterial.prototype.getClassName = function () {
  41225. return "PBRMaterial";
  41226. };
  41227. /**
  41228. * Returns an array of the actively used textures.
  41229. * @returns - Array of BaseTextures
  41230. */
  41231. PBRMaterial.prototype.getActiveTextures = function () {
  41232. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41233. if (this._albedoTexture) {
  41234. activeTextures.push(this._albedoTexture);
  41235. }
  41236. if (this._ambientTexture) {
  41237. activeTextures.push(this._ambientTexture);
  41238. }
  41239. if (this._opacityTexture) {
  41240. activeTextures.push(this._opacityTexture);
  41241. }
  41242. if (this._reflectionTexture) {
  41243. activeTextures.push(this._reflectionTexture);
  41244. }
  41245. if (this._emissiveTexture) {
  41246. activeTextures.push(this._emissiveTexture);
  41247. }
  41248. if (this._reflectivityTexture) {
  41249. activeTextures.push(this._reflectivityTexture);
  41250. }
  41251. if (this._metallicTexture) {
  41252. activeTextures.push(this._metallicTexture);
  41253. }
  41254. if (this._microSurfaceTexture) {
  41255. activeTextures.push(this._microSurfaceTexture);
  41256. }
  41257. if (this._bumpTexture) {
  41258. activeTextures.push(this._bumpTexture);
  41259. }
  41260. if (this._lightmapTexture) {
  41261. activeTextures.push(this._lightmapTexture);
  41262. }
  41263. if (this._refractionTexture) {
  41264. activeTextures.push(this._refractionTexture);
  41265. }
  41266. return activeTextures;
  41267. };
  41268. /**
  41269. * Checks to see if a texture is used in the material.
  41270. * @param texture - Base texture to use.
  41271. * @returns - Boolean specifying if a texture is used in the material.
  41272. */
  41273. PBRMaterial.prototype.hasTexture = function (texture) {
  41274. if (_super.prototype.hasTexture.call(this, texture)) {
  41275. return true;
  41276. }
  41277. if (this._albedoTexture === texture) {
  41278. return true;
  41279. }
  41280. if (this._ambientTexture === texture) {
  41281. return true;
  41282. }
  41283. if (this._opacityTexture === texture) {
  41284. return true;
  41285. }
  41286. if (this._reflectionTexture === texture) {
  41287. return true;
  41288. }
  41289. if (this._reflectivityTexture === texture) {
  41290. return true;
  41291. }
  41292. if (this._metallicTexture === texture) {
  41293. return true;
  41294. }
  41295. if (this._microSurfaceTexture === texture) {
  41296. return true;
  41297. }
  41298. if (this._bumpTexture === texture) {
  41299. return true;
  41300. }
  41301. if (this._lightmapTexture === texture) {
  41302. return true;
  41303. }
  41304. if (this._refractionTexture === texture) {
  41305. return true;
  41306. }
  41307. return false;
  41308. };
  41309. /**
  41310. * Makes a duplicate of the current material.
  41311. * @param name - name to use for the new material.
  41312. */
  41313. PBRMaterial.prototype.clone = function (name) {
  41314. var _this = this;
  41315. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41316. clone.id = name;
  41317. clone.name = name;
  41318. return clone;
  41319. };
  41320. /**
  41321. * Serializes this PBR Material.
  41322. * @returns - An object with the serialized material.
  41323. */
  41324. PBRMaterial.prototype.serialize = function () {
  41325. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41326. serializationObject.customType = "BABYLON.PBRMaterial";
  41327. return serializationObject;
  41328. };
  41329. // Statics
  41330. /**
  41331. * Parses a PBR Material from a serialized object.
  41332. * @param source - Serialized object.
  41333. * @param scene - BJS scene instance.
  41334. * @param rootUrl - url for the scene object
  41335. * @returns - PBRMaterial
  41336. */
  41337. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41338. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41339. };
  41340. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41341. /**
  41342. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41343. */
  41344. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41345. /**
  41346. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41347. */
  41348. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41349. /**
  41350. * 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.
  41351. * They are also discarded below the alpha cutoff threshold to improve performances.
  41352. */
  41353. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41354. __decorate([
  41355. BABYLON.serialize(),
  41356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41357. ], PBRMaterial.prototype, "directIntensity", void 0);
  41358. __decorate([
  41359. BABYLON.serialize(),
  41360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41361. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41362. __decorate([
  41363. BABYLON.serialize(),
  41364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41365. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41366. __decorate([
  41367. BABYLON.serialize(),
  41368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41369. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41370. __decorate([
  41371. BABYLON.serialize(),
  41372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41373. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41374. __decorate([
  41375. BABYLON.serializeAsTexture(),
  41376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41377. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41378. __decorate([
  41379. BABYLON.serializeAsTexture(),
  41380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41381. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41382. __decorate([
  41383. BABYLON.serialize(),
  41384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41385. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41386. __decorate([
  41387. BABYLON.serializeAsTexture(),
  41388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41389. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41390. __decorate([
  41391. BABYLON.serializeAsTexture(),
  41392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41393. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41394. __decorate([
  41395. BABYLON.serializeAsTexture(),
  41396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41397. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41398. __decorate([
  41399. BABYLON.serializeAsTexture(),
  41400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41401. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41402. __decorate([
  41403. BABYLON.serializeAsTexture(),
  41404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41405. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41406. __decorate([
  41407. BABYLON.serialize(),
  41408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41409. ], PBRMaterial.prototype, "metallic", void 0);
  41410. __decorate([
  41411. BABYLON.serialize(),
  41412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41413. ], PBRMaterial.prototype, "roughness", void 0);
  41414. __decorate([
  41415. BABYLON.serializeAsTexture(),
  41416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41417. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41418. __decorate([
  41419. BABYLON.serializeAsTexture(),
  41420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41421. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41422. __decorate([
  41423. BABYLON.serializeAsTexture(),
  41424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41425. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41426. __decorate([
  41427. BABYLON.serializeAsTexture(),
  41428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41429. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41430. __decorate([
  41431. BABYLON.serializeAsColor3("ambient"),
  41432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41433. ], PBRMaterial.prototype, "ambientColor", void 0);
  41434. __decorate([
  41435. BABYLON.serializeAsColor3("albedo"),
  41436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41437. ], PBRMaterial.prototype, "albedoColor", void 0);
  41438. __decorate([
  41439. BABYLON.serializeAsColor3("reflectivity"),
  41440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41441. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41442. __decorate([
  41443. BABYLON.serializeAsColor3("reflection"),
  41444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41445. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41446. __decorate([
  41447. BABYLON.serializeAsColor3("emissive"),
  41448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41449. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41450. __decorate([
  41451. BABYLON.serialize(),
  41452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41453. ], PBRMaterial.prototype, "microSurface", void 0);
  41454. __decorate([
  41455. BABYLON.serialize(),
  41456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41457. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41458. __decorate([
  41459. BABYLON.serialize(),
  41460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41461. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41462. __decorate([
  41463. BABYLON.serialize(),
  41464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41465. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41466. __decorate([
  41467. BABYLON.serialize(),
  41468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41469. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41470. __decorate([
  41471. BABYLON.serialize(),
  41472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41473. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41474. __decorate([
  41475. BABYLON.serialize(),
  41476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41477. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41478. __decorate([
  41479. BABYLON.serialize(),
  41480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41481. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41482. __decorate([
  41483. BABYLON.serialize(),
  41484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41485. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41486. __decorate([
  41487. BABYLON.serialize(),
  41488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41489. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41490. __decorate([
  41491. BABYLON.serialize(),
  41492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41493. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41494. __decorate([
  41495. BABYLON.serialize(),
  41496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41497. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41498. __decorate([
  41499. BABYLON.serialize(),
  41500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41501. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41502. __decorate([
  41503. BABYLON.serialize(),
  41504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41505. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41506. __decorate([
  41507. BABYLON.serialize(),
  41508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41509. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41510. __decorate([
  41511. BABYLON.serialize(),
  41512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41513. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41514. __decorate([
  41515. BABYLON.serialize(),
  41516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41517. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41518. __decorate([
  41519. BABYLON.serialize(),
  41520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41521. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41522. __decorate([
  41523. BABYLON.serialize(),
  41524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41525. ], PBRMaterial.prototype, "useParallax", void 0);
  41526. __decorate([
  41527. BABYLON.serialize(),
  41528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41529. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41530. __decorate([
  41531. BABYLON.serialize(),
  41532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41533. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41534. __decorate([
  41535. BABYLON.serialize(),
  41536. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41537. ], PBRMaterial.prototype, "disableLighting", void 0);
  41538. __decorate([
  41539. BABYLON.serialize(),
  41540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41541. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41542. __decorate([
  41543. BABYLON.serialize(),
  41544. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41545. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41546. __decorate([
  41547. BABYLON.serialize(),
  41548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41549. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41550. __decorate([
  41551. BABYLON.serialize(),
  41552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41553. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41554. __decorate([
  41555. BABYLON.serialize(),
  41556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41557. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41558. __decorate([
  41559. BABYLON.serialize(),
  41560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41561. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41562. __decorate([
  41563. BABYLON.serialize(),
  41564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41565. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41566. __decorate([
  41567. BABYLON.serializeAsTexture(),
  41568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41569. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41570. __decorate([
  41571. BABYLON.serialize(),
  41572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41573. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41574. __decorate([
  41575. BABYLON.serialize(),
  41576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41577. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41578. __decorate([
  41579. BABYLON.serialize(),
  41580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41581. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41582. return PBRMaterial;
  41583. }(BABYLON.PBRBaseMaterial));
  41584. BABYLON.PBRMaterial = PBRMaterial;
  41585. })(BABYLON || (BABYLON = {}));
  41586. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41587. var BABYLON;
  41588. (function (BABYLON) {
  41589. /**
  41590. * The PBR material of BJS following the metal roughness convention.
  41591. *
  41592. * This fits to the PBR convention in the GLTF definition:
  41593. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41594. */
  41595. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41596. __extends(PBRMetallicRoughnessMaterial, _super);
  41597. /**
  41598. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41599. *
  41600. * @param name The material name
  41601. * @param scene The scene the material will be use in.
  41602. */
  41603. function PBRMetallicRoughnessMaterial(name, scene) {
  41604. var _this = _super.call(this, name, scene) || this;
  41605. _this._useRoughnessFromMetallicTextureAlpha = false;
  41606. _this._useRoughnessFromMetallicTextureGreen = true;
  41607. _this._useMetallnessFromMetallicTextureBlue = true;
  41608. _this._forceMetallicWorkflow = true;
  41609. return _this;
  41610. }
  41611. /**
  41612. * Return the currrent class name of the material.
  41613. */
  41614. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41615. return "PBRMetallicRoughnessMaterial";
  41616. };
  41617. /**
  41618. * Return the active textures of the material.
  41619. */
  41620. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41621. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41622. if (this.baseTexture) {
  41623. activeTextures.push(this.baseTexture);
  41624. }
  41625. if (this.metallicRoughnessTexture) {
  41626. activeTextures.push(this.metallicRoughnessTexture);
  41627. }
  41628. return activeTextures;
  41629. };
  41630. /**
  41631. * Checks to see if a texture is used in the material.
  41632. * @param texture - Base texture to use.
  41633. * @returns - Boolean specifying if a texture is used in the material.
  41634. */
  41635. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41636. if (_super.prototype.hasTexture.call(this, texture)) {
  41637. return true;
  41638. }
  41639. if (this.baseTexture === texture) {
  41640. return true;
  41641. }
  41642. if (this.metallicRoughnessTexture === texture) {
  41643. return true;
  41644. }
  41645. return false;
  41646. };
  41647. /**
  41648. * Makes a duplicate of the current material.
  41649. * @param name - name to use for the new material.
  41650. */
  41651. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  41652. var _this = this;
  41653. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  41654. clone.id = name;
  41655. clone.name = name;
  41656. return clone;
  41657. };
  41658. /**
  41659. * Serialize the material to a parsable JSON object.
  41660. */
  41661. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  41662. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41663. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  41664. return serializationObject;
  41665. };
  41666. /**
  41667. * Parses a JSON object correponding to the serialize function.
  41668. */
  41669. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  41670. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  41671. };
  41672. __decorate([
  41673. BABYLON.serializeAsColor3(),
  41674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  41675. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  41676. __decorate([
  41677. BABYLON.serializeAsTexture(),
  41678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  41679. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  41680. __decorate([
  41681. BABYLON.serialize(),
  41682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41683. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  41684. __decorate([
  41685. BABYLON.serialize(),
  41686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41687. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  41688. __decorate([
  41689. BABYLON.serializeAsTexture(),
  41690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  41691. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  41692. return PBRMetallicRoughnessMaterial;
  41693. }(BABYLON.PBRBaseSimpleMaterial));
  41694. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  41695. })(BABYLON || (BABYLON = {}));
  41696. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  41697. var BABYLON;
  41698. (function (BABYLON) {
  41699. /**
  41700. * The PBR material of BJS following the specular glossiness convention.
  41701. *
  41702. * This fits to the PBR convention in the GLTF definition:
  41703. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  41704. */
  41705. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  41706. __extends(PBRSpecularGlossinessMaterial, _super);
  41707. /**
  41708. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  41709. *
  41710. * @param name The material name
  41711. * @param scene The scene the material will be use in.
  41712. */
  41713. function PBRSpecularGlossinessMaterial(name, scene) {
  41714. var _this = _super.call(this, name, scene) || this;
  41715. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  41716. return _this;
  41717. }
  41718. /**
  41719. * Return the currrent class name of the material.
  41720. */
  41721. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  41722. return "PBRSpecularGlossinessMaterial";
  41723. };
  41724. /**
  41725. * Return the active textures of the material.
  41726. */
  41727. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  41728. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41729. if (this.diffuseTexture) {
  41730. activeTextures.push(this.diffuseTexture);
  41731. }
  41732. if (this.specularGlossinessTexture) {
  41733. activeTextures.push(this.specularGlossinessTexture);
  41734. }
  41735. return activeTextures;
  41736. };
  41737. /**
  41738. * Checks to see if a texture is used in the material.
  41739. * @param texture - Base texture to use.
  41740. * @returns - Boolean specifying if a texture is used in the material.
  41741. */
  41742. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  41743. if (_super.prototype.hasTexture.call(this, texture)) {
  41744. return true;
  41745. }
  41746. if (this.diffuseTexture === texture) {
  41747. return true;
  41748. }
  41749. if (this.specularGlossinessTexture === texture) {
  41750. return true;
  41751. }
  41752. return false;
  41753. };
  41754. /**
  41755. * Makes a duplicate of the current material.
  41756. * @param name - name to use for the new material.
  41757. */
  41758. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  41759. var _this = this;
  41760. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  41761. clone.id = name;
  41762. clone.name = name;
  41763. return clone;
  41764. };
  41765. /**
  41766. * Serialize the material to a parsable JSON object.
  41767. */
  41768. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  41769. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41770. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  41771. return serializationObject;
  41772. };
  41773. /**
  41774. * Parses a JSON object correponding to the serialize function.
  41775. */
  41776. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  41777. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  41778. };
  41779. __decorate([
  41780. BABYLON.serializeAsColor3("diffuse"),
  41781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  41782. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  41783. __decorate([
  41784. BABYLON.serializeAsTexture(),
  41785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  41786. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  41787. __decorate([
  41788. BABYLON.serializeAsColor3("specular"),
  41789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  41790. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  41791. __decorate([
  41792. BABYLON.serialize(),
  41793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  41794. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  41795. __decorate([
  41796. BABYLON.serializeAsTexture(),
  41797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  41798. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  41799. return PBRSpecularGlossinessMaterial;
  41800. }(BABYLON.PBRBaseSimpleMaterial));
  41801. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  41802. })(BABYLON || (BABYLON = {}));
  41803. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  41804. var BABYLON;
  41805. (function (BABYLON) {
  41806. BABYLON.CameraInputTypes = {};
  41807. var CameraInputsManager = /** @class */ (function () {
  41808. function CameraInputsManager(camera) {
  41809. this.attached = {};
  41810. this.camera = camera;
  41811. this.checkInputs = function () { };
  41812. }
  41813. /**
  41814. * Add an input method to a camera.
  41815. * builtin inputs example: camera.inputs.addGamepad();
  41816. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  41817. * @param input camera input method
  41818. */
  41819. CameraInputsManager.prototype.add = function (input) {
  41820. var type = input.getSimpleName();
  41821. if (this.attached[type]) {
  41822. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  41823. return;
  41824. }
  41825. this.attached[type] = input;
  41826. input.camera = this.camera;
  41827. //for checkInputs, we are dynamically creating a function
  41828. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  41829. if (input.checkInputs) {
  41830. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  41831. }
  41832. if (this.attachedElement) {
  41833. input.attachControl(this.attachedElement);
  41834. }
  41835. };
  41836. /**
  41837. * Remove a specific input method from a camera
  41838. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  41839. * @param inputToRemove camera input method
  41840. */
  41841. CameraInputsManager.prototype.remove = function (inputToRemove) {
  41842. for (var cam in this.attached) {
  41843. var input = this.attached[cam];
  41844. if (input === inputToRemove) {
  41845. input.detachControl(this.attachedElement);
  41846. input.camera = null;
  41847. delete this.attached[cam];
  41848. this.rebuildInputCheck();
  41849. }
  41850. }
  41851. };
  41852. CameraInputsManager.prototype.removeByType = function (inputType) {
  41853. for (var cam in this.attached) {
  41854. var input = this.attached[cam];
  41855. if (input.getClassName() === inputType) {
  41856. input.detachControl(this.attachedElement);
  41857. input.camera = null;
  41858. delete this.attached[cam];
  41859. this.rebuildInputCheck();
  41860. }
  41861. }
  41862. };
  41863. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  41864. var current = this.checkInputs;
  41865. return function () {
  41866. current();
  41867. fn();
  41868. };
  41869. };
  41870. CameraInputsManager.prototype.attachInput = function (input) {
  41871. if (this.attachedElement) {
  41872. input.attachControl(this.attachedElement, this.noPreventDefault);
  41873. }
  41874. };
  41875. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  41876. if (noPreventDefault === void 0) { noPreventDefault = false; }
  41877. if (this.attachedElement) {
  41878. return;
  41879. }
  41880. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  41881. this.attachedElement = element;
  41882. this.noPreventDefault = noPreventDefault;
  41883. for (var cam in this.attached) {
  41884. this.attached[cam].attachControl(element, noPreventDefault);
  41885. }
  41886. };
  41887. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  41888. if (disconnect === void 0) { disconnect = false; }
  41889. if (this.attachedElement !== element) {
  41890. return;
  41891. }
  41892. for (var cam in this.attached) {
  41893. this.attached[cam].detachControl(element);
  41894. if (disconnect) {
  41895. this.attached[cam].camera = null;
  41896. }
  41897. }
  41898. this.attachedElement = null;
  41899. };
  41900. CameraInputsManager.prototype.rebuildInputCheck = function () {
  41901. this.checkInputs = function () { };
  41902. for (var cam in this.attached) {
  41903. var input = this.attached[cam];
  41904. if (input.checkInputs) {
  41905. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  41906. }
  41907. }
  41908. };
  41909. /**
  41910. * Remove all attached input methods from a camera
  41911. */
  41912. CameraInputsManager.prototype.clear = function () {
  41913. if (this.attachedElement) {
  41914. this.detachElement(this.attachedElement, true);
  41915. }
  41916. this.attached = {};
  41917. this.attachedElement = null;
  41918. this.checkInputs = function () { };
  41919. };
  41920. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  41921. var inputs = {};
  41922. for (var cam in this.attached) {
  41923. var input = this.attached[cam];
  41924. var res = BABYLON.SerializationHelper.Serialize(input);
  41925. inputs[input.getClassName()] = res;
  41926. }
  41927. serializedCamera.inputsmgr = inputs;
  41928. };
  41929. CameraInputsManager.prototype.parse = function (parsedCamera) {
  41930. var parsedInputs = parsedCamera.inputsmgr;
  41931. if (parsedInputs) {
  41932. this.clear();
  41933. for (var n in parsedInputs) {
  41934. var construct = BABYLON.CameraInputTypes[n];
  41935. if (construct) {
  41936. var parsedinput = parsedInputs[n];
  41937. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  41938. this.add(input);
  41939. }
  41940. }
  41941. }
  41942. else {
  41943. //2016-03-08 this part is for managing backward compatibility
  41944. for (var n in this.attached) {
  41945. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  41946. if (construct) {
  41947. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  41948. this.remove(this.attached[n]);
  41949. this.add(input);
  41950. }
  41951. }
  41952. }
  41953. };
  41954. return CameraInputsManager;
  41955. }());
  41956. BABYLON.CameraInputsManager = CameraInputsManager;
  41957. })(BABYLON || (BABYLON = {}));
  41958. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  41959. var BABYLON;
  41960. (function (BABYLON) {
  41961. var TargetCamera = /** @class */ (function (_super) {
  41962. __extends(TargetCamera, _super);
  41963. function TargetCamera(name, position, scene) {
  41964. var _this = _super.call(this, name, position, scene) || this;
  41965. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41966. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  41967. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  41968. _this.speed = 2.0;
  41969. _this.noRotationConstraint = false;
  41970. _this.lockedTarget = null;
  41971. _this._currentTarget = BABYLON.Vector3.Zero();
  41972. _this._viewMatrix = BABYLON.Matrix.Zero();
  41973. _this._camMatrix = BABYLON.Matrix.Zero();
  41974. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  41975. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  41976. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  41977. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  41978. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  41979. _this._lookAtTemp = BABYLON.Matrix.Zero();
  41980. _this._tempMatrix = BABYLON.Matrix.Zero();
  41981. return _this;
  41982. }
  41983. TargetCamera.prototype.getFrontPosition = function (distance) {
  41984. this.getWorldMatrix();
  41985. var direction = this.getTarget().subtract(this.position);
  41986. direction.normalize();
  41987. direction.scaleInPlace(distance);
  41988. return this.globalPosition.add(direction);
  41989. };
  41990. TargetCamera.prototype._getLockedTargetPosition = function () {
  41991. if (!this.lockedTarget) {
  41992. return null;
  41993. }
  41994. if (this.lockedTarget.absolutePosition) {
  41995. this.lockedTarget.computeWorldMatrix();
  41996. }
  41997. return this.lockedTarget.absolutePosition || this.lockedTarget;
  41998. };
  41999. TargetCamera.prototype.storeState = function () {
  42000. this._storedPosition = this.position.clone();
  42001. this._storedRotation = this.rotation.clone();
  42002. if (this.rotationQuaternion) {
  42003. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42004. }
  42005. return _super.prototype.storeState.call(this);
  42006. };
  42007. /**
  42008. * Restored camera state. You must call storeState() first
  42009. */
  42010. TargetCamera.prototype._restoreStateValues = function () {
  42011. if (!_super.prototype._restoreStateValues.call(this)) {
  42012. return false;
  42013. }
  42014. this.position = this._storedPosition.clone();
  42015. this.rotation = this._storedRotation.clone();
  42016. if (this.rotationQuaternion) {
  42017. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42018. }
  42019. this.cameraDirection.copyFromFloats(0, 0, 0);
  42020. this.cameraRotation.copyFromFloats(0, 0);
  42021. return true;
  42022. };
  42023. // Cache
  42024. TargetCamera.prototype._initCache = function () {
  42025. _super.prototype._initCache.call(this);
  42026. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42027. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42028. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42029. };
  42030. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42031. if (!ignoreParentClass) {
  42032. _super.prototype._updateCache.call(this);
  42033. }
  42034. var lockedTargetPosition = this._getLockedTargetPosition();
  42035. if (!lockedTargetPosition) {
  42036. this._cache.lockedTarget = null;
  42037. }
  42038. else {
  42039. if (!this._cache.lockedTarget) {
  42040. this._cache.lockedTarget = lockedTargetPosition.clone();
  42041. }
  42042. else {
  42043. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42044. }
  42045. }
  42046. this._cache.rotation.copyFrom(this.rotation);
  42047. if (this.rotationQuaternion)
  42048. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42049. };
  42050. // Synchronized
  42051. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42052. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42053. return false;
  42054. }
  42055. var lockedTargetPosition = this._getLockedTargetPosition();
  42056. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42057. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42058. };
  42059. // Methods
  42060. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42061. var engine = this.getEngine();
  42062. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42063. };
  42064. // Target
  42065. TargetCamera.prototype.setTarget = function (target) {
  42066. this.upVector.normalize();
  42067. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42068. this._camMatrix.invert();
  42069. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42070. var vDir = target.subtract(this.position);
  42071. if (vDir.x >= 0.0) {
  42072. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42073. }
  42074. else {
  42075. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42076. }
  42077. this.rotation.z = 0;
  42078. if (isNaN(this.rotation.x)) {
  42079. this.rotation.x = 0;
  42080. }
  42081. if (isNaN(this.rotation.y)) {
  42082. this.rotation.y = 0;
  42083. }
  42084. if (isNaN(this.rotation.z)) {
  42085. this.rotation.z = 0;
  42086. }
  42087. if (this.rotationQuaternion) {
  42088. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42089. }
  42090. };
  42091. /**
  42092. * Return the current target position of the camera. This value is expressed in local space.
  42093. */
  42094. TargetCamera.prototype.getTarget = function () {
  42095. return this._currentTarget;
  42096. };
  42097. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42098. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42099. };
  42100. TargetCamera.prototype._updatePosition = function () {
  42101. if (this.parent) {
  42102. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42103. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42104. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42105. return;
  42106. }
  42107. this.position.addInPlace(this.cameraDirection);
  42108. };
  42109. TargetCamera.prototype._checkInputs = function () {
  42110. var needToMove = this._decideIfNeedsToMove();
  42111. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42112. // Move
  42113. if (needToMove) {
  42114. this._updatePosition();
  42115. }
  42116. // Rotate
  42117. if (needToRotate) {
  42118. this.rotation.x += this.cameraRotation.x;
  42119. this.rotation.y += this.cameraRotation.y;
  42120. //rotate, if quaternion is set and rotation was used
  42121. if (this.rotationQuaternion) {
  42122. var len = this.rotation.lengthSquared();
  42123. if (len) {
  42124. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42125. }
  42126. }
  42127. if (!this.noRotationConstraint) {
  42128. var limit = (Math.PI / 2) * 0.95;
  42129. if (this.rotation.x > limit)
  42130. this.rotation.x = limit;
  42131. if (this.rotation.x < -limit)
  42132. this.rotation.x = -limit;
  42133. }
  42134. }
  42135. // Inertia
  42136. if (needToMove) {
  42137. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42138. this.cameraDirection.x = 0;
  42139. }
  42140. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42141. this.cameraDirection.y = 0;
  42142. }
  42143. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42144. this.cameraDirection.z = 0;
  42145. }
  42146. this.cameraDirection.scaleInPlace(this.inertia);
  42147. }
  42148. if (needToRotate) {
  42149. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42150. this.cameraRotation.x = 0;
  42151. }
  42152. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42153. this.cameraRotation.y = 0;
  42154. }
  42155. this.cameraRotation.scaleInPlace(this.inertia);
  42156. }
  42157. _super.prototype._checkInputs.call(this);
  42158. };
  42159. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42160. if (this.rotationQuaternion) {
  42161. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42162. }
  42163. else {
  42164. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42165. }
  42166. //update the up vector!
  42167. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42168. };
  42169. TargetCamera.prototype._getViewMatrix = function () {
  42170. if (this.lockedTarget) {
  42171. this.setTarget(this._getLockedTargetPosition());
  42172. }
  42173. // Compute
  42174. this._updateCameraRotationMatrix();
  42175. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42176. // Computing target and final matrix
  42177. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42178. if (this.getScene().useRightHandedSystem) {
  42179. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42180. }
  42181. else {
  42182. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42183. }
  42184. return this._viewMatrix;
  42185. };
  42186. /**
  42187. * @override
  42188. * Override Camera.createRigCamera
  42189. */
  42190. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42191. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42192. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42193. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42194. if (!this.rotationQuaternion) {
  42195. this.rotationQuaternion = new BABYLON.Quaternion();
  42196. }
  42197. rigCamera._cameraRigParams = {};
  42198. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42199. }
  42200. return rigCamera;
  42201. }
  42202. return null;
  42203. };
  42204. /**
  42205. * @override
  42206. * Override Camera._updateRigCameras
  42207. */
  42208. TargetCamera.prototype._updateRigCameras = function () {
  42209. var camLeft = this._rigCameras[0];
  42210. var camRight = this._rigCameras[1];
  42211. switch (this.cameraRigMode) {
  42212. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42213. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42214. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42215. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42216. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42217. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42218. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42219. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42220. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42221. camLeft.setTarget(this.getTarget());
  42222. camRight.setTarget(this.getTarget());
  42223. break;
  42224. case BABYLON.Camera.RIG_MODE_VR:
  42225. if (camLeft.rotationQuaternion) {
  42226. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42227. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42228. }
  42229. else {
  42230. camLeft.rotation.copyFrom(this.rotation);
  42231. camRight.rotation.copyFrom(this.rotation);
  42232. }
  42233. camLeft.position.copyFrom(this.position);
  42234. camRight.position.copyFrom(this.position);
  42235. break;
  42236. }
  42237. _super.prototype._updateRigCameras.call(this);
  42238. };
  42239. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42240. if (!this._rigCamTransformMatrix) {
  42241. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42242. }
  42243. var target = this.getTarget();
  42244. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42245. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42246. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42247. };
  42248. TargetCamera.prototype.getClassName = function () {
  42249. return "TargetCamera";
  42250. };
  42251. __decorate([
  42252. BABYLON.serializeAsVector3()
  42253. ], TargetCamera.prototype, "rotation", void 0);
  42254. __decorate([
  42255. BABYLON.serialize()
  42256. ], TargetCamera.prototype, "speed", void 0);
  42257. __decorate([
  42258. BABYLON.serializeAsMeshReference("lockedTargetId")
  42259. ], TargetCamera.prototype, "lockedTarget", void 0);
  42260. return TargetCamera;
  42261. }(BABYLON.Camera));
  42262. BABYLON.TargetCamera = TargetCamera;
  42263. })(BABYLON || (BABYLON = {}));
  42264. //# sourceMappingURL=babylon.targetCamera.js.map
  42265. var BABYLON;
  42266. (function (BABYLON) {
  42267. var FreeCameraMouseInput = /** @class */ (function () {
  42268. function FreeCameraMouseInput(touchEnabled) {
  42269. if (touchEnabled === void 0) { touchEnabled = true; }
  42270. this.touchEnabled = touchEnabled;
  42271. this.buttons = [0, 1, 2];
  42272. this.angularSensibility = 2000.0;
  42273. this.previousPosition = null;
  42274. }
  42275. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42276. var _this = this;
  42277. var engine = this.camera.getEngine();
  42278. if (!this._pointerInput) {
  42279. this._pointerInput = function (p, s) {
  42280. var evt = p.event;
  42281. if (engine.isInVRExclusivePointerMode) {
  42282. return;
  42283. }
  42284. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42285. return;
  42286. }
  42287. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42288. return;
  42289. }
  42290. var srcElement = (evt.srcElement || evt.target);
  42291. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42292. try {
  42293. srcElement.setPointerCapture(evt.pointerId);
  42294. }
  42295. catch (e) {
  42296. //Nothing to do with the error. Execution will continue.
  42297. }
  42298. _this.previousPosition = {
  42299. x: evt.clientX,
  42300. y: evt.clientY
  42301. };
  42302. if (!noPreventDefault) {
  42303. evt.preventDefault();
  42304. element.focus();
  42305. }
  42306. }
  42307. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42308. try {
  42309. srcElement.releasePointerCapture(evt.pointerId);
  42310. }
  42311. catch (e) {
  42312. //Nothing to do with the error.
  42313. }
  42314. _this.previousPosition = null;
  42315. if (!noPreventDefault) {
  42316. evt.preventDefault();
  42317. }
  42318. }
  42319. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42320. if (!_this.previousPosition || engine.isPointerLock) {
  42321. return;
  42322. }
  42323. var offsetX = evt.clientX - _this.previousPosition.x;
  42324. var offsetY = evt.clientY - _this.previousPosition.y;
  42325. if (_this.camera.getScene().useRightHandedSystem) {
  42326. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42327. }
  42328. else {
  42329. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42330. }
  42331. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42332. _this.previousPosition = {
  42333. x: evt.clientX,
  42334. y: evt.clientY
  42335. };
  42336. if (!noPreventDefault) {
  42337. evt.preventDefault();
  42338. }
  42339. }
  42340. };
  42341. }
  42342. this._onMouseMove = function (evt) {
  42343. if (!engine.isPointerLock) {
  42344. return;
  42345. }
  42346. if (engine.isInVRExclusivePointerMode) {
  42347. return;
  42348. }
  42349. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42350. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42351. if (_this.camera.getScene().useRightHandedSystem) {
  42352. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42353. }
  42354. else {
  42355. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42356. }
  42357. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42358. _this.previousPosition = null;
  42359. if (!noPreventDefault) {
  42360. evt.preventDefault();
  42361. }
  42362. };
  42363. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42364. element.addEventListener("mousemove", this._onMouseMove, false);
  42365. };
  42366. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42367. if (this._observer && element) {
  42368. this.camera.getScene().onPointerObservable.remove(this._observer);
  42369. if (this._onMouseMove) {
  42370. element.removeEventListener("mousemove", this._onMouseMove);
  42371. }
  42372. this._observer = null;
  42373. this._onMouseMove = null;
  42374. this.previousPosition = null;
  42375. }
  42376. };
  42377. FreeCameraMouseInput.prototype.getClassName = function () {
  42378. return "FreeCameraMouseInput";
  42379. };
  42380. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42381. return "mouse";
  42382. };
  42383. __decorate([
  42384. BABYLON.serialize()
  42385. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42386. __decorate([
  42387. BABYLON.serialize()
  42388. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42389. return FreeCameraMouseInput;
  42390. }());
  42391. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42392. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42393. })(BABYLON || (BABYLON = {}));
  42394. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42395. var BABYLON;
  42396. (function (BABYLON) {
  42397. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42398. function FreeCameraKeyboardMoveInput() {
  42399. this._keys = new Array();
  42400. this.keysUp = [38];
  42401. this.keysDown = [40];
  42402. this.keysLeft = [37];
  42403. this.keysRight = [39];
  42404. }
  42405. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42406. var _this = this;
  42407. if (this._onCanvasBlurObserver) {
  42408. return;
  42409. }
  42410. this._scene = this.camera.getScene();
  42411. this._engine = this._scene.getEngine();
  42412. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42413. _this._keys = [];
  42414. });
  42415. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42416. var evt = info.event;
  42417. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42418. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42419. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42420. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42421. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42422. var index = _this._keys.indexOf(evt.keyCode);
  42423. if (index === -1) {
  42424. _this._keys.push(evt.keyCode);
  42425. }
  42426. if (!noPreventDefault) {
  42427. evt.preventDefault();
  42428. }
  42429. }
  42430. }
  42431. else {
  42432. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42433. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42434. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42435. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42436. var index = _this._keys.indexOf(evt.keyCode);
  42437. if (index >= 0) {
  42438. _this._keys.splice(index, 1);
  42439. }
  42440. if (!noPreventDefault) {
  42441. evt.preventDefault();
  42442. }
  42443. }
  42444. }
  42445. });
  42446. };
  42447. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42448. if (this._scene) {
  42449. if (this._onKeyboardObserver) {
  42450. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42451. }
  42452. if (this._onCanvasBlurObserver) {
  42453. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42454. }
  42455. this._onKeyboardObserver = null;
  42456. this._onCanvasBlurObserver = null;
  42457. }
  42458. this._keys = [];
  42459. };
  42460. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42461. if (this._onKeyboardObserver) {
  42462. var camera = this.camera;
  42463. // Keyboard
  42464. for (var index = 0; index < this._keys.length; index++) {
  42465. var keyCode = this._keys[index];
  42466. var speed = camera._computeLocalCameraSpeed();
  42467. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42468. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42469. }
  42470. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42471. camera._localDirection.copyFromFloats(0, 0, speed);
  42472. }
  42473. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42474. camera._localDirection.copyFromFloats(speed, 0, 0);
  42475. }
  42476. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42477. camera._localDirection.copyFromFloats(0, 0, -speed);
  42478. }
  42479. if (camera.getScene().useRightHandedSystem) {
  42480. camera._localDirection.z *= -1;
  42481. }
  42482. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42483. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42484. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42485. }
  42486. }
  42487. };
  42488. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42489. return "FreeCameraKeyboardMoveInput";
  42490. };
  42491. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42492. this._keys = [];
  42493. };
  42494. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42495. return "keyboard";
  42496. };
  42497. __decorate([
  42498. BABYLON.serialize()
  42499. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42500. __decorate([
  42501. BABYLON.serialize()
  42502. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42503. __decorate([
  42504. BABYLON.serialize()
  42505. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42506. __decorate([
  42507. BABYLON.serialize()
  42508. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42509. return FreeCameraKeyboardMoveInput;
  42510. }());
  42511. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42512. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42513. })(BABYLON || (BABYLON = {}));
  42514. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42515. var BABYLON;
  42516. (function (BABYLON) {
  42517. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42518. __extends(FreeCameraInputsManager, _super);
  42519. function FreeCameraInputsManager(camera) {
  42520. return _super.call(this, camera) || this;
  42521. }
  42522. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42523. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42524. return this;
  42525. };
  42526. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42527. if (touchEnabled === void 0) { touchEnabled = true; }
  42528. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42529. return this;
  42530. };
  42531. FreeCameraInputsManager.prototype.addGamepad = function () {
  42532. this.add(new BABYLON.FreeCameraGamepadInput());
  42533. return this;
  42534. };
  42535. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42536. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42537. return this;
  42538. };
  42539. FreeCameraInputsManager.prototype.addTouch = function () {
  42540. this.add(new BABYLON.FreeCameraTouchInput());
  42541. return this;
  42542. };
  42543. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42544. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42545. return this;
  42546. };
  42547. return FreeCameraInputsManager;
  42548. }(BABYLON.CameraInputsManager));
  42549. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42550. })(BABYLON || (BABYLON = {}));
  42551. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42552. var BABYLON;
  42553. (function (BABYLON) {
  42554. var FreeCamera = /** @class */ (function (_super) {
  42555. __extends(FreeCamera, _super);
  42556. function FreeCamera(name, position, scene) {
  42557. var _this = _super.call(this, name, position, scene) || this;
  42558. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42559. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42560. _this.checkCollisions = false;
  42561. _this.applyGravity = false;
  42562. _this._needMoveForGravity = false;
  42563. _this._oldPosition = BABYLON.Vector3.Zero();
  42564. _this._diffPosition = BABYLON.Vector3.Zero();
  42565. _this._newPosition = BABYLON.Vector3.Zero();
  42566. // Collisions
  42567. _this._collisionMask = -1;
  42568. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42569. if (collidedMesh === void 0) { collidedMesh = null; }
  42570. //TODO move this to the collision coordinator!
  42571. if (_this.getScene().workerCollisions)
  42572. newPosition.multiplyInPlace(_this._collider._radius);
  42573. var updatePosition = function (newPos) {
  42574. _this._newPosition.copyFrom(newPos);
  42575. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42576. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42577. _this.position.addInPlace(_this._diffPosition);
  42578. if (_this.onCollide && collidedMesh) {
  42579. _this.onCollide(collidedMesh);
  42580. }
  42581. }
  42582. };
  42583. updatePosition(newPosition);
  42584. };
  42585. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42586. _this.inputs.addKeyboard().addMouse();
  42587. return _this;
  42588. }
  42589. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42590. //-- begin properties for backward compatibility for inputs
  42591. /**
  42592. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42593. * Higher values reduce sensitivity.
  42594. */
  42595. get: function () {
  42596. var mouse = this.inputs.attached["mouse"];
  42597. if (mouse)
  42598. return mouse.angularSensibility;
  42599. return 0;
  42600. },
  42601. /**
  42602. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42603. * Higher values reduce sensitivity.
  42604. */
  42605. set: function (value) {
  42606. var mouse = this.inputs.attached["mouse"];
  42607. if (mouse)
  42608. mouse.angularSensibility = value;
  42609. },
  42610. enumerable: true,
  42611. configurable: true
  42612. });
  42613. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42614. get: function () {
  42615. var keyboard = this.inputs.attached["keyboard"];
  42616. if (keyboard)
  42617. return keyboard.keysUp;
  42618. return [];
  42619. },
  42620. set: function (value) {
  42621. var keyboard = this.inputs.attached["keyboard"];
  42622. if (keyboard)
  42623. keyboard.keysUp = value;
  42624. },
  42625. enumerable: true,
  42626. configurable: true
  42627. });
  42628. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42629. get: function () {
  42630. var keyboard = this.inputs.attached["keyboard"];
  42631. if (keyboard)
  42632. return keyboard.keysDown;
  42633. return [];
  42634. },
  42635. set: function (value) {
  42636. var keyboard = this.inputs.attached["keyboard"];
  42637. if (keyboard)
  42638. keyboard.keysDown = value;
  42639. },
  42640. enumerable: true,
  42641. configurable: true
  42642. });
  42643. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42644. get: function () {
  42645. var keyboard = this.inputs.attached["keyboard"];
  42646. if (keyboard)
  42647. return keyboard.keysLeft;
  42648. return [];
  42649. },
  42650. set: function (value) {
  42651. var keyboard = this.inputs.attached["keyboard"];
  42652. if (keyboard)
  42653. keyboard.keysLeft = value;
  42654. },
  42655. enumerable: true,
  42656. configurable: true
  42657. });
  42658. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  42659. get: function () {
  42660. var keyboard = this.inputs.attached["keyboard"];
  42661. if (keyboard)
  42662. return keyboard.keysRight;
  42663. return [];
  42664. },
  42665. set: function (value) {
  42666. var keyboard = this.inputs.attached["keyboard"];
  42667. if (keyboard)
  42668. keyboard.keysRight = value;
  42669. },
  42670. enumerable: true,
  42671. configurable: true
  42672. });
  42673. // Controls
  42674. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  42675. this.inputs.attachElement(element, noPreventDefault);
  42676. };
  42677. FreeCamera.prototype.detachControl = function (element) {
  42678. this.inputs.detachElement(element);
  42679. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42680. this.cameraRotation = new BABYLON.Vector2(0, 0);
  42681. };
  42682. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  42683. get: function () {
  42684. return this._collisionMask;
  42685. },
  42686. set: function (mask) {
  42687. this._collisionMask = !isNaN(mask) ? mask : -1;
  42688. },
  42689. enumerable: true,
  42690. configurable: true
  42691. });
  42692. FreeCamera.prototype._collideWithWorld = function (displacement) {
  42693. var globalPosition;
  42694. if (this.parent) {
  42695. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  42696. }
  42697. else {
  42698. globalPosition = this.position;
  42699. }
  42700. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  42701. this._oldPosition.addInPlace(this.ellipsoidOffset);
  42702. if (!this._collider) {
  42703. this._collider = new BABYLON.Collider();
  42704. }
  42705. this._collider._radius = this.ellipsoid;
  42706. this._collider.collisionMask = this._collisionMask;
  42707. //no need for clone, as long as gravity is not on.
  42708. var actualDisplacement = displacement;
  42709. //add gravity to the direction to prevent the dual-collision checking
  42710. if (this.applyGravity) {
  42711. //this prevents mending with cameraDirection, a global variable of the free camera class.
  42712. actualDisplacement = displacement.add(this.getScene().gravity);
  42713. }
  42714. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42715. };
  42716. FreeCamera.prototype._checkInputs = function () {
  42717. if (!this._localDirection) {
  42718. this._localDirection = BABYLON.Vector3.Zero();
  42719. this._transformedDirection = BABYLON.Vector3.Zero();
  42720. }
  42721. this.inputs.checkInputs();
  42722. _super.prototype._checkInputs.call(this);
  42723. };
  42724. FreeCamera.prototype._decideIfNeedsToMove = function () {
  42725. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42726. };
  42727. FreeCamera.prototype._updatePosition = function () {
  42728. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  42729. this._collideWithWorld(this.cameraDirection);
  42730. }
  42731. else {
  42732. _super.prototype._updatePosition.call(this);
  42733. }
  42734. };
  42735. FreeCamera.prototype.dispose = function () {
  42736. this.inputs.clear();
  42737. _super.prototype.dispose.call(this);
  42738. };
  42739. FreeCamera.prototype.getClassName = function () {
  42740. return "FreeCamera";
  42741. };
  42742. __decorate([
  42743. BABYLON.serializeAsVector3()
  42744. ], FreeCamera.prototype, "ellipsoid", void 0);
  42745. __decorate([
  42746. BABYLON.serializeAsVector3()
  42747. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  42748. __decorate([
  42749. BABYLON.serialize()
  42750. ], FreeCamera.prototype, "checkCollisions", void 0);
  42751. __decorate([
  42752. BABYLON.serialize()
  42753. ], FreeCamera.prototype, "applyGravity", void 0);
  42754. return FreeCamera;
  42755. }(BABYLON.TargetCamera));
  42756. BABYLON.FreeCamera = FreeCamera;
  42757. })(BABYLON || (BABYLON = {}));
  42758. //# sourceMappingURL=babylon.freeCamera.js.map
  42759. var BABYLON;
  42760. (function (BABYLON) {
  42761. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  42762. function ArcRotateCameraKeyboardMoveInput() {
  42763. this._keys = new Array();
  42764. this.keysUp = [38];
  42765. this.keysDown = [40];
  42766. this.keysLeft = [37];
  42767. this.keysRight = [39];
  42768. this.keysReset = [220];
  42769. this.panningSensibility = 50.0;
  42770. this.zoomingSensibility = 25.0;
  42771. this.useAltToZoom = true;
  42772. }
  42773. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42774. var _this = this;
  42775. if (this._onCanvasBlurObserver) {
  42776. return;
  42777. }
  42778. this._scene = this.camera.getScene();
  42779. this._engine = this._scene.getEngine();
  42780. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42781. _this._keys = [];
  42782. });
  42783. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42784. var evt = info.event;
  42785. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42786. _this._ctrlPressed = evt.ctrlKey;
  42787. _this._altPressed = evt.altKey;
  42788. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42789. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42790. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42791. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  42792. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  42793. var index = _this._keys.indexOf(evt.keyCode);
  42794. if (index === -1) {
  42795. _this._keys.push(evt.keyCode);
  42796. }
  42797. if (evt.preventDefault) {
  42798. if (!noPreventDefault) {
  42799. evt.preventDefault();
  42800. }
  42801. }
  42802. }
  42803. }
  42804. else {
  42805. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42806. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42807. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42808. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  42809. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  42810. var index = _this._keys.indexOf(evt.keyCode);
  42811. if (index >= 0) {
  42812. _this._keys.splice(index, 1);
  42813. }
  42814. if (evt.preventDefault) {
  42815. if (!noPreventDefault) {
  42816. evt.preventDefault();
  42817. }
  42818. }
  42819. }
  42820. }
  42821. });
  42822. };
  42823. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42824. if (this._scene) {
  42825. if (this._onKeyboardObserver) {
  42826. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42827. }
  42828. if (this._onCanvasBlurObserver) {
  42829. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42830. }
  42831. this._onKeyboardObserver = null;
  42832. this._onCanvasBlurObserver = null;
  42833. }
  42834. this._keys = [];
  42835. };
  42836. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42837. if (this._onKeyboardObserver) {
  42838. var camera = this.camera;
  42839. for (var index = 0; index < this._keys.length; index++) {
  42840. var keyCode = this._keys[index];
  42841. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42842. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  42843. camera.inertialPanningX -= 1 / this.panningSensibility;
  42844. }
  42845. else {
  42846. camera.inertialAlphaOffset -= 0.01;
  42847. }
  42848. }
  42849. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42850. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  42851. camera.inertialPanningY += 1 / this.panningSensibility;
  42852. }
  42853. else if (this._altPressed && this.useAltToZoom) {
  42854. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  42855. }
  42856. else {
  42857. camera.inertialBetaOffset -= 0.01;
  42858. }
  42859. }
  42860. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42861. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  42862. camera.inertialPanningX += 1 / this.panningSensibility;
  42863. }
  42864. else {
  42865. camera.inertialAlphaOffset += 0.01;
  42866. }
  42867. }
  42868. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42869. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  42870. camera.inertialPanningY -= 1 / this.panningSensibility;
  42871. }
  42872. else if (this._altPressed && this.useAltToZoom) {
  42873. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  42874. }
  42875. else {
  42876. camera.inertialBetaOffset += 0.01;
  42877. }
  42878. }
  42879. else if (this.keysReset.indexOf(keyCode) !== -1) {
  42880. camera.restoreState();
  42881. }
  42882. }
  42883. }
  42884. };
  42885. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  42886. return "ArcRotateCameraKeyboardMoveInput";
  42887. };
  42888. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42889. return "keyboard";
  42890. };
  42891. __decorate([
  42892. BABYLON.serialize()
  42893. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42894. __decorate([
  42895. BABYLON.serialize()
  42896. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42897. __decorate([
  42898. BABYLON.serialize()
  42899. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42900. __decorate([
  42901. BABYLON.serialize()
  42902. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42903. __decorate([
  42904. BABYLON.serialize()
  42905. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  42906. __decorate([
  42907. BABYLON.serialize()
  42908. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  42909. __decorate([
  42910. BABYLON.serialize()
  42911. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  42912. __decorate([
  42913. BABYLON.serialize()
  42914. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  42915. return ArcRotateCameraKeyboardMoveInput;
  42916. }());
  42917. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  42918. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  42919. })(BABYLON || (BABYLON = {}));
  42920. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  42921. var BABYLON;
  42922. (function (BABYLON) {
  42923. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  42924. function ArcRotateCameraMouseWheelInput() {
  42925. this.wheelPrecision = 3.0;
  42926. /**
  42927. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  42928. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  42929. */
  42930. this.wheelDeltaPercentage = 0;
  42931. }
  42932. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  42933. var _this = this;
  42934. this._wheel = function (p, s) {
  42935. //sanity check - this should be a PointerWheel event.
  42936. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  42937. return;
  42938. var event = p.event;
  42939. var delta = 0;
  42940. if (event.wheelDelta) {
  42941. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  42942. }
  42943. else if (event.detail) {
  42944. delta = -event.detail / _this.wheelPrecision;
  42945. }
  42946. if (delta)
  42947. _this.camera.inertialRadiusOffset += delta;
  42948. if (event.preventDefault) {
  42949. if (!noPreventDefault) {
  42950. event.preventDefault();
  42951. }
  42952. }
  42953. };
  42954. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  42955. };
  42956. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  42957. if (this._observer && element) {
  42958. this.camera.getScene().onPointerObservable.remove(this._observer);
  42959. this._observer = null;
  42960. this._wheel = null;
  42961. }
  42962. };
  42963. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  42964. return "ArcRotateCameraMouseWheelInput";
  42965. };
  42966. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  42967. return "mousewheel";
  42968. };
  42969. __decorate([
  42970. BABYLON.serialize()
  42971. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  42972. __decorate([
  42973. BABYLON.serialize()
  42974. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  42975. return ArcRotateCameraMouseWheelInput;
  42976. }());
  42977. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  42978. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  42979. })(BABYLON || (BABYLON = {}));
  42980. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  42981. var BABYLON;
  42982. (function (BABYLON) {
  42983. var ArcRotateCameraPointersInput = /** @class */ (function () {
  42984. function ArcRotateCameraPointersInput() {
  42985. this.buttons = [0, 1, 2];
  42986. this.angularSensibilityX = 1000.0;
  42987. this.angularSensibilityY = 1000.0;
  42988. this.pinchPrecision = 12.0;
  42989. /**
  42990. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  42991. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  42992. */
  42993. this.pinchDeltaPercentage = 0;
  42994. this.panningSensibility = 1000.0;
  42995. this.multiTouchPanning = true;
  42996. this.multiTouchPanAndZoom = true;
  42997. this._isPanClick = false;
  42998. this.pinchInwards = true;
  42999. }
  43000. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43001. var _this = this;
  43002. var engine = this.camera.getEngine();
  43003. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43004. var pointA = null;
  43005. var pointB = null;
  43006. var previousPinchSquaredDistance = 0;
  43007. var initialDistance = 0;
  43008. var twoFingerActivityCount = 0;
  43009. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43010. this._pointerInput = function (p, s) {
  43011. var evt = p.event;
  43012. var isTouch = p.event.pointerType === "touch";
  43013. if (engine.isInVRExclusivePointerMode) {
  43014. return;
  43015. }
  43016. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43017. return;
  43018. }
  43019. var srcElement = (evt.srcElement || evt.target);
  43020. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43021. try {
  43022. srcElement.setPointerCapture(evt.pointerId);
  43023. }
  43024. catch (e) {
  43025. //Nothing to do with the error. Execution will continue.
  43026. }
  43027. // Manage panning with pan button click
  43028. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43029. // manage pointers
  43030. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43031. if (pointA === null) {
  43032. pointA = cacheSoloPointer;
  43033. }
  43034. else if (pointB === null) {
  43035. pointB = cacheSoloPointer;
  43036. }
  43037. if (!noPreventDefault) {
  43038. evt.preventDefault();
  43039. element.focus();
  43040. }
  43041. }
  43042. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43043. _this.camera.restoreState();
  43044. }
  43045. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43046. try {
  43047. srcElement.releasePointerCapture(evt.pointerId);
  43048. }
  43049. catch (e) {
  43050. //Nothing to do with the error.
  43051. }
  43052. cacheSoloPointer = null;
  43053. previousPinchSquaredDistance = 0;
  43054. previousMultiTouchPanPosition.isPaning = false;
  43055. previousMultiTouchPanPosition.isPinching = false;
  43056. twoFingerActivityCount = 0;
  43057. initialDistance = 0;
  43058. if (!isTouch) {
  43059. pointB = null; // Mouse and pen are mono pointer
  43060. }
  43061. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43062. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43063. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43064. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43065. if (engine.badOS) {
  43066. pointA = pointB = null;
  43067. }
  43068. else {
  43069. //only remove the impacted pointer in case of multitouch allowing on most
  43070. //platforms switching from rotate to zoom and pan seamlessly.
  43071. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43072. pointA = pointB;
  43073. pointB = null;
  43074. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43075. }
  43076. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43077. pointB = null;
  43078. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43079. }
  43080. else {
  43081. pointA = pointB = null;
  43082. }
  43083. }
  43084. if (!noPreventDefault) {
  43085. evt.preventDefault();
  43086. }
  43087. }
  43088. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43089. if (!noPreventDefault) {
  43090. evt.preventDefault();
  43091. }
  43092. // One button down
  43093. if (pointA && pointB === null && cacheSoloPointer) {
  43094. if (_this.panningSensibility !== 0 &&
  43095. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43096. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43097. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43098. }
  43099. else {
  43100. var offsetX = evt.clientX - cacheSoloPointer.x;
  43101. var offsetY = evt.clientY - cacheSoloPointer.y;
  43102. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43103. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43104. }
  43105. cacheSoloPointer.x = evt.clientX;
  43106. cacheSoloPointer.y = evt.clientY;
  43107. }
  43108. else if (pointA && pointB) {
  43109. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43110. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43111. ed.x = evt.clientX;
  43112. ed.y = evt.clientY;
  43113. var direction = _this.pinchInwards ? 1 : -1;
  43114. var distX = pointA.x - pointB.x;
  43115. var distY = pointA.y - pointB.y;
  43116. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43117. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43118. if (previousPinchSquaredDistance === 0) {
  43119. initialDistance = pinchDistance;
  43120. previousPinchSquaredDistance = pinchSquaredDistance;
  43121. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43122. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43123. return;
  43124. }
  43125. if (_this.multiTouchPanAndZoom) {
  43126. if (_this.pinchDeltaPercentage) {
  43127. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43128. }
  43129. else {
  43130. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43131. (_this.pinchPrecision *
  43132. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43133. direction);
  43134. }
  43135. if (_this.panningSensibility !== 0) {
  43136. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43137. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43138. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43139. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43140. previousMultiTouchPanPosition.x = pointersCenterX;
  43141. previousMultiTouchPanPosition.y = pointersCenterY;
  43142. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43143. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43144. }
  43145. }
  43146. else {
  43147. twoFingerActivityCount++;
  43148. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43149. if (_this.pinchDeltaPercentage) {
  43150. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43151. }
  43152. else {
  43153. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43154. (_this.pinchPrecision *
  43155. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43156. direction);
  43157. }
  43158. previousMultiTouchPanPosition.isPaning = false;
  43159. previousMultiTouchPanPosition.isPinching = true;
  43160. }
  43161. else {
  43162. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43163. if (!previousMultiTouchPanPosition.isPaning) {
  43164. previousMultiTouchPanPosition.isPaning = true;
  43165. previousMultiTouchPanPosition.isPinching = false;
  43166. previousMultiTouchPanPosition.x = ed.x;
  43167. previousMultiTouchPanPosition.y = ed.y;
  43168. return;
  43169. }
  43170. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43171. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43172. }
  43173. }
  43174. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43175. previousMultiTouchPanPosition.x = ed.x;
  43176. previousMultiTouchPanPosition.y = ed.y;
  43177. }
  43178. }
  43179. previousPinchSquaredDistance = pinchSquaredDistance;
  43180. }
  43181. }
  43182. };
  43183. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43184. this._onContextMenu = function (evt) {
  43185. evt.preventDefault();
  43186. };
  43187. if (!this.camera._useCtrlForPanning) {
  43188. element.addEventListener("contextmenu", this._onContextMenu, false);
  43189. }
  43190. this._onLostFocus = function () {
  43191. //this._keys = [];
  43192. pointA = pointB = null;
  43193. previousPinchSquaredDistance = 0;
  43194. previousMultiTouchPanPosition.isPaning = false;
  43195. previousMultiTouchPanPosition.isPinching = false;
  43196. twoFingerActivityCount = 0;
  43197. cacheSoloPointer = null;
  43198. initialDistance = 0;
  43199. };
  43200. this._onMouseMove = function (evt) {
  43201. if (!engine.isPointerLock) {
  43202. return;
  43203. }
  43204. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43205. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43206. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43207. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43208. if (!noPreventDefault) {
  43209. evt.preventDefault();
  43210. }
  43211. };
  43212. this._onGestureStart = function (e) {
  43213. if (window.MSGesture === undefined) {
  43214. return;
  43215. }
  43216. if (!_this._MSGestureHandler) {
  43217. _this._MSGestureHandler = new MSGesture();
  43218. _this._MSGestureHandler.target = element;
  43219. }
  43220. _this._MSGestureHandler.addPointer(e.pointerId);
  43221. };
  43222. this._onGesture = function (e) {
  43223. _this.camera.radius *= e.scale;
  43224. if (e.preventDefault) {
  43225. if (!noPreventDefault) {
  43226. e.stopPropagation();
  43227. e.preventDefault();
  43228. }
  43229. }
  43230. };
  43231. element.addEventListener("mousemove", this._onMouseMove, false);
  43232. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43233. element.addEventListener("MSGestureChange", this._onGesture, false);
  43234. BABYLON.Tools.RegisterTopRootEvents([
  43235. { name: "blur", handler: this._onLostFocus }
  43236. ]);
  43237. };
  43238. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43239. if (this._onLostFocus) {
  43240. BABYLON.Tools.UnregisterTopRootEvents([
  43241. { name: "blur", handler: this._onLostFocus }
  43242. ]);
  43243. }
  43244. if (element && this._observer) {
  43245. this.camera.getScene().onPointerObservable.remove(this._observer);
  43246. this._observer = null;
  43247. if (this._onContextMenu) {
  43248. element.removeEventListener("contextmenu", this._onContextMenu);
  43249. }
  43250. if (this._onMouseMove) {
  43251. element.removeEventListener("mousemove", this._onMouseMove);
  43252. }
  43253. if (this._onGestureStart) {
  43254. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43255. }
  43256. if (this._onGesture) {
  43257. element.removeEventListener("MSGestureChange", this._onGesture);
  43258. }
  43259. this._isPanClick = false;
  43260. this.pinchInwards = true;
  43261. this._onMouseMove = null;
  43262. this._onGestureStart = null;
  43263. this._onGesture = null;
  43264. this._MSGestureHandler = null;
  43265. this._onLostFocus = null;
  43266. this._onContextMenu = null;
  43267. }
  43268. };
  43269. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43270. return "ArcRotateCameraPointersInput";
  43271. };
  43272. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43273. return "pointers";
  43274. };
  43275. __decorate([
  43276. BABYLON.serialize()
  43277. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43278. __decorate([
  43279. BABYLON.serialize()
  43280. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43281. __decorate([
  43282. BABYLON.serialize()
  43283. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43284. __decorate([
  43285. BABYLON.serialize()
  43286. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43287. __decorate([
  43288. BABYLON.serialize()
  43289. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43290. __decorate([
  43291. BABYLON.serialize()
  43292. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43293. __decorate([
  43294. BABYLON.serialize()
  43295. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43296. __decorate([
  43297. BABYLON.serialize()
  43298. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43299. return ArcRotateCameraPointersInput;
  43300. }());
  43301. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43302. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43303. })(BABYLON || (BABYLON = {}));
  43304. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43305. var BABYLON;
  43306. (function (BABYLON) {
  43307. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43308. __extends(ArcRotateCameraInputsManager, _super);
  43309. function ArcRotateCameraInputsManager(camera) {
  43310. return _super.call(this, camera) || this;
  43311. }
  43312. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43313. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43314. return this;
  43315. };
  43316. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43317. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43318. return this;
  43319. };
  43320. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43321. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43322. return this;
  43323. };
  43324. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43325. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43326. return this;
  43327. };
  43328. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43329. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43330. return this;
  43331. };
  43332. return ArcRotateCameraInputsManager;
  43333. }(BABYLON.CameraInputsManager));
  43334. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43335. })(BABYLON || (BABYLON = {}));
  43336. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43337. var BABYLON;
  43338. (function (BABYLON) {
  43339. var ArcRotateCamera = /** @class */ (function (_super) {
  43340. __extends(ArcRotateCamera, _super);
  43341. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43342. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43343. _this.inertialAlphaOffset = 0;
  43344. _this.inertialBetaOffset = 0;
  43345. _this.inertialRadiusOffset = 0;
  43346. _this.lowerAlphaLimit = null;
  43347. _this.upperAlphaLimit = null;
  43348. _this.lowerBetaLimit = 0.01;
  43349. _this.upperBetaLimit = Math.PI;
  43350. _this.lowerRadiusLimit = null;
  43351. _this.upperRadiusLimit = null;
  43352. _this.inertialPanningX = 0;
  43353. _this.inertialPanningY = 0;
  43354. _this.pinchToPanMaxDistance = 20;
  43355. _this.panningDistanceLimit = null;
  43356. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43357. _this.panningInertia = 0.9;
  43358. //-- end properties for backward compatibility for inputs
  43359. _this.zoomOnFactor = 1;
  43360. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43361. _this.allowUpsideDown = true;
  43362. _this._viewMatrix = new BABYLON.Matrix();
  43363. // Panning
  43364. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43365. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43366. _this.checkCollisions = false;
  43367. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43368. _this._previousPosition = BABYLON.Vector3.Zero();
  43369. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43370. _this._newPosition = BABYLON.Vector3.Zero();
  43371. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43372. if (collidedMesh === void 0) { collidedMesh = null; }
  43373. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43374. newPosition.multiplyInPlace(_this._collider._radius);
  43375. }
  43376. if (!collidedMesh) {
  43377. _this._previousPosition.copyFrom(_this.position);
  43378. }
  43379. else {
  43380. _this.setPosition(newPosition);
  43381. if (_this.onCollide) {
  43382. _this.onCollide(collidedMesh);
  43383. }
  43384. }
  43385. // Recompute because of constraints
  43386. var cosa = Math.cos(_this.alpha);
  43387. var sina = Math.sin(_this.alpha);
  43388. var cosb = Math.cos(_this.beta);
  43389. var sinb = Math.sin(_this.beta);
  43390. if (sinb === 0) {
  43391. sinb = 0.0001;
  43392. }
  43393. var target = _this._getTargetPosition();
  43394. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43395. _this.position.copyFrom(_this._newPosition);
  43396. var up = _this.upVector;
  43397. if (_this.allowUpsideDown && _this.beta < 0) {
  43398. up = up.clone();
  43399. up = up.negate();
  43400. }
  43401. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43402. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43403. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43404. _this._collisionTriggered = false;
  43405. };
  43406. _this._target = BABYLON.Vector3.Zero();
  43407. if (target) {
  43408. _this.setTarget(target);
  43409. }
  43410. _this.alpha = alpha;
  43411. _this.beta = beta;
  43412. _this.radius = radius;
  43413. _this.getViewMatrix();
  43414. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43415. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43416. return _this;
  43417. }
  43418. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43419. get: function () {
  43420. return this._target;
  43421. },
  43422. set: function (value) {
  43423. this.setTarget(value);
  43424. },
  43425. enumerable: true,
  43426. configurable: true
  43427. });
  43428. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43429. //-- begin properties for backward compatibility for inputs
  43430. get: function () {
  43431. var pointers = this.inputs.attached["pointers"];
  43432. if (pointers)
  43433. return pointers.angularSensibilityX;
  43434. return 0;
  43435. },
  43436. set: function (value) {
  43437. var pointers = this.inputs.attached["pointers"];
  43438. if (pointers) {
  43439. pointers.angularSensibilityX = value;
  43440. }
  43441. },
  43442. enumerable: true,
  43443. configurable: true
  43444. });
  43445. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43446. get: function () {
  43447. var pointers = this.inputs.attached["pointers"];
  43448. if (pointers)
  43449. return pointers.angularSensibilityY;
  43450. return 0;
  43451. },
  43452. set: function (value) {
  43453. var pointers = this.inputs.attached["pointers"];
  43454. if (pointers) {
  43455. pointers.angularSensibilityY = value;
  43456. }
  43457. },
  43458. enumerable: true,
  43459. configurable: true
  43460. });
  43461. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43462. get: function () {
  43463. var pointers = this.inputs.attached["pointers"];
  43464. if (pointers)
  43465. return pointers.pinchPrecision;
  43466. return 0;
  43467. },
  43468. set: function (value) {
  43469. var pointers = this.inputs.attached["pointers"];
  43470. if (pointers) {
  43471. pointers.pinchPrecision = value;
  43472. }
  43473. },
  43474. enumerable: true,
  43475. configurable: true
  43476. });
  43477. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43478. get: function () {
  43479. var pointers = this.inputs.attached["pointers"];
  43480. if (pointers)
  43481. return pointers.pinchDeltaPercentage;
  43482. return 0;
  43483. },
  43484. set: function (value) {
  43485. var pointers = this.inputs.attached["pointers"];
  43486. if (pointers) {
  43487. pointers.pinchDeltaPercentage = value;
  43488. }
  43489. },
  43490. enumerable: true,
  43491. configurable: true
  43492. });
  43493. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43494. get: function () {
  43495. var pointers = this.inputs.attached["pointers"];
  43496. if (pointers)
  43497. return pointers.panningSensibility;
  43498. return 0;
  43499. },
  43500. set: function (value) {
  43501. var pointers = this.inputs.attached["pointers"];
  43502. if (pointers) {
  43503. pointers.panningSensibility = value;
  43504. }
  43505. },
  43506. enumerable: true,
  43507. configurable: true
  43508. });
  43509. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43510. get: function () {
  43511. var keyboard = this.inputs.attached["keyboard"];
  43512. if (keyboard)
  43513. return keyboard.keysUp;
  43514. return [];
  43515. },
  43516. set: function (value) {
  43517. var keyboard = this.inputs.attached["keyboard"];
  43518. if (keyboard)
  43519. keyboard.keysUp = value;
  43520. },
  43521. enumerable: true,
  43522. configurable: true
  43523. });
  43524. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43525. get: function () {
  43526. var keyboard = this.inputs.attached["keyboard"];
  43527. if (keyboard)
  43528. return keyboard.keysDown;
  43529. return [];
  43530. },
  43531. set: function (value) {
  43532. var keyboard = this.inputs.attached["keyboard"];
  43533. if (keyboard)
  43534. keyboard.keysDown = value;
  43535. },
  43536. enumerable: true,
  43537. configurable: true
  43538. });
  43539. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43540. get: function () {
  43541. var keyboard = this.inputs.attached["keyboard"];
  43542. if (keyboard)
  43543. return keyboard.keysLeft;
  43544. return [];
  43545. },
  43546. set: function (value) {
  43547. var keyboard = this.inputs.attached["keyboard"];
  43548. if (keyboard)
  43549. keyboard.keysLeft = value;
  43550. },
  43551. enumerable: true,
  43552. configurable: true
  43553. });
  43554. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43555. get: function () {
  43556. var keyboard = this.inputs.attached["keyboard"];
  43557. if (keyboard)
  43558. return keyboard.keysRight;
  43559. return [];
  43560. },
  43561. set: function (value) {
  43562. var keyboard = this.inputs.attached["keyboard"];
  43563. if (keyboard)
  43564. keyboard.keysRight = value;
  43565. },
  43566. enumerable: true,
  43567. configurable: true
  43568. });
  43569. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43570. get: function () {
  43571. var mousewheel = this.inputs.attached["mousewheel"];
  43572. if (mousewheel)
  43573. return mousewheel.wheelPrecision;
  43574. return 0;
  43575. },
  43576. set: function (value) {
  43577. var mousewheel = this.inputs.attached["mousewheel"];
  43578. if (mousewheel)
  43579. mousewheel.wheelPrecision = value;
  43580. },
  43581. enumerable: true,
  43582. configurable: true
  43583. });
  43584. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43585. get: function () {
  43586. var mousewheel = this.inputs.attached["mousewheel"];
  43587. if (mousewheel)
  43588. return mousewheel.wheelDeltaPercentage;
  43589. return 0;
  43590. },
  43591. set: function (value) {
  43592. var mousewheel = this.inputs.attached["mousewheel"];
  43593. if (mousewheel)
  43594. mousewheel.wheelDeltaPercentage = value;
  43595. },
  43596. enumerable: true,
  43597. configurable: true
  43598. });
  43599. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43600. get: function () {
  43601. return this._bouncingBehavior;
  43602. },
  43603. enumerable: true,
  43604. configurable: true
  43605. });
  43606. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43607. get: function () {
  43608. return this._bouncingBehavior != null;
  43609. },
  43610. set: function (value) {
  43611. if (value === this.useBouncingBehavior) {
  43612. return;
  43613. }
  43614. if (value) {
  43615. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43616. this.addBehavior(this._bouncingBehavior);
  43617. }
  43618. else if (this._bouncingBehavior) {
  43619. this.removeBehavior(this._bouncingBehavior);
  43620. this._bouncingBehavior = null;
  43621. }
  43622. },
  43623. enumerable: true,
  43624. configurable: true
  43625. });
  43626. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43627. get: function () {
  43628. return this._framingBehavior;
  43629. },
  43630. enumerable: true,
  43631. configurable: true
  43632. });
  43633. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43634. get: function () {
  43635. return this._framingBehavior != null;
  43636. },
  43637. set: function (value) {
  43638. if (value === this.useFramingBehavior) {
  43639. return;
  43640. }
  43641. if (value) {
  43642. this._framingBehavior = new BABYLON.FramingBehavior();
  43643. this.addBehavior(this._framingBehavior);
  43644. }
  43645. else if (this._framingBehavior) {
  43646. this.removeBehavior(this._framingBehavior);
  43647. this._framingBehavior = null;
  43648. }
  43649. },
  43650. enumerable: true,
  43651. configurable: true
  43652. });
  43653. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  43654. get: function () {
  43655. return this._autoRotationBehavior;
  43656. },
  43657. enumerable: true,
  43658. configurable: true
  43659. });
  43660. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  43661. get: function () {
  43662. return this._autoRotationBehavior != null;
  43663. },
  43664. set: function (value) {
  43665. if (value === this.useAutoRotationBehavior) {
  43666. return;
  43667. }
  43668. if (value) {
  43669. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  43670. this.addBehavior(this._autoRotationBehavior);
  43671. }
  43672. else if (this._autoRotationBehavior) {
  43673. this.removeBehavior(this._autoRotationBehavior);
  43674. this._autoRotationBehavior = null;
  43675. }
  43676. },
  43677. enumerable: true,
  43678. configurable: true
  43679. });
  43680. // Cache
  43681. ArcRotateCamera.prototype._initCache = function () {
  43682. _super.prototype._initCache.call(this);
  43683. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43684. this._cache.alpha = undefined;
  43685. this._cache.beta = undefined;
  43686. this._cache.radius = undefined;
  43687. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  43688. };
  43689. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  43690. if (!ignoreParentClass) {
  43691. _super.prototype._updateCache.call(this);
  43692. }
  43693. this._cache._target.copyFrom(this._getTargetPosition());
  43694. this._cache.alpha = this.alpha;
  43695. this._cache.beta = this.beta;
  43696. this._cache.radius = this.radius;
  43697. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  43698. };
  43699. ArcRotateCamera.prototype._getTargetPosition = function () {
  43700. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  43701. var pos = this._targetHost.getAbsolutePosition();
  43702. if (this._targetBoundingCenter) {
  43703. pos.addToRef(this._targetBoundingCenter, this._target);
  43704. }
  43705. else {
  43706. this._target.copyFrom(pos);
  43707. }
  43708. }
  43709. var lockedTargetPosition = this._getLockedTargetPosition();
  43710. if (lockedTargetPosition) {
  43711. return lockedTargetPosition;
  43712. }
  43713. return this._target;
  43714. };
  43715. ArcRotateCamera.prototype.storeState = function () {
  43716. this._storedAlpha = this.alpha;
  43717. this._storedBeta = this.beta;
  43718. this._storedRadius = this.radius;
  43719. this._storedTarget = this._getTargetPosition().clone();
  43720. return _super.prototype.storeState.call(this);
  43721. };
  43722. /**
  43723. * Restored camera state. You must call storeState() first
  43724. */
  43725. ArcRotateCamera.prototype._restoreStateValues = function () {
  43726. if (!_super.prototype._restoreStateValues.call(this)) {
  43727. return false;
  43728. }
  43729. this.alpha = this._storedAlpha;
  43730. this.beta = this._storedBeta;
  43731. this.radius = this._storedRadius;
  43732. this.setTarget(this._storedTarget.clone());
  43733. this.inertialAlphaOffset = 0;
  43734. this.inertialBetaOffset = 0;
  43735. this.inertialRadiusOffset = 0;
  43736. this.inertialPanningX = 0;
  43737. this.inertialPanningY = 0;
  43738. return true;
  43739. };
  43740. // Synchronized
  43741. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  43742. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  43743. return false;
  43744. return this._cache._target.equals(this._getTargetPosition())
  43745. && this._cache.alpha === this.alpha
  43746. && this._cache.beta === this.beta
  43747. && this._cache.radius === this.radius
  43748. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  43749. };
  43750. // Methods
  43751. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  43752. var _this = this;
  43753. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  43754. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  43755. this._useCtrlForPanning = useCtrlForPanning;
  43756. this._panningMouseButton = panningMouseButton;
  43757. this.inputs.attachElement(element, noPreventDefault);
  43758. this._reset = function () {
  43759. _this.inertialAlphaOffset = 0;
  43760. _this.inertialBetaOffset = 0;
  43761. _this.inertialRadiusOffset = 0;
  43762. _this.inertialPanningX = 0;
  43763. _this.inertialPanningY = 0;
  43764. };
  43765. };
  43766. ArcRotateCamera.prototype.detachControl = function (element) {
  43767. this.inputs.detachElement(element);
  43768. if (this._reset) {
  43769. this._reset();
  43770. }
  43771. };
  43772. ArcRotateCamera.prototype._checkInputs = function () {
  43773. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  43774. if (this._collisionTriggered) {
  43775. return;
  43776. }
  43777. this.inputs.checkInputs();
  43778. // Inertia
  43779. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  43780. if (this.getScene().useRightHandedSystem) {
  43781. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  43782. }
  43783. else {
  43784. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  43785. }
  43786. this.beta += this.inertialBetaOffset;
  43787. this.radius -= this.inertialRadiusOffset;
  43788. this.inertialAlphaOffset *= this.inertia;
  43789. this.inertialBetaOffset *= this.inertia;
  43790. this.inertialRadiusOffset *= this.inertia;
  43791. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  43792. this.inertialAlphaOffset = 0;
  43793. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  43794. this.inertialBetaOffset = 0;
  43795. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  43796. this.inertialRadiusOffset = 0;
  43797. }
  43798. // Panning inertia
  43799. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  43800. if (!this._localDirection) {
  43801. this._localDirection = BABYLON.Vector3.Zero();
  43802. this._transformedDirection = BABYLON.Vector3.Zero();
  43803. }
  43804. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  43805. this._localDirection.multiplyInPlace(this.panningAxis);
  43806. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  43807. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  43808. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  43809. if (!this.panningAxis.y) {
  43810. this._transformedDirection.y = 0;
  43811. }
  43812. if (!this._targetHost) {
  43813. if (this.panningDistanceLimit) {
  43814. this._transformedDirection.addInPlace(this._target);
  43815. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  43816. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  43817. this._target.copyFrom(this._transformedDirection);
  43818. }
  43819. }
  43820. else {
  43821. this._target.addInPlace(this._transformedDirection);
  43822. }
  43823. }
  43824. this.inertialPanningX *= this.panningInertia;
  43825. this.inertialPanningY *= this.panningInertia;
  43826. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  43827. this.inertialPanningX = 0;
  43828. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  43829. this.inertialPanningY = 0;
  43830. }
  43831. // Limits
  43832. this._checkLimits();
  43833. _super.prototype._checkInputs.call(this);
  43834. };
  43835. ArcRotateCamera.prototype._checkLimits = function () {
  43836. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  43837. if (this.allowUpsideDown && this.beta > Math.PI) {
  43838. this.beta = this.beta - (2 * Math.PI);
  43839. }
  43840. }
  43841. else {
  43842. if (this.beta < this.lowerBetaLimit) {
  43843. this.beta = this.lowerBetaLimit;
  43844. }
  43845. }
  43846. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  43847. if (this.allowUpsideDown && this.beta < -Math.PI) {
  43848. this.beta = this.beta + (2 * Math.PI);
  43849. }
  43850. }
  43851. else {
  43852. if (this.beta > this.upperBetaLimit) {
  43853. this.beta = this.upperBetaLimit;
  43854. }
  43855. }
  43856. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  43857. this.alpha = this.lowerAlphaLimit;
  43858. }
  43859. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  43860. this.alpha = this.upperAlphaLimit;
  43861. }
  43862. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  43863. this.radius = this.lowerRadiusLimit;
  43864. }
  43865. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  43866. this.radius = this.upperRadiusLimit;
  43867. }
  43868. };
  43869. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  43870. var radiusv3 = this.position.subtract(this._getTargetPosition());
  43871. this.radius = radiusv3.length();
  43872. if (this.radius === 0) {
  43873. this.radius = 0.0001; // Just to avoid division by zero
  43874. }
  43875. // Alpha
  43876. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  43877. if (radiusv3.z < 0) {
  43878. this.alpha = 2 * Math.PI - this.alpha;
  43879. }
  43880. // Beta
  43881. this.beta = Math.acos(radiusv3.y / this.radius);
  43882. this._checkLimits();
  43883. };
  43884. ArcRotateCamera.prototype.setPosition = function (position) {
  43885. if (this.position.equals(position)) {
  43886. return;
  43887. }
  43888. this.position.copyFrom(position);
  43889. this.rebuildAnglesAndRadius();
  43890. };
  43891. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  43892. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  43893. if (allowSamePosition === void 0) { allowSamePosition = false; }
  43894. if (target.getBoundingInfo) {
  43895. if (toBoundingCenter) {
  43896. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  43897. }
  43898. else {
  43899. this._targetBoundingCenter = null;
  43900. }
  43901. this._targetHost = target;
  43902. this._target = this._getTargetPosition();
  43903. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  43904. }
  43905. else {
  43906. var newTarget = target;
  43907. var currentTarget = this._getTargetPosition();
  43908. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  43909. return;
  43910. }
  43911. this._targetHost = null;
  43912. this._target = newTarget;
  43913. this._targetBoundingCenter = null;
  43914. this.onMeshTargetChangedObservable.notifyObservers(null);
  43915. }
  43916. this.rebuildAnglesAndRadius();
  43917. };
  43918. ArcRotateCamera.prototype._getViewMatrix = function () {
  43919. // Compute
  43920. var cosa = Math.cos(this.alpha);
  43921. var sina = Math.sin(this.alpha);
  43922. var cosb = Math.cos(this.beta);
  43923. var sinb = Math.sin(this.beta);
  43924. if (sinb === 0) {
  43925. sinb = 0.0001;
  43926. }
  43927. var target = this._getTargetPosition();
  43928. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  43929. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  43930. if (!this._collider) {
  43931. this._collider = new BABYLON.Collider();
  43932. }
  43933. this._collider._radius = this.collisionRadius;
  43934. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  43935. this._collisionTriggered = true;
  43936. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43937. }
  43938. else {
  43939. this.position.copyFrom(this._newPosition);
  43940. var up = this.upVector;
  43941. if (this.allowUpsideDown && sinb < 0) {
  43942. up = up.clone();
  43943. up = up.negate();
  43944. }
  43945. if (this.getScene().useRightHandedSystem) {
  43946. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  43947. }
  43948. else {
  43949. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  43950. }
  43951. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  43952. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  43953. }
  43954. this._currentTarget = target;
  43955. return this._viewMatrix;
  43956. };
  43957. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  43958. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  43959. meshes = meshes || this.getScene().meshes;
  43960. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  43961. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  43962. this.radius = distance * this.zoomOnFactor;
  43963. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  43964. };
  43965. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  43966. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  43967. var meshesOrMinMaxVector;
  43968. var distance;
  43969. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  43970. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  43971. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  43972. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  43973. }
  43974. else {
  43975. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  43976. meshesOrMinMaxVector = minMaxVectorAndDistance;
  43977. distance = minMaxVectorAndDistance.distance;
  43978. }
  43979. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  43980. if (!doNotUpdateMaxZ) {
  43981. this.maxZ = distance * 2;
  43982. }
  43983. };
  43984. /**
  43985. * @override
  43986. * Override Camera.createRigCamera
  43987. */
  43988. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43989. var alphaShift = 0;
  43990. switch (this.cameraRigMode) {
  43991. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43992. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43993. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43994. case BABYLON.Camera.RIG_MODE_VR:
  43995. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  43996. break;
  43997. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43998. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  43999. break;
  44000. }
  44001. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44002. rigCam._cameraRigParams = {};
  44003. return rigCam;
  44004. };
  44005. /**
  44006. * @override
  44007. * Override Camera._updateRigCameras
  44008. */
  44009. ArcRotateCamera.prototype._updateRigCameras = function () {
  44010. var camLeft = this._rigCameras[0];
  44011. var camRight = this._rigCameras[1];
  44012. camLeft.beta = camRight.beta = this.beta;
  44013. camLeft.radius = camRight.radius = this.radius;
  44014. switch (this.cameraRigMode) {
  44015. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44016. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44017. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44018. case BABYLON.Camera.RIG_MODE_VR:
  44019. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44020. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44021. break;
  44022. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44023. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44024. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44025. break;
  44026. }
  44027. _super.prototype._updateRigCameras.call(this);
  44028. };
  44029. ArcRotateCamera.prototype.dispose = function () {
  44030. this.inputs.clear();
  44031. _super.prototype.dispose.call(this);
  44032. };
  44033. ArcRotateCamera.prototype.getClassName = function () {
  44034. return "ArcRotateCamera";
  44035. };
  44036. __decorate([
  44037. BABYLON.serialize()
  44038. ], ArcRotateCamera.prototype, "alpha", void 0);
  44039. __decorate([
  44040. BABYLON.serialize()
  44041. ], ArcRotateCamera.prototype, "beta", void 0);
  44042. __decorate([
  44043. BABYLON.serialize()
  44044. ], ArcRotateCamera.prototype, "radius", void 0);
  44045. __decorate([
  44046. BABYLON.serializeAsVector3("target")
  44047. ], ArcRotateCamera.prototype, "_target", void 0);
  44048. __decorate([
  44049. BABYLON.serialize()
  44050. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44051. __decorate([
  44052. BABYLON.serialize()
  44053. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44054. __decorate([
  44055. BABYLON.serialize()
  44056. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44057. __decorate([
  44058. BABYLON.serialize()
  44059. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44060. __decorate([
  44061. BABYLON.serialize()
  44062. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44063. __decorate([
  44064. BABYLON.serialize()
  44065. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44066. __decorate([
  44067. BABYLON.serialize()
  44068. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44069. __decorate([
  44070. BABYLON.serialize()
  44071. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44072. __decorate([
  44073. BABYLON.serialize()
  44074. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44075. __decorate([
  44076. BABYLON.serialize()
  44077. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44078. __decorate([
  44079. BABYLON.serialize()
  44080. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44081. __decorate([
  44082. BABYLON.serialize()
  44083. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44084. __decorate([
  44085. BABYLON.serialize()
  44086. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44087. __decorate([
  44088. BABYLON.serializeAsVector3()
  44089. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44090. __decorate([
  44091. BABYLON.serialize()
  44092. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44093. __decorate([
  44094. BABYLON.serialize()
  44095. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44096. __decorate([
  44097. BABYLON.serialize()
  44098. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44099. return ArcRotateCamera;
  44100. }(BABYLON.TargetCamera));
  44101. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44102. })(BABYLON || (BABYLON = {}));
  44103. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44104. var BABYLON;
  44105. (function (BABYLON) {
  44106. /**
  44107. * The HemisphericLight simulates the ambient environment light,
  44108. * so the passed direction is the light reflection direction, not the incoming direction.
  44109. */
  44110. var HemisphericLight = /** @class */ (function (_super) {
  44111. __extends(HemisphericLight, _super);
  44112. /**
  44113. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44114. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44115. * The HemisphericLight can't cast shadows.
  44116. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44117. * @param name The friendly name of the light
  44118. * @param direction The direction of the light reflection
  44119. * @param scene The scene the light belongs to
  44120. */
  44121. function HemisphericLight(name, direction, scene) {
  44122. var _this = _super.call(this, name, scene) || this;
  44123. /**
  44124. * The groundColor is the light in the opposite direction to the one specified during creation.
  44125. * 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.
  44126. */
  44127. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44128. _this.direction = direction || BABYLON.Vector3.Up();
  44129. return _this;
  44130. }
  44131. HemisphericLight.prototype._buildUniformLayout = function () {
  44132. this._uniformBuffer.addUniform("vLightData", 4);
  44133. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44134. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44135. this._uniformBuffer.addUniform("vLightGround", 3);
  44136. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44137. this._uniformBuffer.addUniform("depthValues", 2);
  44138. this._uniformBuffer.create();
  44139. };
  44140. /**
  44141. * Returns the string "HemisphericLight".
  44142. * @return The class name
  44143. */
  44144. HemisphericLight.prototype.getClassName = function () {
  44145. return "HemisphericLight";
  44146. };
  44147. /**
  44148. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44149. * Returns the updated direction.
  44150. * @param target The target the direction should point to
  44151. * @return The computed direction
  44152. */
  44153. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44154. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44155. return this.direction;
  44156. };
  44157. /**
  44158. * Returns the shadow generator associated to the light.
  44159. * @returns Always null for hemispheric lights because it does not support shadows.
  44160. */
  44161. HemisphericLight.prototype.getShadowGenerator = function () {
  44162. return null;
  44163. };
  44164. /**
  44165. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44166. * @param effect The effect to update
  44167. * @param lightIndex The index of the light in the effect to update
  44168. * @returns The hemispheric light
  44169. */
  44170. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44171. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44172. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44173. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44174. return this;
  44175. };
  44176. /**
  44177. * @ignore internal use only.
  44178. */
  44179. HemisphericLight.prototype._getWorldMatrix = function () {
  44180. if (!this._worldMatrix) {
  44181. this._worldMatrix = BABYLON.Matrix.Identity();
  44182. }
  44183. return this._worldMatrix;
  44184. };
  44185. /**
  44186. * Returns the integer 3.
  44187. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44188. */
  44189. HemisphericLight.prototype.getTypeID = function () {
  44190. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44191. };
  44192. __decorate([
  44193. BABYLON.serializeAsColor3()
  44194. ], HemisphericLight.prototype, "groundColor", void 0);
  44195. __decorate([
  44196. BABYLON.serializeAsVector3()
  44197. ], HemisphericLight.prototype, "direction", void 0);
  44198. return HemisphericLight;
  44199. }(BABYLON.Light));
  44200. BABYLON.HemisphericLight = HemisphericLight;
  44201. })(BABYLON || (BABYLON = {}));
  44202. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44203. var BABYLON;
  44204. (function (BABYLON) {
  44205. /**
  44206. * Base implementation of @see IShadowLight
  44207. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44208. */
  44209. var ShadowLight = /** @class */ (function (_super) {
  44210. __extends(ShadowLight, _super);
  44211. function ShadowLight() {
  44212. var _this = _super !== null && _super.apply(this, arguments) || this;
  44213. _this._needProjectionMatrixCompute = true;
  44214. return _this;
  44215. }
  44216. ShadowLight.prototype._setPosition = function (value) {
  44217. this._position = value;
  44218. };
  44219. Object.defineProperty(ShadowLight.prototype, "position", {
  44220. /**
  44221. * Sets the position the shadow will be casted from. Also use as the light position for both
  44222. * point and spot lights.
  44223. */
  44224. get: function () {
  44225. return this._position;
  44226. },
  44227. /**
  44228. * Sets the position the shadow will be casted from. Also use as the light position for both
  44229. * point and spot lights.
  44230. */
  44231. set: function (value) {
  44232. this._setPosition(value);
  44233. },
  44234. enumerable: true,
  44235. configurable: true
  44236. });
  44237. ShadowLight.prototype._setDirection = function (value) {
  44238. this._direction = value;
  44239. };
  44240. Object.defineProperty(ShadowLight.prototype, "direction", {
  44241. /**
  44242. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44243. * Also use as the light direction on spot and directional lights.
  44244. */
  44245. get: function () {
  44246. return this._direction;
  44247. },
  44248. /**
  44249. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44250. * Also use as the light direction on spot and directional lights.
  44251. */
  44252. set: function (value) {
  44253. this._setDirection(value);
  44254. },
  44255. enumerable: true,
  44256. configurable: true
  44257. });
  44258. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44259. /**
  44260. * Gets the shadow projection clipping minimum z value.
  44261. */
  44262. get: function () {
  44263. return this._shadowMinZ;
  44264. },
  44265. /**
  44266. * Sets the shadow projection clipping minimum z value.
  44267. */
  44268. set: function (value) {
  44269. this._shadowMinZ = value;
  44270. this.forceProjectionMatrixCompute();
  44271. },
  44272. enumerable: true,
  44273. configurable: true
  44274. });
  44275. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44276. /**
  44277. * Sets the shadow projection clipping maximum z value.
  44278. */
  44279. get: function () {
  44280. return this._shadowMaxZ;
  44281. },
  44282. /**
  44283. * Gets the shadow projection clipping maximum z value.
  44284. */
  44285. set: function (value) {
  44286. this._shadowMaxZ = value;
  44287. this.forceProjectionMatrixCompute();
  44288. },
  44289. enumerable: true,
  44290. configurable: true
  44291. });
  44292. /**
  44293. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44294. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44295. */
  44296. ShadowLight.prototype.computeTransformedInformation = function () {
  44297. if (this.parent && this.parent.getWorldMatrix) {
  44298. if (!this.transformedPosition) {
  44299. this.transformedPosition = BABYLON.Vector3.Zero();
  44300. }
  44301. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44302. // In case the direction is present.
  44303. if (this.direction) {
  44304. if (!this.transformedDirection) {
  44305. this.transformedDirection = BABYLON.Vector3.Zero();
  44306. }
  44307. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44308. }
  44309. return true;
  44310. }
  44311. return false;
  44312. };
  44313. /**
  44314. * Return the depth scale used for the shadow map.
  44315. * @returns the depth scale.
  44316. */
  44317. ShadowLight.prototype.getDepthScale = function () {
  44318. return 50.0;
  44319. };
  44320. /**
  44321. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44322. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44323. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44324. */
  44325. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44326. return this.transformedDirection ? this.transformedDirection : this.direction;
  44327. };
  44328. /**
  44329. * Returns the ShadowLight absolute position in the World.
  44330. * @returns the position vector in world space
  44331. */
  44332. ShadowLight.prototype.getAbsolutePosition = function () {
  44333. return this.transformedPosition ? this.transformedPosition : this.position;
  44334. };
  44335. /**
  44336. * Sets the ShadowLight direction toward the passed target.
  44337. * @param target The point tot target in local space
  44338. * @returns the updated ShadowLight direction
  44339. */
  44340. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44341. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44342. return this.direction;
  44343. };
  44344. /**
  44345. * Returns the light rotation in euler definition.
  44346. * @returns the x y z rotation in local space.
  44347. */
  44348. ShadowLight.prototype.getRotation = function () {
  44349. this.direction.normalize();
  44350. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44351. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44352. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44353. };
  44354. /**
  44355. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44356. * @returns true if a cube texture needs to be use
  44357. */
  44358. ShadowLight.prototype.needCube = function () {
  44359. return false;
  44360. };
  44361. /**
  44362. * Detects if the projection matrix requires to be recomputed this frame.
  44363. * @returns true if it requires to be recomputed otherwise, false.
  44364. */
  44365. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44366. return this._needProjectionMatrixCompute;
  44367. };
  44368. /**
  44369. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44370. */
  44371. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44372. this._needProjectionMatrixCompute = true;
  44373. };
  44374. /**
  44375. * Get the world matrix of the sahdow lights.
  44376. * @ignore Internal Use Only
  44377. */
  44378. ShadowLight.prototype._getWorldMatrix = function () {
  44379. if (!this._worldMatrix) {
  44380. this._worldMatrix = BABYLON.Matrix.Identity();
  44381. }
  44382. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44383. return this._worldMatrix;
  44384. };
  44385. /**
  44386. * Gets the minZ used for shadow according to both the scene and the light.
  44387. * @param activeCamera The camera we are returning the min for
  44388. * @returns the depth min z
  44389. */
  44390. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44391. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44392. };
  44393. /**
  44394. * Gets the maxZ used for shadow according to both the scene and the light.
  44395. * @param activeCamera The camera we are returning the max for
  44396. * @returns the depth max z
  44397. */
  44398. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44399. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44400. };
  44401. /**
  44402. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44403. * @param matrix The materix to updated with the projection information
  44404. * @param viewMatrix The transform matrix of the light
  44405. * @param renderList The list of mesh to render in the map
  44406. * @returns The current light
  44407. */
  44408. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44409. if (this.customProjectionMatrixBuilder) {
  44410. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44411. }
  44412. else {
  44413. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44414. }
  44415. return this;
  44416. };
  44417. __decorate([
  44418. BABYLON.serializeAsVector3()
  44419. ], ShadowLight.prototype, "position", null);
  44420. __decorate([
  44421. BABYLON.serializeAsVector3()
  44422. ], ShadowLight.prototype, "direction", null);
  44423. __decorate([
  44424. BABYLON.serialize()
  44425. ], ShadowLight.prototype, "shadowMinZ", null);
  44426. __decorate([
  44427. BABYLON.serialize()
  44428. ], ShadowLight.prototype, "shadowMaxZ", null);
  44429. return ShadowLight;
  44430. }(BABYLON.Light));
  44431. BABYLON.ShadowLight = ShadowLight;
  44432. })(BABYLON || (BABYLON = {}));
  44433. //# sourceMappingURL=babylon.shadowLight.js.map
  44434. var BABYLON;
  44435. (function (BABYLON) {
  44436. /**
  44437. * A point light is a light defined by an unique point in world space.
  44438. * The light is emitted in every direction from this point.
  44439. * A good example of a point light is a standard light bulb.
  44440. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44441. */
  44442. var PointLight = /** @class */ (function (_super) {
  44443. __extends(PointLight, _super);
  44444. /**
  44445. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44446. * A PointLight emits the light in every direction.
  44447. * It can cast shadows.
  44448. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44449. * ```javascript
  44450. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44451. * ```
  44452. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44453. * @param name The light friendly name
  44454. * @param position The position of the point light in the scene
  44455. * @param scene The scene the lights belongs to
  44456. */
  44457. function PointLight(name, position, scene) {
  44458. var _this = _super.call(this, name, scene) || this;
  44459. _this._shadowAngle = Math.PI / 2;
  44460. _this.position = position;
  44461. return _this;
  44462. }
  44463. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44464. /**
  44465. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44466. * This specifies what angle the shadow will use to be created.
  44467. *
  44468. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44469. */
  44470. get: function () {
  44471. return this._shadowAngle;
  44472. },
  44473. /**
  44474. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44475. * This specifies what angle the shadow will use to be created.
  44476. *
  44477. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44478. */
  44479. set: function (value) {
  44480. this._shadowAngle = value;
  44481. this.forceProjectionMatrixCompute();
  44482. },
  44483. enumerable: true,
  44484. configurable: true
  44485. });
  44486. Object.defineProperty(PointLight.prototype, "direction", {
  44487. /**
  44488. * Gets the direction if it has been set.
  44489. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44490. */
  44491. get: function () {
  44492. return this._direction;
  44493. },
  44494. /**
  44495. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44496. */
  44497. set: function (value) {
  44498. var previousNeedCube = this.needCube();
  44499. this._direction = value;
  44500. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44501. this._shadowGenerator.recreateShadowMap();
  44502. }
  44503. },
  44504. enumerable: true,
  44505. configurable: true
  44506. });
  44507. /**
  44508. * Returns the string "PointLight"
  44509. * @returns the class name
  44510. */
  44511. PointLight.prototype.getClassName = function () {
  44512. return "PointLight";
  44513. };
  44514. /**
  44515. * Returns the integer 0.
  44516. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44517. */
  44518. PointLight.prototype.getTypeID = function () {
  44519. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44520. };
  44521. /**
  44522. * Specifies wether or not the shadowmap should be a cube texture.
  44523. * @returns true if the shadowmap needs to be a cube texture.
  44524. */
  44525. PointLight.prototype.needCube = function () {
  44526. return !this.direction;
  44527. };
  44528. /**
  44529. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44530. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44531. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44532. */
  44533. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44534. if (this.direction) {
  44535. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44536. }
  44537. else {
  44538. switch (faceIndex) {
  44539. case 0:
  44540. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44541. case 1:
  44542. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44543. case 2:
  44544. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44545. case 3:
  44546. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44547. case 4:
  44548. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44549. case 5:
  44550. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44551. }
  44552. }
  44553. return BABYLON.Vector3.Zero();
  44554. };
  44555. /**
  44556. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44557. * - fov = PI / 2
  44558. * - aspect ratio : 1.0
  44559. * - z-near and far equal to the active camera minZ and maxZ.
  44560. * Returns the PointLight.
  44561. */
  44562. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44563. var activeCamera = this.getScene().activeCamera;
  44564. if (!activeCamera) {
  44565. return;
  44566. }
  44567. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44568. };
  44569. PointLight.prototype._buildUniformLayout = function () {
  44570. this._uniformBuffer.addUniform("vLightData", 4);
  44571. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44572. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44573. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44574. this._uniformBuffer.addUniform("depthValues", 2);
  44575. this._uniformBuffer.create();
  44576. };
  44577. /**
  44578. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44579. * @param effect The effect to update
  44580. * @param lightIndex The index of the light in the effect to update
  44581. * @returns The point light
  44582. */
  44583. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44584. if (this.computeTransformedInformation()) {
  44585. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44586. return this;
  44587. }
  44588. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44589. return this;
  44590. };
  44591. __decorate([
  44592. BABYLON.serialize()
  44593. ], PointLight.prototype, "shadowAngle", null);
  44594. return PointLight;
  44595. }(BABYLON.ShadowLight));
  44596. BABYLON.PointLight = PointLight;
  44597. })(BABYLON || (BABYLON = {}));
  44598. //# sourceMappingURL=babylon.pointLight.js.map
  44599. var BABYLON;
  44600. (function (BABYLON) {
  44601. /**
  44602. * A directional light is defined by a direction (what a surprise!).
  44603. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44604. * 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.
  44605. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44606. */
  44607. var DirectionalLight = /** @class */ (function (_super) {
  44608. __extends(DirectionalLight, _super);
  44609. /**
  44610. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44611. * The directional light is emitted from everywhere in the given direction.
  44612. * It can cast shawdows.
  44613. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44614. * @param name The friendly name of the light
  44615. * @param direction The direction of the light
  44616. * @param scene The scene the light belongs to
  44617. */
  44618. function DirectionalLight(name, direction, scene) {
  44619. var _this = _super.call(this, name, scene) || this;
  44620. _this._shadowFrustumSize = 0;
  44621. _this._shadowOrthoScale = 0.5;
  44622. /**
  44623. * Automatically compute the projection matrix to best fit (including all the casters)
  44624. * on each frame.
  44625. */
  44626. _this.autoUpdateExtends = true;
  44627. // Cache
  44628. _this._orthoLeft = Number.MAX_VALUE;
  44629. _this._orthoRight = Number.MIN_VALUE;
  44630. _this._orthoTop = Number.MIN_VALUE;
  44631. _this._orthoBottom = Number.MAX_VALUE;
  44632. _this.position = direction.scale(-1.0);
  44633. _this.direction = direction;
  44634. return _this;
  44635. }
  44636. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44637. /**
  44638. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44639. */
  44640. get: function () {
  44641. return this._shadowFrustumSize;
  44642. },
  44643. /**
  44644. * Specifies a fix frustum size for the shadow generation.
  44645. */
  44646. set: function (value) {
  44647. this._shadowFrustumSize = value;
  44648. this.forceProjectionMatrixCompute();
  44649. },
  44650. enumerable: true,
  44651. configurable: true
  44652. });
  44653. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  44654. /**
  44655. * Gets the shadow projection scale against the optimal computed one.
  44656. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44657. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44658. */
  44659. get: function () {
  44660. return this._shadowOrthoScale;
  44661. },
  44662. /**
  44663. * Sets the shadow projection scale against the optimal computed one.
  44664. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44665. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44666. */
  44667. set: function (value) {
  44668. this._shadowOrthoScale = value;
  44669. this.forceProjectionMatrixCompute();
  44670. },
  44671. enumerable: true,
  44672. configurable: true
  44673. });
  44674. /**
  44675. * Returns the string "DirectionalLight".
  44676. * @return The class name
  44677. */
  44678. DirectionalLight.prototype.getClassName = function () {
  44679. return "DirectionalLight";
  44680. };
  44681. /**
  44682. * Returns the integer 1.
  44683. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44684. */
  44685. DirectionalLight.prototype.getTypeID = function () {
  44686. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  44687. };
  44688. /**
  44689. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  44690. * Returns the DirectionalLight Shadow projection matrix.
  44691. */
  44692. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44693. if (this.shadowFrustumSize > 0) {
  44694. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  44695. }
  44696. else {
  44697. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44698. }
  44699. };
  44700. /**
  44701. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  44702. * Returns the DirectionalLight Shadow projection matrix.
  44703. */
  44704. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  44705. var activeCamera = this.getScene().activeCamera;
  44706. if (!activeCamera) {
  44707. return;
  44708. }
  44709. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  44710. };
  44711. /**
  44712. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  44713. * Returns the DirectionalLight Shadow projection matrix.
  44714. */
  44715. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44716. var activeCamera = this.getScene().activeCamera;
  44717. if (!activeCamera) {
  44718. return;
  44719. }
  44720. // Check extends
  44721. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  44722. var tempVector3 = BABYLON.Vector3.Zero();
  44723. this._orthoLeft = Number.MAX_VALUE;
  44724. this._orthoRight = Number.MIN_VALUE;
  44725. this._orthoTop = Number.MIN_VALUE;
  44726. this._orthoBottom = Number.MAX_VALUE;
  44727. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  44728. var mesh = renderList[meshIndex];
  44729. if (!mesh) {
  44730. continue;
  44731. }
  44732. var boundingInfo = mesh.getBoundingInfo();
  44733. var boundingBox = boundingInfo.boundingBox;
  44734. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  44735. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  44736. if (tempVector3.x < this._orthoLeft)
  44737. this._orthoLeft = tempVector3.x;
  44738. if (tempVector3.y < this._orthoBottom)
  44739. this._orthoBottom = tempVector3.y;
  44740. if (tempVector3.x > this._orthoRight)
  44741. this._orthoRight = tempVector3.x;
  44742. if (tempVector3.y > this._orthoTop)
  44743. this._orthoTop = tempVector3.y;
  44744. }
  44745. }
  44746. }
  44747. var xOffset = this._orthoRight - this._orthoLeft;
  44748. var yOffset = this._orthoTop - this._orthoBottom;
  44749. 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);
  44750. };
  44751. DirectionalLight.prototype._buildUniformLayout = function () {
  44752. this._uniformBuffer.addUniform("vLightData", 4);
  44753. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44754. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44755. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44756. this._uniformBuffer.addUniform("depthValues", 2);
  44757. this._uniformBuffer.create();
  44758. };
  44759. /**
  44760. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  44761. * @param effect The effect to update
  44762. * @param lightIndex The index of the light in the effect to update
  44763. * @returns The directional light
  44764. */
  44765. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  44766. if (this.computeTransformedInformation()) {
  44767. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  44768. return this;
  44769. }
  44770. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  44771. return this;
  44772. };
  44773. /**
  44774. * Gets the minZ used for shadow according to both the scene and the light.
  44775. *
  44776. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  44777. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  44778. * @param activeCamera The camera we are returning the min for
  44779. * @returns the depth min z
  44780. */
  44781. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  44782. return 1;
  44783. };
  44784. /**
  44785. * Gets the maxZ used for shadow according to both the scene and the light.
  44786. *
  44787. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  44788. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  44789. * @param activeCamera The camera we are returning the max for
  44790. * @returns the depth max z
  44791. */
  44792. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  44793. return 1;
  44794. };
  44795. __decorate([
  44796. BABYLON.serialize()
  44797. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  44798. __decorate([
  44799. BABYLON.serialize()
  44800. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  44801. __decorate([
  44802. BABYLON.serialize()
  44803. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  44804. return DirectionalLight;
  44805. }(BABYLON.ShadowLight));
  44806. BABYLON.DirectionalLight = DirectionalLight;
  44807. })(BABYLON || (BABYLON = {}));
  44808. //# sourceMappingURL=babylon.directionalLight.js.map
  44809. var BABYLON;
  44810. (function (BABYLON) {
  44811. /**
  44812. * A spot light is defined by a position, a direction, an angle, and an exponent.
  44813. * These values define a cone of light starting from the position, emitting toward the direction.
  44814. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  44815. * and the exponent defines the speed of the decay of the light with distance (reach).
  44816. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44817. */
  44818. var SpotLight = /** @class */ (function (_super) {
  44819. __extends(SpotLight, _super);
  44820. /**
  44821. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  44822. * It can cast shadows.
  44823. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44824. * @param name The light friendly name
  44825. * @param position The position of the spot light in the scene
  44826. * @param direction The direction of the light in the scene
  44827. * @param angle The cone angle of the light in Radians
  44828. * @param exponent The light decay speed with the distance from the emission spot
  44829. * @param scene The scene the lights belongs to
  44830. */
  44831. function SpotLight(name, position, direction, angle, exponent, scene) {
  44832. var _this = _super.call(this, name, scene) || this;
  44833. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  44834. _this._projectionTextureLightNear = 1e-6;
  44835. _this._projectionTextureLightFar = 1000.0;
  44836. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  44837. _this._projectionTextureViewLightDirty = true;
  44838. _this._projectionTextureProjectionLightDirty = true;
  44839. _this._projectionTextureDirty = true;
  44840. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  44841. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  44842. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  44843. _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);
  44844. _this.position = position;
  44845. _this.direction = direction;
  44846. _this.angle = angle;
  44847. _this.exponent = exponent;
  44848. return _this;
  44849. }
  44850. Object.defineProperty(SpotLight.prototype, "angle", {
  44851. /**
  44852. * Gets the cone angle of the spot light in Radians.
  44853. */
  44854. get: function () {
  44855. return this._angle;
  44856. },
  44857. /**
  44858. * Sets the cone angle of the spot light in Radians.
  44859. */
  44860. set: function (value) {
  44861. this._angle = value;
  44862. this._projectionTextureProjectionLightDirty = true;
  44863. this.forceProjectionMatrixCompute();
  44864. },
  44865. enumerable: true,
  44866. configurable: true
  44867. });
  44868. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  44869. /**
  44870. * Allows scaling the angle of the light for shadow generation only.
  44871. */
  44872. get: function () {
  44873. return this._shadowAngleScale;
  44874. },
  44875. /**
  44876. * Allows scaling the angle of the light for shadow generation only.
  44877. */
  44878. set: function (value) {
  44879. this._shadowAngleScale = value;
  44880. this.forceProjectionMatrixCompute();
  44881. },
  44882. enumerable: true,
  44883. configurable: true
  44884. });
  44885. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  44886. /**
  44887. * Allows reading the projecton texture
  44888. */
  44889. get: function () {
  44890. return this._projectionTextureMatrix;
  44891. },
  44892. enumerable: true,
  44893. configurable: true
  44894. });
  44895. ;
  44896. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  44897. /**
  44898. * Gets the near clip of the Spotlight for texture projection.
  44899. */
  44900. get: function () {
  44901. return this._projectionTextureLightNear;
  44902. },
  44903. /**
  44904. * Sets the near clip of the Spotlight for texture projection.
  44905. */
  44906. set: function (value) {
  44907. this._projectionTextureLightNear = value;
  44908. this._projectionTextureProjectionLightDirty = true;
  44909. },
  44910. enumerable: true,
  44911. configurable: true
  44912. });
  44913. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  44914. /**
  44915. * Gets the far clip of the Spotlight for texture projection.
  44916. */
  44917. get: function () {
  44918. return this._projectionTextureLightFar;
  44919. },
  44920. /**
  44921. * Sets the far clip of the Spotlight for texture projection.
  44922. */
  44923. set: function (value) {
  44924. this._projectionTextureLightFar = value;
  44925. this._projectionTextureProjectionLightDirty = true;
  44926. },
  44927. enumerable: true,
  44928. configurable: true
  44929. });
  44930. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  44931. /**
  44932. * Gets the Up vector of the Spotlight for texture projection.
  44933. */
  44934. get: function () {
  44935. return this._projectionTextureUpDirection;
  44936. },
  44937. /**
  44938. * Sets the Up vector of the Spotlight for texture projection.
  44939. */
  44940. set: function (value) {
  44941. this._projectionTextureUpDirection = value;
  44942. this._projectionTextureProjectionLightDirty = true;
  44943. },
  44944. enumerable: true,
  44945. configurable: true
  44946. });
  44947. ;
  44948. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  44949. /**
  44950. * Gets the projection texture of the light.
  44951. */
  44952. get: function () {
  44953. return this._projectionTexture;
  44954. },
  44955. /**
  44956. * Sets the projection texture of the light.
  44957. */
  44958. set: function (value) {
  44959. this._projectionTexture = value;
  44960. this._projectionTextureDirty = true;
  44961. },
  44962. enumerable: true,
  44963. configurable: true
  44964. });
  44965. /**
  44966. * Returns the string "SpotLight".
  44967. * @returns the class name
  44968. */
  44969. SpotLight.prototype.getClassName = function () {
  44970. return "SpotLight";
  44971. };
  44972. /**
  44973. * Returns the integer 2.
  44974. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44975. */
  44976. SpotLight.prototype.getTypeID = function () {
  44977. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  44978. };
  44979. /**
  44980. * Overrides the direction setter to recompute the projection texture view light Matrix.
  44981. */
  44982. SpotLight.prototype._setDirection = function (value) {
  44983. _super.prototype._setDirection.call(this, value);
  44984. this._projectionTextureViewLightDirty = true;
  44985. };
  44986. /**
  44987. * Overrides the position setter to recompute the projection texture view light Matrix.
  44988. */
  44989. SpotLight.prototype._setPosition = function (value) {
  44990. _super.prototype._setPosition.call(this, value);
  44991. this._projectionTextureViewLightDirty = true;
  44992. };
  44993. /**
  44994. * 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.
  44995. * Returns the SpotLight.
  44996. */
  44997. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44998. var activeCamera = this.getScene().activeCamera;
  44999. if (!activeCamera) {
  45000. return;
  45001. }
  45002. this._shadowAngleScale = this._shadowAngleScale || 1;
  45003. var angle = this._shadowAngleScale * this._angle;
  45004. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45005. };
  45006. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45007. this._projectionTextureViewLightDirty = false;
  45008. this._projectionTextureDirty = true;
  45009. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45010. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45011. };
  45012. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45013. this._projectionTextureProjectionLightDirty = false;
  45014. this._projectionTextureDirty = true;
  45015. var light_far = this.projectionTextureLightFar;
  45016. var light_near = this.projectionTextureLightNear;
  45017. var P = light_far / (light_far - light_near);
  45018. var Q = -P * light_near;
  45019. var S = 1.0 / Math.tan(this._angle / 2.0);
  45020. var A = 1.0;
  45021. 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);
  45022. };
  45023. /**
  45024. * Main function for light texture projection matrix computing.
  45025. */
  45026. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45027. this._projectionTextureDirty = false;
  45028. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45029. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45030. };
  45031. SpotLight.prototype._buildUniformLayout = function () {
  45032. this._uniformBuffer.addUniform("vLightData", 4);
  45033. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45034. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45035. this._uniformBuffer.addUniform("vLightDirection", 3);
  45036. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45037. this._uniformBuffer.addUniform("depthValues", 2);
  45038. this._uniformBuffer.create();
  45039. };
  45040. /**
  45041. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45042. * @param effect The effect to update
  45043. * @param lightIndex The index of the light in the effect to update
  45044. * @returns The spot light
  45045. */
  45046. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45047. var normalizeDirection;
  45048. if (this.computeTransformedInformation()) {
  45049. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45050. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45051. }
  45052. else {
  45053. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45054. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45055. }
  45056. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45057. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45058. if (this._projectionTextureViewLightDirty) {
  45059. this._computeProjectionTextureViewLightMatrix();
  45060. }
  45061. if (this._projectionTextureProjectionLightDirty) {
  45062. this._computeProjectionTextureProjectionLightMatrix();
  45063. }
  45064. if (this._projectionTextureDirty) {
  45065. this._computeProjectionTextureMatrix();
  45066. }
  45067. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45068. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45069. }
  45070. return this;
  45071. };
  45072. /**
  45073. * Disposes the light and the associated resources.
  45074. */
  45075. SpotLight.prototype.dispose = function () {
  45076. _super.prototype.dispose.call(this);
  45077. if (this._projectionTexture) {
  45078. this._projectionTexture.dispose();
  45079. }
  45080. };
  45081. __decorate([
  45082. BABYLON.serialize()
  45083. ], SpotLight.prototype, "angle", null);
  45084. __decorate([
  45085. BABYLON.serialize()
  45086. ], SpotLight.prototype, "shadowAngleScale", null);
  45087. __decorate([
  45088. BABYLON.serialize()
  45089. ], SpotLight.prototype, "exponent", void 0);
  45090. __decorate([
  45091. BABYLON.serialize()
  45092. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45093. __decorate([
  45094. BABYLON.serialize()
  45095. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45096. __decorate([
  45097. BABYLON.serialize()
  45098. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45099. __decorate([
  45100. BABYLON.serializeAsTexture("projectedLightTexture")
  45101. ], SpotLight.prototype, "_projectionTexture", void 0);
  45102. return SpotLight;
  45103. }(BABYLON.ShadowLight));
  45104. BABYLON.SpotLight = SpotLight;
  45105. })(BABYLON || (BABYLON = {}));
  45106. //# sourceMappingURL=babylon.spotLight.js.map
  45107. var BABYLON;
  45108. (function (BABYLON) {
  45109. var AnimationRange = /** @class */ (function () {
  45110. function AnimationRange(name, from, to) {
  45111. this.name = name;
  45112. this.from = from;
  45113. this.to = to;
  45114. }
  45115. AnimationRange.prototype.clone = function () {
  45116. return new AnimationRange(this.name, this.from, this.to);
  45117. };
  45118. return AnimationRange;
  45119. }());
  45120. BABYLON.AnimationRange = AnimationRange;
  45121. /**
  45122. * Composed of a frame, and an action function
  45123. */
  45124. var AnimationEvent = /** @class */ (function () {
  45125. function AnimationEvent(frame, action, onlyOnce) {
  45126. this.frame = frame;
  45127. this.action = action;
  45128. this.onlyOnce = onlyOnce;
  45129. this.isDone = false;
  45130. }
  45131. return AnimationEvent;
  45132. }());
  45133. BABYLON.AnimationEvent = AnimationEvent;
  45134. var PathCursor = /** @class */ (function () {
  45135. function PathCursor(path) {
  45136. this.path = path;
  45137. this._onchange = new Array();
  45138. this.value = 0;
  45139. this.animations = new Array();
  45140. }
  45141. PathCursor.prototype.getPoint = function () {
  45142. var point = this.path.getPointAtLengthPosition(this.value);
  45143. return new BABYLON.Vector3(point.x, 0, point.y);
  45144. };
  45145. PathCursor.prototype.moveAhead = function (step) {
  45146. if (step === void 0) { step = 0.002; }
  45147. this.move(step);
  45148. return this;
  45149. };
  45150. PathCursor.prototype.moveBack = function (step) {
  45151. if (step === void 0) { step = 0.002; }
  45152. this.move(-step);
  45153. return this;
  45154. };
  45155. PathCursor.prototype.move = function (step) {
  45156. if (Math.abs(step) > 1) {
  45157. throw "step size should be less than 1.";
  45158. }
  45159. this.value += step;
  45160. this.ensureLimits();
  45161. this.raiseOnChange();
  45162. return this;
  45163. };
  45164. PathCursor.prototype.ensureLimits = function () {
  45165. while (this.value > 1) {
  45166. this.value -= 1;
  45167. }
  45168. while (this.value < 0) {
  45169. this.value += 1;
  45170. }
  45171. return this;
  45172. };
  45173. // used by animation engine
  45174. PathCursor.prototype.raiseOnChange = function () {
  45175. var _this = this;
  45176. this._onchange.forEach(function (f) { return f(_this); });
  45177. return this;
  45178. };
  45179. PathCursor.prototype.onchange = function (f) {
  45180. this._onchange.push(f);
  45181. return this;
  45182. };
  45183. return PathCursor;
  45184. }());
  45185. BABYLON.PathCursor = PathCursor;
  45186. var AnimationKeyInterpolation;
  45187. (function (AnimationKeyInterpolation) {
  45188. /**
  45189. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45190. */
  45191. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45192. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45193. var Animation = /** @class */ (function () {
  45194. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45195. this.name = name;
  45196. this.targetProperty = targetProperty;
  45197. this.framePerSecond = framePerSecond;
  45198. this.dataType = dataType;
  45199. this.loopMode = loopMode;
  45200. this.enableBlending = enableBlending;
  45201. this._runtimeAnimations = new Array();
  45202. // The set of event that will be linked to this animation
  45203. this._events = new Array();
  45204. this.blendingSpeed = 0.01;
  45205. this._ranges = {};
  45206. this.targetPropertyPath = targetProperty.split(".");
  45207. this.dataType = dataType;
  45208. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45209. }
  45210. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45211. var dataType = undefined;
  45212. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45213. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45214. }
  45215. else if (from instanceof BABYLON.Quaternion) {
  45216. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45217. }
  45218. else if (from instanceof BABYLON.Vector3) {
  45219. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45220. }
  45221. else if (from instanceof BABYLON.Vector2) {
  45222. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45223. }
  45224. else if (from instanceof BABYLON.Color3) {
  45225. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45226. }
  45227. else if (from instanceof BABYLON.Size) {
  45228. dataType = Animation.ANIMATIONTYPE_SIZE;
  45229. }
  45230. if (dataType == undefined) {
  45231. return null;
  45232. }
  45233. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45234. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45235. animation.setKeys(keys);
  45236. if (easingFunction !== undefined) {
  45237. animation.setEasingFunction(easingFunction);
  45238. }
  45239. return animation;
  45240. };
  45241. /**
  45242. * Sets up an animation.
  45243. * @param property the property to animate
  45244. * @param animationType the animation type to apply
  45245. * @param easingFunction the easing function used in the animation
  45246. * @returns The created animation
  45247. */
  45248. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45249. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45250. animation.setEasingFunction(easingFunction);
  45251. return animation;
  45252. };
  45253. /**
  45254. * Create and start an animation on a node
  45255. * @param {string} name defines the name of the global animation that will be run on all nodes
  45256. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45257. * @param {string} targetProperty defines property to animate
  45258. * @param {number} framePerSecond defines the number of frame per second yo use
  45259. * @param {number} totalFrame defines the number of frames in total
  45260. * @param {any} from defines the initial value
  45261. * @param {any} to defines the final value
  45262. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45263. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45264. * @param onAnimationEnd defines the callback to call when animation end
  45265. * @returns the animatable created for this animation
  45266. */
  45267. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45268. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45269. if (!animation) {
  45270. return null;
  45271. }
  45272. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45273. };
  45274. /**
  45275. * Create and start an animation on a node and its descendants
  45276. * @param {string} name defines the name of the global animation that will be run on all nodes
  45277. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45278. * @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.
  45279. * @param {string} targetProperty defines property to animate
  45280. * @param {number} framePerSecond defines the number of frame per second yo use
  45281. * @param {number} totalFrame defines the number of frames in total
  45282. * @param {any} from defines the initial value
  45283. * @param {any} to defines the final value
  45284. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45285. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45286. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45287. * @returns the list of animatables created for all nodes
  45288. * @example https://www.babylonjs-playground.com/#MH0VLI
  45289. */
  45290. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45291. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45292. if (!animation) {
  45293. return null;
  45294. }
  45295. var scene = node.getScene();
  45296. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45297. };
  45298. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45299. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45300. if (!animation) {
  45301. return null;
  45302. }
  45303. node.animations.push(animation);
  45304. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45305. };
  45306. /**
  45307. * Transition property of the Camera to the target Value.
  45308. * @param property The property to transition
  45309. * @param targetValue The target Value of the property
  45310. * @param host The object where the property to animate belongs
  45311. * @param scene Scene used to run the animation
  45312. * @param frameRate Framerate (in frame/s) to use
  45313. * @param transition The transition type we want to use
  45314. * @param duration The duration of the animation, in milliseconds
  45315. * @param onAnimationEnd Call back trigger at the end of the animation.
  45316. */
  45317. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45318. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45319. if (duration <= 0) {
  45320. host[property] = targetValue;
  45321. if (onAnimationEnd) {
  45322. onAnimationEnd();
  45323. }
  45324. return null;
  45325. }
  45326. var endFrame = frameRate * (duration / 1000);
  45327. transition.setKeys([{
  45328. frame: 0,
  45329. value: host[property].clone ? host[property].clone() : host[property]
  45330. },
  45331. {
  45332. frame: endFrame,
  45333. value: targetValue
  45334. }]);
  45335. if (!host.animations) {
  45336. host.animations = [];
  45337. }
  45338. host.animations.push(transition);
  45339. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45340. animation.onAnimationEnd = onAnimationEnd;
  45341. return animation;
  45342. };
  45343. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45344. /**
  45345. * Return the array of runtime animations currently using this animation
  45346. */
  45347. get: function () {
  45348. return this._runtimeAnimations;
  45349. },
  45350. enumerable: true,
  45351. configurable: true
  45352. });
  45353. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45354. get: function () {
  45355. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45356. var runtimeAnimation = _a[_i];
  45357. if (!runtimeAnimation.isStopped) {
  45358. return true;
  45359. }
  45360. }
  45361. return false;
  45362. },
  45363. enumerable: true,
  45364. configurable: true
  45365. });
  45366. // Methods
  45367. /**
  45368. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45369. */
  45370. Animation.prototype.toString = function (fullDetails) {
  45371. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45372. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45373. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45374. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45375. if (fullDetails) {
  45376. ret += ", Ranges: {";
  45377. var first = true;
  45378. for (var name in this._ranges) {
  45379. if (first) {
  45380. ret += ", ";
  45381. first = false;
  45382. }
  45383. ret += name;
  45384. }
  45385. ret += "}";
  45386. }
  45387. return ret;
  45388. };
  45389. /**
  45390. * Add an event to this animation.
  45391. */
  45392. Animation.prototype.addEvent = function (event) {
  45393. this._events.push(event);
  45394. };
  45395. /**
  45396. * Remove all events found at the given frame
  45397. * @param frame
  45398. */
  45399. Animation.prototype.removeEvents = function (frame) {
  45400. for (var index = 0; index < this._events.length; index++) {
  45401. if (this._events[index].frame === frame) {
  45402. this._events.splice(index, 1);
  45403. index--;
  45404. }
  45405. }
  45406. };
  45407. Animation.prototype.getEvents = function () {
  45408. return this._events;
  45409. };
  45410. Animation.prototype.createRange = function (name, from, to) {
  45411. // check name not already in use; could happen for bones after serialized
  45412. if (!this._ranges[name]) {
  45413. this._ranges[name] = new AnimationRange(name, from, to);
  45414. }
  45415. };
  45416. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45417. if (deleteFrames === void 0) { deleteFrames = true; }
  45418. var range = this._ranges[name];
  45419. if (!range) {
  45420. return;
  45421. }
  45422. if (deleteFrames) {
  45423. var from = range.from;
  45424. var to = range.to;
  45425. // this loop MUST go high to low for multiple splices to work
  45426. for (var key = this._keys.length - 1; key >= 0; key--) {
  45427. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45428. this._keys.splice(key, 1);
  45429. }
  45430. }
  45431. }
  45432. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45433. };
  45434. Animation.prototype.getRange = function (name) {
  45435. return this._ranges[name];
  45436. };
  45437. Animation.prototype.getKeys = function () {
  45438. return this._keys;
  45439. };
  45440. Animation.prototype.getHighestFrame = function () {
  45441. var ret = 0;
  45442. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45443. if (ret < this._keys[key].frame) {
  45444. ret = this._keys[key].frame;
  45445. }
  45446. }
  45447. return ret;
  45448. };
  45449. Animation.prototype.getEasingFunction = function () {
  45450. return this._easingFunction;
  45451. };
  45452. Animation.prototype.setEasingFunction = function (easingFunction) {
  45453. this._easingFunction = easingFunction;
  45454. };
  45455. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45456. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45457. };
  45458. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45459. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45460. };
  45461. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45462. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45463. };
  45464. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45465. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45466. };
  45467. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45468. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45469. };
  45470. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45471. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45472. };
  45473. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45474. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45475. };
  45476. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45477. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45478. };
  45479. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45480. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45481. };
  45482. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45483. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45484. };
  45485. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45486. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45487. };
  45488. Animation.prototype.clone = function () {
  45489. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45490. clone.enableBlending = this.enableBlending;
  45491. clone.blendingSpeed = this.blendingSpeed;
  45492. if (this._keys) {
  45493. clone.setKeys(this._keys);
  45494. }
  45495. if (this._ranges) {
  45496. clone._ranges = {};
  45497. for (var name in this._ranges) {
  45498. var range = this._ranges[name];
  45499. if (!range) {
  45500. continue;
  45501. }
  45502. clone._ranges[name] = range.clone();
  45503. }
  45504. }
  45505. return clone;
  45506. };
  45507. Animation.prototype.setKeys = function (values) {
  45508. this._keys = values.slice(0);
  45509. };
  45510. Animation.prototype.serialize = function () {
  45511. var serializationObject = {};
  45512. serializationObject.name = this.name;
  45513. serializationObject.property = this.targetProperty;
  45514. serializationObject.framePerSecond = this.framePerSecond;
  45515. serializationObject.dataType = this.dataType;
  45516. serializationObject.loopBehavior = this.loopMode;
  45517. serializationObject.enableBlending = this.enableBlending;
  45518. serializationObject.blendingSpeed = this.blendingSpeed;
  45519. var dataType = this.dataType;
  45520. serializationObject.keys = [];
  45521. var keys = this.getKeys();
  45522. for (var index = 0; index < keys.length; index++) {
  45523. var animationKey = keys[index];
  45524. var key = {};
  45525. key.frame = animationKey.frame;
  45526. switch (dataType) {
  45527. case Animation.ANIMATIONTYPE_FLOAT:
  45528. key.values = [animationKey.value];
  45529. break;
  45530. case Animation.ANIMATIONTYPE_QUATERNION:
  45531. case Animation.ANIMATIONTYPE_MATRIX:
  45532. case Animation.ANIMATIONTYPE_VECTOR3:
  45533. case Animation.ANIMATIONTYPE_COLOR3:
  45534. key.values = animationKey.value.asArray();
  45535. break;
  45536. }
  45537. serializationObject.keys.push(key);
  45538. }
  45539. serializationObject.ranges = [];
  45540. for (var name in this._ranges) {
  45541. var source = this._ranges[name];
  45542. if (!source) {
  45543. continue;
  45544. }
  45545. var range = {};
  45546. range.name = name;
  45547. range.from = source.from;
  45548. range.to = source.to;
  45549. serializationObject.ranges.push(range);
  45550. }
  45551. return serializationObject;
  45552. };
  45553. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45554. get: function () {
  45555. return Animation._ANIMATIONTYPE_FLOAT;
  45556. },
  45557. enumerable: true,
  45558. configurable: true
  45559. });
  45560. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45561. get: function () {
  45562. return Animation._ANIMATIONTYPE_VECTOR3;
  45563. },
  45564. enumerable: true,
  45565. configurable: true
  45566. });
  45567. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45568. get: function () {
  45569. return Animation._ANIMATIONTYPE_VECTOR2;
  45570. },
  45571. enumerable: true,
  45572. configurable: true
  45573. });
  45574. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45575. get: function () {
  45576. return Animation._ANIMATIONTYPE_SIZE;
  45577. },
  45578. enumerable: true,
  45579. configurable: true
  45580. });
  45581. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45582. get: function () {
  45583. return Animation._ANIMATIONTYPE_QUATERNION;
  45584. },
  45585. enumerable: true,
  45586. configurable: true
  45587. });
  45588. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45589. get: function () {
  45590. return Animation._ANIMATIONTYPE_MATRIX;
  45591. },
  45592. enumerable: true,
  45593. configurable: true
  45594. });
  45595. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45596. get: function () {
  45597. return Animation._ANIMATIONTYPE_COLOR3;
  45598. },
  45599. enumerable: true,
  45600. configurable: true
  45601. });
  45602. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45603. get: function () {
  45604. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45605. },
  45606. enumerable: true,
  45607. configurable: true
  45608. });
  45609. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45610. get: function () {
  45611. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45612. },
  45613. enumerable: true,
  45614. configurable: true
  45615. });
  45616. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45617. get: function () {
  45618. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45619. },
  45620. enumerable: true,
  45621. configurable: true
  45622. });
  45623. Animation.Parse = function (parsedAnimation) {
  45624. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45625. var dataType = parsedAnimation.dataType;
  45626. var keys = [];
  45627. var data;
  45628. var index;
  45629. if (parsedAnimation.enableBlending) {
  45630. animation.enableBlending = parsedAnimation.enableBlending;
  45631. }
  45632. if (parsedAnimation.blendingSpeed) {
  45633. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45634. }
  45635. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45636. var key = parsedAnimation.keys[index];
  45637. var inTangent;
  45638. var outTangent;
  45639. switch (dataType) {
  45640. case Animation.ANIMATIONTYPE_FLOAT:
  45641. data = key.values[0];
  45642. if (key.values.length >= 1) {
  45643. inTangent = key.values[1];
  45644. }
  45645. if (key.values.length >= 2) {
  45646. outTangent = key.values[2];
  45647. }
  45648. break;
  45649. case Animation.ANIMATIONTYPE_QUATERNION:
  45650. data = BABYLON.Quaternion.FromArray(key.values);
  45651. if (key.values.length >= 8) {
  45652. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  45653. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  45654. inTangent = _inTangent;
  45655. }
  45656. }
  45657. if (key.values.length >= 12) {
  45658. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  45659. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  45660. outTangent = _outTangent;
  45661. }
  45662. }
  45663. break;
  45664. case Animation.ANIMATIONTYPE_MATRIX:
  45665. data = BABYLON.Matrix.FromArray(key.values);
  45666. break;
  45667. case Animation.ANIMATIONTYPE_COLOR3:
  45668. data = BABYLON.Color3.FromArray(key.values);
  45669. break;
  45670. case Animation.ANIMATIONTYPE_VECTOR3:
  45671. default:
  45672. data = BABYLON.Vector3.FromArray(key.values);
  45673. break;
  45674. }
  45675. var keyData = {};
  45676. keyData.frame = key.frame;
  45677. keyData.value = data;
  45678. if (inTangent != undefined) {
  45679. keyData.inTangent = inTangent;
  45680. }
  45681. if (outTangent != undefined) {
  45682. keyData.outTangent = outTangent;
  45683. }
  45684. keys.push(keyData);
  45685. }
  45686. animation.setKeys(keys);
  45687. if (parsedAnimation.ranges) {
  45688. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  45689. data = parsedAnimation.ranges[index];
  45690. animation.createRange(data.name, data.from, data.to);
  45691. }
  45692. }
  45693. return animation;
  45694. };
  45695. Animation.AppendSerializedAnimations = function (source, destination) {
  45696. if (source.animations) {
  45697. destination.animations = [];
  45698. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  45699. var animation = source.animations[animationIndex];
  45700. destination.animations.push(animation.serialize());
  45701. }
  45702. }
  45703. };
  45704. Animation.AllowMatricesInterpolation = false;
  45705. // Statics
  45706. Animation._ANIMATIONTYPE_FLOAT = 0;
  45707. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  45708. Animation._ANIMATIONTYPE_QUATERNION = 2;
  45709. Animation._ANIMATIONTYPE_MATRIX = 3;
  45710. Animation._ANIMATIONTYPE_COLOR3 = 4;
  45711. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  45712. Animation._ANIMATIONTYPE_SIZE = 6;
  45713. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  45714. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  45715. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  45716. return Animation;
  45717. }());
  45718. BABYLON.Animation = Animation;
  45719. })(BABYLON || (BABYLON = {}));
  45720. //# sourceMappingURL=babylon.animation.js.map
  45721. var BABYLON;
  45722. (function (BABYLON) {
  45723. /**
  45724. * This class defines the direct association between an animation and a target
  45725. */
  45726. var TargetedAnimation = /** @class */ (function () {
  45727. function TargetedAnimation() {
  45728. }
  45729. return TargetedAnimation;
  45730. }());
  45731. BABYLON.TargetedAnimation = TargetedAnimation;
  45732. /**
  45733. * Use this class to create coordinated animations on multiple targets
  45734. */
  45735. var AnimationGroup = /** @class */ (function () {
  45736. function AnimationGroup(name, scene) {
  45737. if (scene === void 0) { scene = null; }
  45738. this.name = name;
  45739. this._targetedAnimations = new Array();
  45740. this._animatables = new Array();
  45741. this._from = Number.MAX_VALUE;
  45742. this._to = -Number.MAX_VALUE;
  45743. this._speedRatio = 1;
  45744. this.onAnimationEndObservable = new BABYLON.Observable();
  45745. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45746. this._scene.animationGroups.push(this);
  45747. }
  45748. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  45749. /**
  45750. * Define if the animations are started
  45751. */
  45752. get: function () {
  45753. return this._isStarted;
  45754. },
  45755. enumerable: true,
  45756. configurable: true
  45757. });
  45758. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  45759. /**
  45760. * Gets or sets the speed ratio to use for all animations
  45761. */
  45762. get: function () {
  45763. return this._speedRatio;
  45764. },
  45765. /**
  45766. * Gets or sets the speed ratio to use for all animations
  45767. */
  45768. set: function (value) {
  45769. if (this._speedRatio === value) {
  45770. return;
  45771. }
  45772. this._speedRatio = value;
  45773. for (var index = 0; index < this._animatables.length; index++) {
  45774. var animatable = this._animatables[index];
  45775. animatable.speedRatio = this._speedRatio;
  45776. }
  45777. },
  45778. enumerable: true,
  45779. configurable: true
  45780. });
  45781. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  45782. /**
  45783. * Gets the targeted animations for this animation group
  45784. */
  45785. get: function () {
  45786. return this._targetedAnimations;
  45787. },
  45788. enumerable: true,
  45789. configurable: true
  45790. });
  45791. /**
  45792. * Add an animation (with its target) in the group
  45793. * @param animation defines the animation we want to add
  45794. * @param target defines the target of the animation
  45795. * @returns the {BABYLON.TargetedAnimation} object
  45796. */
  45797. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  45798. var targetedAnimation = {
  45799. animation: animation,
  45800. target: target
  45801. };
  45802. var keys = animation.getKeys();
  45803. if (this._from > keys[0].frame) {
  45804. this._from = keys[0].frame;
  45805. }
  45806. if (this._to < keys[keys.length - 1].frame) {
  45807. this._to = keys[keys.length - 1].frame;
  45808. }
  45809. this._targetedAnimations.push(targetedAnimation);
  45810. return targetedAnimation;
  45811. };
  45812. /**
  45813. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  45814. * It can add constant keys at begin or end
  45815. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  45816. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  45817. */
  45818. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  45819. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  45820. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  45821. beginFrame = Math.max(beginFrame, this._from);
  45822. endFrame = Math.min(endFrame, this._to);
  45823. for (var index = 0; index < this._targetedAnimations.length; index++) {
  45824. var targetedAnimation = this._targetedAnimations[index];
  45825. var keys = targetedAnimation.animation.getKeys();
  45826. var startKey = keys[0];
  45827. var endKey = keys[keys.length - 1];
  45828. if (startKey.frame > beginFrame) {
  45829. var newKey = {
  45830. frame: beginFrame,
  45831. value: startKey.value,
  45832. inTangent: startKey.inTangent,
  45833. outTangent: startKey.outTangent,
  45834. interpolation: startKey.interpolation
  45835. };
  45836. keys.splice(0, 0, newKey);
  45837. }
  45838. if (endKey.frame < endFrame) {
  45839. var newKey = {
  45840. frame: endFrame,
  45841. value: endKey.value,
  45842. inTangent: endKey.outTangent,
  45843. outTangent: endKey.outTangent,
  45844. interpolation: endKey.interpolation
  45845. };
  45846. keys.push(newKey);
  45847. }
  45848. }
  45849. return this;
  45850. };
  45851. /**
  45852. * Start all animations on given targets
  45853. * @param loop defines if animations must loop
  45854. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  45855. */
  45856. AnimationGroup.prototype.start = function (loop, speedRatio) {
  45857. var _this = this;
  45858. if (loop === void 0) { loop = false; }
  45859. if (speedRatio === void 0) { speedRatio = 1; }
  45860. if (this._isStarted || this._targetedAnimations.length === 0) {
  45861. return this;
  45862. }
  45863. var _loop_1 = function () {
  45864. var targetedAnimation = this_1._targetedAnimations[index];
  45865. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  45866. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  45867. }));
  45868. };
  45869. var this_1 = this;
  45870. for (var index = 0; index < this._targetedAnimations.length; index++) {
  45871. _loop_1();
  45872. }
  45873. this._speedRatio = speedRatio;
  45874. this._isStarted = true;
  45875. return this;
  45876. };
  45877. /**
  45878. * Pause all animations
  45879. */
  45880. AnimationGroup.prototype.pause = function () {
  45881. if (!this._isStarted) {
  45882. return this;
  45883. }
  45884. for (var index = 0; index < this._animatables.length; index++) {
  45885. var animatable = this._animatables[index];
  45886. animatable.pause();
  45887. }
  45888. return this;
  45889. };
  45890. /**
  45891. * Play all animations to initial state
  45892. * This function will start() the animations if they were not started or will restart() them if they were paused
  45893. * @param loop defines if animations must loop
  45894. */
  45895. AnimationGroup.prototype.play = function (loop) {
  45896. if (this.isStarted) {
  45897. if (loop !== undefined) {
  45898. for (var index = 0; index < this._animatables.length; index++) {
  45899. var animatable = this._animatables[index];
  45900. animatable.loopAnimation = loop;
  45901. }
  45902. }
  45903. this.restart();
  45904. }
  45905. else {
  45906. this.start(loop, this._speedRatio);
  45907. }
  45908. return this;
  45909. };
  45910. /**
  45911. * Reset all animations to initial state
  45912. */
  45913. AnimationGroup.prototype.reset = function () {
  45914. if (!this._isStarted) {
  45915. return this;
  45916. }
  45917. for (var index = 0; index < this._animatables.length; index++) {
  45918. var animatable = this._animatables[index];
  45919. animatable.reset();
  45920. }
  45921. return this;
  45922. };
  45923. /**
  45924. * Restart animations from key 0
  45925. */
  45926. AnimationGroup.prototype.restart = function () {
  45927. if (!this._isStarted) {
  45928. return this;
  45929. }
  45930. for (var index = 0; index < this._animatables.length; index++) {
  45931. var animatable = this._animatables[index];
  45932. animatable.restart();
  45933. }
  45934. return this;
  45935. };
  45936. /**
  45937. * Stop all animations
  45938. */
  45939. AnimationGroup.prototype.stop = function () {
  45940. if (!this._isStarted) {
  45941. return this;
  45942. }
  45943. for (var index = 0; index < this._animatables.length; index++) {
  45944. var animatable = this._animatables[index];
  45945. animatable.stop();
  45946. }
  45947. this._isStarted = false;
  45948. return this;
  45949. };
  45950. /**
  45951. * Dispose all associated resources
  45952. */
  45953. AnimationGroup.prototype.dispose = function () {
  45954. this._targetedAnimations = [];
  45955. this._animatables = [];
  45956. var index = this._scene.animationGroups.indexOf(this);
  45957. if (index > -1) {
  45958. this._scene.animationGroups.splice(index, 1);
  45959. }
  45960. };
  45961. return AnimationGroup;
  45962. }());
  45963. BABYLON.AnimationGroup = AnimationGroup;
  45964. })(BABYLON || (BABYLON = {}));
  45965. //# sourceMappingURL=babylon.animationGroup.js.map
  45966. var BABYLON;
  45967. (function (BABYLON) {
  45968. var RuntimeAnimation = /** @class */ (function () {
  45969. function RuntimeAnimation(target, animation) {
  45970. this._offsetsCache = {};
  45971. this._highLimitsCache = {};
  45972. this._stopped = false;
  45973. this._blendingFactor = 0;
  45974. this._ratioOffset = 0;
  45975. this._animation = animation;
  45976. this._target = target;
  45977. animation._runtimeAnimations.push(this);
  45978. }
  45979. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  45980. get: function () {
  45981. return this._animation;
  45982. },
  45983. enumerable: true,
  45984. configurable: true
  45985. });
  45986. RuntimeAnimation.prototype.reset = function () {
  45987. this._offsetsCache = {};
  45988. this._highLimitsCache = {};
  45989. this.currentFrame = 0;
  45990. this._blendingFactor = 0;
  45991. this._originalBlendValue = null;
  45992. };
  45993. RuntimeAnimation.prototype.isStopped = function () {
  45994. return this._stopped;
  45995. };
  45996. RuntimeAnimation.prototype.dispose = function () {
  45997. var index = this._animation.runtimeAnimations.indexOf(this);
  45998. if (index > -1) {
  45999. this._animation.runtimeAnimations.splice(index, 1);
  46000. }
  46001. };
  46002. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46003. if (typeof value === "function") {
  46004. return value();
  46005. }
  46006. return value;
  46007. };
  46008. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46009. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46010. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46011. }
  46012. this.currentFrame = currentFrame;
  46013. var keys = this._animation.getKeys();
  46014. // Try to get a hash to find the right key
  46015. 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));
  46016. if (keys[startKeyIndex].frame >= currentFrame) {
  46017. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46018. startKeyIndex--;
  46019. }
  46020. }
  46021. for (var key = startKeyIndex; key < keys.length; key++) {
  46022. var endKey = keys[key + 1];
  46023. if (endKey.frame >= currentFrame) {
  46024. var startKey = keys[key];
  46025. var startValue = this._getKeyValue(startKey.value);
  46026. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46027. return startValue;
  46028. }
  46029. var endValue = this._getKeyValue(endKey.value);
  46030. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46031. var frameDelta = endKey.frame - startKey.frame;
  46032. // gradient : percent of currentFrame between the frame inf and the frame sup
  46033. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46034. // check for easingFunction and correction of gradient
  46035. var easingFunction = this._animation.getEasingFunction();
  46036. if (easingFunction != null) {
  46037. gradient = easingFunction.ease(gradient);
  46038. }
  46039. switch (this._animation.dataType) {
  46040. // Float
  46041. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46042. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46043. switch (loopMode) {
  46044. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46045. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46046. return floatValue;
  46047. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46048. return offsetValue * repeatCount + floatValue;
  46049. }
  46050. break;
  46051. // Quaternion
  46052. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46053. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46054. switch (loopMode) {
  46055. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46056. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46057. return quatValue;
  46058. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46059. return quatValue.add(offsetValue.scale(repeatCount));
  46060. }
  46061. return quatValue;
  46062. // Vector3
  46063. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46064. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46065. switch (loopMode) {
  46066. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46067. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46068. return vec3Value;
  46069. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46070. return vec3Value.add(offsetValue.scale(repeatCount));
  46071. }
  46072. // Vector2
  46073. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46074. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46075. switch (loopMode) {
  46076. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46077. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46078. return vec2Value;
  46079. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46080. return vec2Value.add(offsetValue.scale(repeatCount));
  46081. }
  46082. // Size
  46083. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46084. switch (loopMode) {
  46085. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46086. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46087. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46088. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46089. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46090. }
  46091. // Color3
  46092. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46093. switch (loopMode) {
  46094. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46095. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46096. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46097. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46098. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46099. }
  46100. // Matrix
  46101. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46102. switch (loopMode) {
  46103. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46104. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46105. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46106. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46107. }
  46108. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46109. return startValue;
  46110. }
  46111. default:
  46112. break;
  46113. }
  46114. break;
  46115. }
  46116. }
  46117. return this._getKeyValue(keys[keys.length - 1].value);
  46118. };
  46119. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46120. if (blend === void 0) { blend = false; }
  46121. // Set value
  46122. var path;
  46123. var destination;
  46124. var targetPropertyPath = this._animation.targetPropertyPath;
  46125. if (targetPropertyPath.length > 1) {
  46126. var property = this._target[targetPropertyPath[0]];
  46127. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46128. property = property[targetPropertyPath[index]];
  46129. }
  46130. path = targetPropertyPath[targetPropertyPath.length - 1];
  46131. destination = property;
  46132. }
  46133. else {
  46134. path = targetPropertyPath[0];
  46135. destination = this._target;
  46136. }
  46137. // Blending
  46138. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46139. if (!this._originalBlendValue) {
  46140. if (destination[path].clone) {
  46141. this._originalBlendValue = destination[path].clone();
  46142. }
  46143. else {
  46144. this._originalBlendValue = destination[path];
  46145. }
  46146. }
  46147. if (this._originalBlendValue.prototype) {
  46148. if (this._originalBlendValue.prototype.Lerp) {
  46149. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46150. }
  46151. else {
  46152. destination[path] = currentValue;
  46153. }
  46154. }
  46155. else if (this._originalBlendValue.m) {
  46156. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46157. }
  46158. else {
  46159. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46160. }
  46161. this._blendingFactor += this._animation.blendingSpeed;
  46162. }
  46163. else {
  46164. destination[path] = currentValue;
  46165. }
  46166. if (this._target.markAsDirty) {
  46167. this._target.markAsDirty(this._animation.targetProperty);
  46168. }
  46169. };
  46170. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46171. var keys = this._animation.getKeys();
  46172. if (frame < keys[0].frame) {
  46173. frame = keys[0].frame;
  46174. }
  46175. else if (frame > keys[keys.length - 1].frame) {
  46176. frame = keys[keys.length - 1].frame;
  46177. }
  46178. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46179. this.setValue(currentValue);
  46180. };
  46181. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46182. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46183. this._ratioOffset = this._previousRatio - newRatio;
  46184. };
  46185. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46186. if (blend === void 0) { blend = false; }
  46187. var targetPropertyPath = this._animation.targetPropertyPath;
  46188. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46189. this._stopped = true;
  46190. return false;
  46191. }
  46192. var returnValue = true;
  46193. var keys = this._animation.getKeys();
  46194. // Adding a start key at frame 0 if missing
  46195. if (keys[0].frame !== 0) {
  46196. var newKey = { frame: 0, value: keys[0].value };
  46197. keys.splice(0, 0, newKey);
  46198. }
  46199. // Check limits
  46200. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46201. from = keys[0].frame;
  46202. }
  46203. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46204. to = keys[keys.length - 1].frame;
  46205. }
  46206. //to and from cannot be the same key
  46207. if (from === to) {
  46208. if (from > keys[0].frame) {
  46209. from--;
  46210. }
  46211. else if (to < keys[keys.length - 1].frame) {
  46212. to++;
  46213. }
  46214. }
  46215. // Compute ratio
  46216. var range = to - from;
  46217. var offsetValue;
  46218. // ratio represents the frame delta between from and to
  46219. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46220. var highLimitValue = 0;
  46221. this._previousDelay = delay;
  46222. this._previousRatio = ratio;
  46223. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46224. returnValue = false;
  46225. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46226. }
  46227. else {
  46228. // Get max value if required
  46229. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46230. var keyOffset = to.toString() + from.toString();
  46231. if (!this._offsetsCache[keyOffset]) {
  46232. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46233. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46234. switch (this._animation.dataType) {
  46235. // Float
  46236. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46237. this._offsetsCache[keyOffset] = toValue - fromValue;
  46238. break;
  46239. // Quaternion
  46240. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46241. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46242. break;
  46243. // Vector3
  46244. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46245. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46246. // Vector2
  46247. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46248. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46249. // Size
  46250. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46251. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46252. // Color3
  46253. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46254. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46255. default:
  46256. break;
  46257. }
  46258. this._highLimitsCache[keyOffset] = toValue;
  46259. }
  46260. highLimitValue = this._highLimitsCache[keyOffset];
  46261. offsetValue = this._offsetsCache[keyOffset];
  46262. }
  46263. }
  46264. if (offsetValue === undefined) {
  46265. switch (this._animation.dataType) {
  46266. // Float
  46267. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46268. offsetValue = 0;
  46269. break;
  46270. // Quaternion
  46271. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46272. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46273. break;
  46274. // Vector3
  46275. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46276. offsetValue = BABYLON.Vector3.Zero();
  46277. break;
  46278. // Vector2
  46279. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46280. offsetValue = BABYLON.Vector2.Zero();
  46281. break;
  46282. // Size
  46283. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46284. offsetValue = BABYLON.Size.Zero();
  46285. break;
  46286. // Color3
  46287. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46288. offsetValue = BABYLON.Color3.Black();
  46289. }
  46290. }
  46291. // Compute value
  46292. var repeatCount = (ratio / range) >> 0;
  46293. var currentFrame = returnValue ? from + ratio % range : to;
  46294. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46295. // Set value
  46296. this.setValue(currentValue);
  46297. // Check events
  46298. var events = this._animation.getEvents();
  46299. for (var index = 0; index < events.length; index++) {
  46300. // Make sure current frame has passed event frame and that event frame is within the current range
  46301. // Also, handle both forward and reverse animations
  46302. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46303. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46304. var event = events[index];
  46305. if (!event.isDone) {
  46306. // If event should be done only once, remove it.
  46307. if (event.onlyOnce) {
  46308. events.splice(index, 1);
  46309. index--;
  46310. }
  46311. event.isDone = true;
  46312. event.action();
  46313. } // Don't do anything if the event has already be done.
  46314. }
  46315. else if (events[index].isDone && !events[index].onlyOnce) {
  46316. // reset event, the animation is looping
  46317. events[index].isDone = false;
  46318. }
  46319. }
  46320. if (!returnValue) {
  46321. this._stopped = true;
  46322. }
  46323. return returnValue;
  46324. };
  46325. return RuntimeAnimation;
  46326. }());
  46327. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46328. })(BABYLON || (BABYLON = {}));
  46329. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46330. var BABYLON;
  46331. (function (BABYLON) {
  46332. var Animatable = /** @class */ (function () {
  46333. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46334. if (fromFrame === void 0) { fromFrame = 0; }
  46335. if (toFrame === void 0) { toFrame = 100; }
  46336. if (loopAnimation === void 0) { loopAnimation = false; }
  46337. if (speedRatio === void 0) { speedRatio = 1.0; }
  46338. this.target = target;
  46339. this.fromFrame = fromFrame;
  46340. this.toFrame = toFrame;
  46341. this.loopAnimation = loopAnimation;
  46342. this.onAnimationEnd = onAnimationEnd;
  46343. this._localDelayOffset = null;
  46344. this._pausedDelay = null;
  46345. this._runtimeAnimations = new Array();
  46346. this._paused = false;
  46347. this._speedRatio = 1;
  46348. this.animationStarted = false;
  46349. if (animations) {
  46350. this.appendAnimations(target, animations);
  46351. }
  46352. this._speedRatio = speedRatio;
  46353. this._scene = scene;
  46354. scene._activeAnimatables.push(this);
  46355. }
  46356. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46357. get: function () {
  46358. return this._speedRatio;
  46359. },
  46360. set: function (value) {
  46361. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46362. var animation = this._runtimeAnimations[index];
  46363. animation._prepareForSpeedRatioChange(value);
  46364. }
  46365. this._speedRatio = value;
  46366. },
  46367. enumerable: true,
  46368. configurable: true
  46369. });
  46370. // Methods
  46371. Animatable.prototype.getAnimations = function () {
  46372. return this._runtimeAnimations;
  46373. };
  46374. Animatable.prototype.appendAnimations = function (target, animations) {
  46375. for (var index = 0; index < animations.length; index++) {
  46376. var animation = animations[index];
  46377. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46378. }
  46379. };
  46380. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46381. var runtimeAnimations = this._runtimeAnimations;
  46382. for (var index = 0; index < runtimeAnimations.length; index++) {
  46383. if (runtimeAnimations[index].animation.targetProperty === property) {
  46384. return runtimeAnimations[index].animation;
  46385. }
  46386. }
  46387. return null;
  46388. };
  46389. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46390. var runtimeAnimations = this._runtimeAnimations;
  46391. for (var index = 0; index < runtimeAnimations.length; index++) {
  46392. if (runtimeAnimations[index].animation.targetProperty === property) {
  46393. return runtimeAnimations[index];
  46394. }
  46395. }
  46396. return null;
  46397. };
  46398. Animatable.prototype.reset = function () {
  46399. var runtimeAnimations = this._runtimeAnimations;
  46400. for (var index = 0; index < runtimeAnimations.length; index++) {
  46401. runtimeAnimations[index].reset();
  46402. }
  46403. // Reset to original value
  46404. for (index = 0; index < runtimeAnimations.length; index++) {
  46405. var animation = runtimeAnimations[index];
  46406. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46407. }
  46408. this._localDelayOffset = null;
  46409. this._pausedDelay = null;
  46410. };
  46411. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46412. var runtimeAnimations = this._runtimeAnimations;
  46413. for (var index = 0; index < runtimeAnimations.length; index++) {
  46414. runtimeAnimations[index].animation.enableBlending = true;
  46415. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46416. }
  46417. };
  46418. Animatable.prototype.disableBlending = function () {
  46419. var runtimeAnimations = this._runtimeAnimations;
  46420. for (var index = 0; index < runtimeAnimations.length; index++) {
  46421. runtimeAnimations[index].animation.enableBlending = false;
  46422. }
  46423. };
  46424. Animatable.prototype.goToFrame = function (frame) {
  46425. var runtimeAnimations = this._runtimeAnimations;
  46426. if (runtimeAnimations[0]) {
  46427. var fps = runtimeAnimations[0].animation.framePerSecond;
  46428. var currentFrame = runtimeAnimations[0].currentFrame;
  46429. var adjustTime = frame - currentFrame;
  46430. var delay = adjustTime * 1000 / fps;
  46431. if (this._localDelayOffset === null) {
  46432. this._localDelayOffset = 0;
  46433. }
  46434. this._localDelayOffset -= delay;
  46435. }
  46436. for (var index = 0; index < runtimeAnimations.length; index++) {
  46437. runtimeAnimations[index].goToFrame(frame);
  46438. }
  46439. };
  46440. Animatable.prototype.pause = function () {
  46441. if (this._paused) {
  46442. return;
  46443. }
  46444. this._paused = true;
  46445. };
  46446. Animatable.prototype.restart = function () {
  46447. this._paused = false;
  46448. };
  46449. Animatable.prototype.stop = function (animationName) {
  46450. if (animationName) {
  46451. var idx = this._scene._activeAnimatables.indexOf(this);
  46452. if (idx > -1) {
  46453. var runtimeAnimations = this._runtimeAnimations;
  46454. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46455. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46456. continue;
  46457. }
  46458. runtimeAnimations[index].dispose();
  46459. runtimeAnimations.splice(index, 1);
  46460. }
  46461. if (runtimeAnimations.length == 0) {
  46462. this._scene._activeAnimatables.splice(idx, 1);
  46463. if (this.onAnimationEnd) {
  46464. this.onAnimationEnd();
  46465. }
  46466. }
  46467. }
  46468. }
  46469. else {
  46470. var index = this._scene._activeAnimatables.indexOf(this);
  46471. if (index > -1) {
  46472. this._scene._activeAnimatables.splice(index, 1);
  46473. var runtimeAnimations = this._runtimeAnimations;
  46474. for (var index = 0; index < runtimeAnimations.length; index++) {
  46475. runtimeAnimations[index].dispose();
  46476. }
  46477. if (this.onAnimationEnd) {
  46478. this.onAnimationEnd();
  46479. }
  46480. }
  46481. }
  46482. };
  46483. Animatable.prototype._animate = function (delay) {
  46484. if (this._paused) {
  46485. this.animationStarted = false;
  46486. if (this._pausedDelay === null) {
  46487. this._pausedDelay = delay;
  46488. }
  46489. return true;
  46490. }
  46491. if (this._localDelayOffset === null) {
  46492. this._localDelayOffset = delay;
  46493. this._pausedDelay = null;
  46494. }
  46495. else if (this._pausedDelay !== null) {
  46496. this._localDelayOffset += delay - this._pausedDelay;
  46497. this._pausedDelay = null;
  46498. }
  46499. // Animating
  46500. var running = false;
  46501. var runtimeAnimations = this._runtimeAnimations;
  46502. var index;
  46503. for (index = 0; index < runtimeAnimations.length; index++) {
  46504. var animation = runtimeAnimations[index];
  46505. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46506. running = running || isRunning;
  46507. }
  46508. this.animationStarted = running;
  46509. if (!running) {
  46510. // Remove from active animatables
  46511. index = this._scene._activeAnimatables.indexOf(this);
  46512. this._scene._activeAnimatables.splice(index, 1);
  46513. // Dispose all runtime animations
  46514. for (index = 0; index < runtimeAnimations.length; index++) {
  46515. runtimeAnimations[index].dispose();
  46516. }
  46517. }
  46518. if (!running && this.onAnimationEnd) {
  46519. this.onAnimationEnd();
  46520. this.onAnimationEnd = null;
  46521. }
  46522. return running;
  46523. };
  46524. return Animatable;
  46525. }());
  46526. BABYLON.Animatable = Animatable;
  46527. })(BABYLON || (BABYLON = {}));
  46528. //# sourceMappingURL=babylon.animatable.js.map
  46529. var BABYLON;
  46530. (function (BABYLON) {
  46531. var EasingFunction = /** @class */ (function () {
  46532. function EasingFunction() {
  46533. // Properties
  46534. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46535. }
  46536. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46537. get: function () {
  46538. return EasingFunction._EASINGMODE_EASEIN;
  46539. },
  46540. enumerable: true,
  46541. configurable: true
  46542. });
  46543. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46544. get: function () {
  46545. return EasingFunction._EASINGMODE_EASEOUT;
  46546. },
  46547. enumerable: true,
  46548. configurable: true
  46549. });
  46550. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46551. get: function () {
  46552. return EasingFunction._EASINGMODE_EASEINOUT;
  46553. },
  46554. enumerable: true,
  46555. configurable: true
  46556. });
  46557. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46558. var n = Math.min(Math.max(easingMode, 0), 2);
  46559. this._easingMode = n;
  46560. };
  46561. EasingFunction.prototype.getEasingMode = function () {
  46562. return this._easingMode;
  46563. };
  46564. EasingFunction.prototype.easeInCore = function (gradient) {
  46565. throw new Error('You must implement this method');
  46566. };
  46567. EasingFunction.prototype.ease = function (gradient) {
  46568. switch (this._easingMode) {
  46569. case EasingFunction.EASINGMODE_EASEIN:
  46570. return this.easeInCore(gradient);
  46571. case EasingFunction.EASINGMODE_EASEOUT:
  46572. return (1 - this.easeInCore(1 - gradient));
  46573. }
  46574. if (gradient >= 0.5) {
  46575. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46576. }
  46577. return (this.easeInCore(gradient * 2) * 0.5);
  46578. };
  46579. //Statics
  46580. EasingFunction._EASINGMODE_EASEIN = 0;
  46581. EasingFunction._EASINGMODE_EASEOUT = 1;
  46582. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46583. return EasingFunction;
  46584. }());
  46585. BABYLON.EasingFunction = EasingFunction;
  46586. var CircleEase = /** @class */ (function (_super) {
  46587. __extends(CircleEase, _super);
  46588. function CircleEase() {
  46589. return _super !== null && _super.apply(this, arguments) || this;
  46590. }
  46591. CircleEase.prototype.easeInCore = function (gradient) {
  46592. gradient = Math.max(0, Math.min(1, gradient));
  46593. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46594. };
  46595. return CircleEase;
  46596. }(EasingFunction));
  46597. BABYLON.CircleEase = CircleEase;
  46598. var BackEase = /** @class */ (function (_super) {
  46599. __extends(BackEase, _super);
  46600. function BackEase(amplitude) {
  46601. if (amplitude === void 0) { amplitude = 1; }
  46602. var _this = _super.call(this) || this;
  46603. _this.amplitude = amplitude;
  46604. return _this;
  46605. }
  46606. BackEase.prototype.easeInCore = function (gradient) {
  46607. var num = Math.max(0, this.amplitude);
  46608. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46609. };
  46610. return BackEase;
  46611. }(EasingFunction));
  46612. BABYLON.BackEase = BackEase;
  46613. var BounceEase = /** @class */ (function (_super) {
  46614. __extends(BounceEase, _super);
  46615. function BounceEase(bounces, bounciness) {
  46616. if (bounces === void 0) { bounces = 3; }
  46617. if (bounciness === void 0) { bounciness = 2; }
  46618. var _this = _super.call(this) || this;
  46619. _this.bounces = bounces;
  46620. _this.bounciness = bounciness;
  46621. return _this;
  46622. }
  46623. BounceEase.prototype.easeInCore = function (gradient) {
  46624. var y = Math.max(0.0, this.bounces);
  46625. var bounciness = this.bounciness;
  46626. if (bounciness <= 1.0) {
  46627. bounciness = 1.001;
  46628. }
  46629. var num9 = Math.pow(bounciness, y);
  46630. var num5 = 1.0 - bounciness;
  46631. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46632. var num15 = gradient * num4;
  46633. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46634. var num3 = Math.floor(num65);
  46635. var num13 = num3 + 1.0;
  46636. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46637. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46638. var num7 = (num8 + num12) * 0.5;
  46639. var num6 = gradient - num7;
  46640. var num2 = num7 - num8;
  46641. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46642. };
  46643. return BounceEase;
  46644. }(EasingFunction));
  46645. BABYLON.BounceEase = BounceEase;
  46646. var CubicEase = /** @class */ (function (_super) {
  46647. __extends(CubicEase, _super);
  46648. function CubicEase() {
  46649. return _super !== null && _super.apply(this, arguments) || this;
  46650. }
  46651. CubicEase.prototype.easeInCore = function (gradient) {
  46652. return (gradient * gradient * gradient);
  46653. };
  46654. return CubicEase;
  46655. }(EasingFunction));
  46656. BABYLON.CubicEase = CubicEase;
  46657. var ElasticEase = /** @class */ (function (_super) {
  46658. __extends(ElasticEase, _super);
  46659. function ElasticEase(oscillations, springiness) {
  46660. if (oscillations === void 0) { oscillations = 3; }
  46661. if (springiness === void 0) { springiness = 3; }
  46662. var _this = _super.call(this) || this;
  46663. _this.oscillations = oscillations;
  46664. _this.springiness = springiness;
  46665. return _this;
  46666. }
  46667. ElasticEase.prototype.easeInCore = function (gradient) {
  46668. var num2;
  46669. var num3 = Math.max(0.0, this.oscillations);
  46670. var num = Math.max(0.0, this.springiness);
  46671. if (num == 0) {
  46672. num2 = gradient;
  46673. }
  46674. else {
  46675. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  46676. }
  46677. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  46678. };
  46679. return ElasticEase;
  46680. }(EasingFunction));
  46681. BABYLON.ElasticEase = ElasticEase;
  46682. var ExponentialEase = /** @class */ (function (_super) {
  46683. __extends(ExponentialEase, _super);
  46684. function ExponentialEase(exponent) {
  46685. if (exponent === void 0) { exponent = 2; }
  46686. var _this = _super.call(this) || this;
  46687. _this.exponent = exponent;
  46688. return _this;
  46689. }
  46690. ExponentialEase.prototype.easeInCore = function (gradient) {
  46691. if (this.exponent <= 0) {
  46692. return gradient;
  46693. }
  46694. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  46695. };
  46696. return ExponentialEase;
  46697. }(EasingFunction));
  46698. BABYLON.ExponentialEase = ExponentialEase;
  46699. var PowerEase = /** @class */ (function (_super) {
  46700. __extends(PowerEase, _super);
  46701. function PowerEase(power) {
  46702. if (power === void 0) { power = 2; }
  46703. var _this = _super.call(this) || this;
  46704. _this.power = power;
  46705. return _this;
  46706. }
  46707. PowerEase.prototype.easeInCore = function (gradient) {
  46708. var y = Math.max(0.0, this.power);
  46709. return Math.pow(gradient, y);
  46710. };
  46711. return PowerEase;
  46712. }(EasingFunction));
  46713. BABYLON.PowerEase = PowerEase;
  46714. var QuadraticEase = /** @class */ (function (_super) {
  46715. __extends(QuadraticEase, _super);
  46716. function QuadraticEase() {
  46717. return _super !== null && _super.apply(this, arguments) || this;
  46718. }
  46719. QuadraticEase.prototype.easeInCore = function (gradient) {
  46720. return (gradient * gradient);
  46721. };
  46722. return QuadraticEase;
  46723. }(EasingFunction));
  46724. BABYLON.QuadraticEase = QuadraticEase;
  46725. var QuarticEase = /** @class */ (function (_super) {
  46726. __extends(QuarticEase, _super);
  46727. function QuarticEase() {
  46728. return _super !== null && _super.apply(this, arguments) || this;
  46729. }
  46730. QuarticEase.prototype.easeInCore = function (gradient) {
  46731. return (gradient * gradient * gradient * gradient);
  46732. };
  46733. return QuarticEase;
  46734. }(EasingFunction));
  46735. BABYLON.QuarticEase = QuarticEase;
  46736. var QuinticEase = /** @class */ (function (_super) {
  46737. __extends(QuinticEase, _super);
  46738. function QuinticEase() {
  46739. return _super !== null && _super.apply(this, arguments) || this;
  46740. }
  46741. QuinticEase.prototype.easeInCore = function (gradient) {
  46742. return (gradient * gradient * gradient * gradient * gradient);
  46743. };
  46744. return QuinticEase;
  46745. }(EasingFunction));
  46746. BABYLON.QuinticEase = QuinticEase;
  46747. var SineEase = /** @class */ (function (_super) {
  46748. __extends(SineEase, _super);
  46749. function SineEase() {
  46750. return _super !== null && _super.apply(this, arguments) || this;
  46751. }
  46752. SineEase.prototype.easeInCore = function (gradient) {
  46753. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  46754. };
  46755. return SineEase;
  46756. }(EasingFunction));
  46757. BABYLON.SineEase = SineEase;
  46758. var BezierCurveEase = /** @class */ (function (_super) {
  46759. __extends(BezierCurveEase, _super);
  46760. function BezierCurveEase(x1, y1, x2, y2) {
  46761. if (x1 === void 0) { x1 = 0; }
  46762. if (y1 === void 0) { y1 = 0; }
  46763. if (x2 === void 0) { x2 = 1; }
  46764. if (y2 === void 0) { y2 = 1; }
  46765. var _this = _super.call(this) || this;
  46766. _this.x1 = x1;
  46767. _this.y1 = y1;
  46768. _this.x2 = x2;
  46769. _this.y2 = y2;
  46770. return _this;
  46771. }
  46772. BezierCurveEase.prototype.easeInCore = function (gradient) {
  46773. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  46774. };
  46775. return BezierCurveEase;
  46776. }(EasingFunction));
  46777. BABYLON.BezierCurveEase = BezierCurveEase;
  46778. })(BABYLON || (BABYLON = {}));
  46779. //# sourceMappingURL=babylon.easing.js.map
  46780. var BABYLON;
  46781. (function (BABYLON) {
  46782. var Condition = /** @class */ (function () {
  46783. function Condition(actionManager) {
  46784. this._actionManager = actionManager;
  46785. }
  46786. Condition.prototype.isValid = function () {
  46787. return true;
  46788. };
  46789. Condition.prototype._getProperty = function (propertyPath) {
  46790. return this._actionManager._getProperty(propertyPath);
  46791. };
  46792. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  46793. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46794. };
  46795. Condition.prototype.serialize = function () {
  46796. };
  46797. Condition.prototype._serialize = function (serializedCondition) {
  46798. return {
  46799. type: 2,
  46800. children: [],
  46801. name: serializedCondition.name,
  46802. properties: serializedCondition.properties
  46803. };
  46804. };
  46805. return Condition;
  46806. }());
  46807. BABYLON.Condition = Condition;
  46808. var ValueCondition = /** @class */ (function (_super) {
  46809. __extends(ValueCondition, _super);
  46810. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  46811. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  46812. var _this = _super.call(this, actionManager) || this;
  46813. _this.propertyPath = propertyPath;
  46814. _this.value = value;
  46815. _this.operator = operator;
  46816. _this._target = target;
  46817. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  46818. _this._property = _this._getProperty(_this.propertyPath);
  46819. return _this;
  46820. }
  46821. Object.defineProperty(ValueCondition, "IsEqual", {
  46822. get: function () {
  46823. return ValueCondition._IsEqual;
  46824. },
  46825. enumerable: true,
  46826. configurable: true
  46827. });
  46828. Object.defineProperty(ValueCondition, "IsDifferent", {
  46829. get: function () {
  46830. return ValueCondition._IsDifferent;
  46831. },
  46832. enumerable: true,
  46833. configurable: true
  46834. });
  46835. Object.defineProperty(ValueCondition, "IsGreater", {
  46836. get: function () {
  46837. return ValueCondition._IsGreater;
  46838. },
  46839. enumerable: true,
  46840. configurable: true
  46841. });
  46842. Object.defineProperty(ValueCondition, "IsLesser", {
  46843. get: function () {
  46844. return ValueCondition._IsLesser;
  46845. },
  46846. enumerable: true,
  46847. configurable: true
  46848. });
  46849. // Methods
  46850. ValueCondition.prototype.isValid = function () {
  46851. switch (this.operator) {
  46852. case ValueCondition.IsGreater:
  46853. return this._effectiveTarget[this._property] > this.value;
  46854. case ValueCondition.IsLesser:
  46855. return this._effectiveTarget[this._property] < this.value;
  46856. case ValueCondition.IsEqual:
  46857. case ValueCondition.IsDifferent:
  46858. var check;
  46859. if (this.value.equals) {
  46860. check = this.value.equals(this._effectiveTarget[this._property]);
  46861. }
  46862. else {
  46863. check = this.value === this._effectiveTarget[this._property];
  46864. }
  46865. return this.operator === ValueCondition.IsEqual ? check : !check;
  46866. }
  46867. return false;
  46868. };
  46869. ValueCondition.prototype.serialize = function () {
  46870. return this._serialize({
  46871. name: "ValueCondition",
  46872. properties: [
  46873. BABYLON.Action._GetTargetProperty(this._target),
  46874. { name: "propertyPath", value: this.propertyPath },
  46875. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46876. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  46877. ]
  46878. });
  46879. };
  46880. ValueCondition.GetOperatorName = function (operator) {
  46881. switch (operator) {
  46882. case ValueCondition._IsEqual: return "IsEqual";
  46883. case ValueCondition._IsDifferent: return "IsDifferent";
  46884. case ValueCondition._IsGreater: return "IsGreater";
  46885. case ValueCondition._IsLesser: return "IsLesser";
  46886. default: return "";
  46887. }
  46888. };
  46889. // Statics
  46890. ValueCondition._IsEqual = 0;
  46891. ValueCondition._IsDifferent = 1;
  46892. ValueCondition._IsGreater = 2;
  46893. ValueCondition._IsLesser = 3;
  46894. return ValueCondition;
  46895. }(Condition));
  46896. BABYLON.ValueCondition = ValueCondition;
  46897. var PredicateCondition = /** @class */ (function (_super) {
  46898. __extends(PredicateCondition, _super);
  46899. function PredicateCondition(actionManager, predicate) {
  46900. var _this = _super.call(this, actionManager) || this;
  46901. _this.predicate = predicate;
  46902. return _this;
  46903. }
  46904. PredicateCondition.prototype.isValid = function () {
  46905. return this.predicate();
  46906. };
  46907. return PredicateCondition;
  46908. }(Condition));
  46909. BABYLON.PredicateCondition = PredicateCondition;
  46910. var StateCondition = /** @class */ (function (_super) {
  46911. __extends(StateCondition, _super);
  46912. function StateCondition(actionManager, target, value) {
  46913. var _this = _super.call(this, actionManager) || this;
  46914. _this.value = value;
  46915. _this._target = target;
  46916. return _this;
  46917. }
  46918. // Methods
  46919. StateCondition.prototype.isValid = function () {
  46920. return this._target.state === this.value;
  46921. };
  46922. StateCondition.prototype.serialize = function () {
  46923. return this._serialize({
  46924. name: "StateCondition",
  46925. properties: [
  46926. BABYLON.Action._GetTargetProperty(this._target),
  46927. { name: "value", value: this.value }
  46928. ]
  46929. });
  46930. };
  46931. return StateCondition;
  46932. }(Condition));
  46933. BABYLON.StateCondition = StateCondition;
  46934. })(BABYLON || (BABYLON = {}));
  46935. //# sourceMappingURL=babylon.condition.js.map
  46936. var BABYLON;
  46937. (function (BABYLON) {
  46938. var Action = /** @class */ (function () {
  46939. function Action(triggerOptions, condition) {
  46940. this.triggerOptions = triggerOptions;
  46941. this.onBeforeExecuteObservable = new BABYLON.Observable();
  46942. if (triggerOptions.parameter) {
  46943. this.trigger = triggerOptions.trigger;
  46944. this._triggerParameter = triggerOptions.parameter;
  46945. }
  46946. else {
  46947. this.trigger = triggerOptions;
  46948. }
  46949. this._nextActiveAction = this;
  46950. this._condition = condition;
  46951. }
  46952. // Methods
  46953. Action.prototype._prepare = function () {
  46954. };
  46955. Action.prototype.getTriggerParameter = function () {
  46956. return this._triggerParameter;
  46957. };
  46958. Action.prototype._executeCurrent = function (evt) {
  46959. if (this._nextActiveAction._condition) {
  46960. var condition = this._nextActiveAction._condition;
  46961. var currentRenderId = this._actionManager.getScene().getRenderId();
  46962. // We cache the current evaluation for the current frame
  46963. if (condition._evaluationId === currentRenderId) {
  46964. if (!condition._currentResult) {
  46965. return;
  46966. }
  46967. }
  46968. else {
  46969. condition._evaluationId = currentRenderId;
  46970. if (!condition.isValid()) {
  46971. condition._currentResult = false;
  46972. return;
  46973. }
  46974. condition._currentResult = true;
  46975. }
  46976. }
  46977. this.onBeforeExecuteObservable.notifyObservers(this);
  46978. this._nextActiveAction.execute(evt);
  46979. this.skipToNextActiveAction();
  46980. };
  46981. Action.prototype.execute = function (evt) {
  46982. };
  46983. Action.prototype.skipToNextActiveAction = function () {
  46984. if (this._nextActiveAction._child) {
  46985. if (!this._nextActiveAction._child._actionManager) {
  46986. this._nextActiveAction._child._actionManager = this._actionManager;
  46987. }
  46988. this._nextActiveAction = this._nextActiveAction._child;
  46989. }
  46990. else {
  46991. this._nextActiveAction = this;
  46992. }
  46993. };
  46994. Action.prototype.then = function (action) {
  46995. this._child = action;
  46996. action._actionManager = this._actionManager;
  46997. action._prepare();
  46998. return action;
  46999. };
  47000. Action.prototype._getProperty = function (propertyPath) {
  47001. return this._actionManager._getProperty(propertyPath);
  47002. };
  47003. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47004. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47005. };
  47006. Action.prototype.serialize = function (parent) {
  47007. };
  47008. // Called by BABYLON.Action objects in serialize(...). Internal use
  47009. Action.prototype._serialize = function (serializedAction, parent) {
  47010. var serializationObject = {
  47011. type: 1,
  47012. children: [],
  47013. name: serializedAction.name,
  47014. properties: serializedAction.properties || []
  47015. };
  47016. // Serialize child
  47017. if (this._child) {
  47018. this._child.serialize(serializationObject);
  47019. }
  47020. // Check if "this" has a condition
  47021. if (this._condition) {
  47022. var serializedCondition = this._condition.serialize();
  47023. serializedCondition.children.push(serializationObject);
  47024. if (parent) {
  47025. parent.children.push(serializedCondition);
  47026. }
  47027. return serializedCondition;
  47028. }
  47029. if (parent) {
  47030. parent.children.push(serializationObject);
  47031. }
  47032. return serializationObject;
  47033. };
  47034. Action._SerializeValueAsString = function (value) {
  47035. if (typeof value === "number") {
  47036. return value.toString();
  47037. }
  47038. if (typeof value === "boolean") {
  47039. return value ? "true" : "false";
  47040. }
  47041. if (value instanceof BABYLON.Vector2) {
  47042. return value.x + ", " + value.y;
  47043. }
  47044. if (value instanceof BABYLON.Vector3) {
  47045. return value.x + ", " + value.y + ", " + value.z;
  47046. }
  47047. if (value instanceof BABYLON.Color3) {
  47048. return value.r + ", " + value.g + ", " + value.b;
  47049. }
  47050. if (value instanceof BABYLON.Color4) {
  47051. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47052. }
  47053. return value; // string
  47054. };
  47055. Action._GetTargetProperty = function (target) {
  47056. return {
  47057. name: "target",
  47058. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47059. : target instanceof BABYLON.Light ? "LightProperties"
  47060. : target instanceof BABYLON.Camera ? "CameraProperties"
  47061. : "SceneProperties",
  47062. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47063. };
  47064. };
  47065. return Action;
  47066. }());
  47067. BABYLON.Action = Action;
  47068. })(BABYLON || (BABYLON = {}));
  47069. //# sourceMappingURL=babylon.action.js.map
  47070. var BABYLON;
  47071. (function (BABYLON) {
  47072. /**
  47073. * ActionEvent is the event beint sent when an action is triggered.
  47074. */
  47075. var ActionEvent = /** @class */ (function () {
  47076. /**
  47077. * @param source The mesh or sprite that triggered the action.
  47078. * @param pointerX The X mouse cursor position at the time of the event
  47079. * @param pointerY The Y mouse cursor position at the time of the event
  47080. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47081. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47082. */
  47083. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47084. this.source = source;
  47085. this.pointerX = pointerX;
  47086. this.pointerY = pointerY;
  47087. this.meshUnderPointer = meshUnderPointer;
  47088. this.sourceEvent = sourceEvent;
  47089. this.additionalData = additionalData;
  47090. }
  47091. /**
  47092. * Helper function to auto-create an ActionEvent from a source mesh.
  47093. * @param source The source mesh that triggered the event
  47094. * @param evt {Event} The original (browser) event
  47095. */
  47096. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47097. var scene = source.getScene();
  47098. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47099. };
  47100. /**
  47101. * Helper function to auto-create an ActionEvent from a source mesh.
  47102. * @param source The source sprite that triggered the event
  47103. * @param scene Scene associated with the sprite
  47104. * @param evt {Event} The original (browser) event
  47105. */
  47106. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47107. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47108. };
  47109. /**
  47110. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47111. * @param scene the scene where the event occurred
  47112. * @param evt {Event} The original (browser) event
  47113. */
  47114. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47115. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47116. };
  47117. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47118. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47119. };
  47120. return ActionEvent;
  47121. }());
  47122. BABYLON.ActionEvent = ActionEvent;
  47123. /**
  47124. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47125. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47126. */
  47127. var ActionManager = /** @class */ (function () {
  47128. function ActionManager(scene) {
  47129. // Members
  47130. this.actions = new Array();
  47131. this.hoverCursor = '';
  47132. this._scene = scene;
  47133. scene._actionManagers.push(this);
  47134. }
  47135. Object.defineProperty(ActionManager, "NothingTrigger", {
  47136. get: function () {
  47137. return ActionManager._NothingTrigger;
  47138. },
  47139. enumerable: true,
  47140. configurable: true
  47141. });
  47142. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47143. get: function () {
  47144. return ActionManager._OnPickTrigger;
  47145. },
  47146. enumerable: true,
  47147. configurable: true
  47148. });
  47149. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47150. get: function () {
  47151. return ActionManager._OnLeftPickTrigger;
  47152. },
  47153. enumerable: true,
  47154. configurable: true
  47155. });
  47156. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47157. get: function () {
  47158. return ActionManager._OnRightPickTrigger;
  47159. },
  47160. enumerable: true,
  47161. configurable: true
  47162. });
  47163. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47164. get: function () {
  47165. return ActionManager._OnCenterPickTrigger;
  47166. },
  47167. enumerable: true,
  47168. configurable: true
  47169. });
  47170. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47171. get: function () {
  47172. return ActionManager._OnPickDownTrigger;
  47173. },
  47174. enumerable: true,
  47175. configurable: true
  47176. });
  47177. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47178. get: function () {
  47179. return ActionManager._OnDoublePickTrigger;
  47180. },
  47181. enumerable: true,
  47182. configurable: true
  47183. });
  47184. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47185. get: function () {
  47186. return ActionManager._OnPickUpTrigger;
  47187. },
  47188. enumerable: true,
  47189. configurable: true
  47190. });
  47191. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47192. /// This trigger will only be raised if you also declared a OnPickDown
  47193. get: function () {
  47194. return ActionManager._OnPickOutTrigger;
  47195. },
  47196. enumerable: true,
  47197. configurable: true
  47198. });
  47199. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47200. get: function () {
  47201. return ActionManager._OnLongPressTrigger;
  47202. },
  47203. enumerable: true,
  47204. configurable: true
  47205. });
  47206. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47207. get: function () {
  47208. return ActionManager._OnPointerOverTrigger;
  47209. },
  47210. enumerable: true,
  47211. configurable: true
  47212. });
  47213. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47214. get: function () {
  47215. return ActionManager._OnPointerOutTrigger;
  47216. },
  47217. enumerable: true,
  47218. configurable: true
  47219. });
  47220. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47221. get: function () {
  47222. return ActionManager._OnEveryFrameTrigger;
  47223. },
  47224. enumerable: true,
  47225. configurable: true
  47226. });
  47227. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47228. get: function () {
  47229. return ActionManager._OnIntersectionEnterTrigger;
  47230. },
  47231. enumerable: true,
  47232. configurable: true
  47233. });
  47234. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47235. get: function () {
  47236. return ActionManager._OnIntersectionExitTrigger;
  47237. },
  47238. enumerable: true,
  47239. configurable: true
  47240. });
  47241. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47242. get: function () {
  47243. return ActionManager._OnKeyDownTrigger;
  47244. },
  47245. enumerable: true,
  47246. configurable: true
  47247. });
  47248. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47249. get: function () {
  47250. return ActionManager._OnKeyUpTrigger;
  47251. },
  47252. enumerable: true,
  47253. configurable: true
  47254. });
  47255. // Methods
  47256. ActionManager.prototype.dispose = function () {
  47257. var index = this._scene._actionManagers.indexOf(this);
  47258. for (var i = 0; i < this.actions.length; i++) {
  47259. var action = this.actions[i];
  47260. ActionManager.Triggers[action.trigger]--;
  47261. if (ActionManager.Triggers[action.trigger] === 0) {
  47262. delete ActionManager.Triggers[action.trigger];
  47263. }
  47264. }
  47265. if (index > -1) {
  47266. this._scene._actionManagers.splice(index, 1);
  47267. }
  47268. };
  47269. ActionManager.prototype.getScene = function () {
  47270. return this._scene;
  47271. };
  47272. /**
  47273. * Does this action manager handles actions of any of the given triggers
  47274. * @param {number[]} triggers - the triggers to be tested
  47275. * @return {boolean} whether one (or more) of the triggers is handeled
  47276. */
  47277. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47278. for (var index = 0; index < this.actions.length; index++) {
  47279. var action = this.actions[index];
  47280. if (triggers.indexOf(action.trigger) > -1) {
  47281. return true;
  47282. }
  47283. }
  47284. return false;
  47285. };
  47286. /**
  47287. * Does this action manager handles actions of a given trigger
  47288. * @param {number} trigger - the trigger to be tested
  47289. * @return {boolean} whether the trigger is handeled
  47290. */
  47291. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47292. for (var index = 0; index < this.actions.length; index++) {
  47293. var action = this.actions[index];
  47294. if (action.trigger === trigger) {
  47295. return true;
  47296. }
  47297. }
  47298. return false;
  47299. };
  47300. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47301. /**
  47302. * Does this action manager has pointer triggers
  47303. * @return {boolean} whether or not it has pointer triggers
  47304. */
  47305. get: function () {
  47306. for (var index = 0; index < this.actions.length; index++) {
  47307. var action = this.actions[index];
  47308. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47309. return true;
  47310. }
  47311. }
  47312. return false;
  47313. },
  47314. enumerable: true,
  47315. configurable: true
  47316. });
  47317. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47318. /**
  47319. * Does this action manager has pick triggers
  47320. * @return {boolean} whether or not it has pick triggers
  47321. */
  47322. get: function () {
  47323. for (var index = 0; index < this.actions.length; index++) {
  47324. var action = this.actions[index];
  47325. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47326. return true;
  47327. }
  47328. }
  47329. return false;
  47330. },
  47331. enumerable: true,
  47332. configurable: true
  47333. });
  47334. Object.defineProperty(ActionManager, "HasTriggers", {
  47335. /**
  47336. * Does exist one action manager with at least one trigger
  47337. * @return {boolean} whether or not it exists one action manager with one trigger
  47338. **/
  47339. get: function () {
  47340. for (var t in ActionManager.Triggers) {
  47341. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47342. return true;
  47343. }
  47344. }
  47345. return false;
  47346. },
  47347. enumerable: true,
  47348. configurable: true
  47349. });
  47350. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47351. /**
  47352. * Does exist one action manager with at least one pick trigger
  47353. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47354. **/
  47355. get: function () {
  47356. for (var t in ActionManager.Triggers) {
  47357. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47358. var t_int = parseInt(t);
  47359. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47360. return true;
  47361. }
  47362. }
  47363. }
  47364. return false;
  47365. },
  47366. enumerable: true,
  47367. configurable: true
  47368. });
  47369. /**
  47370. * Does exist one action manager that handles actions of a given trigger
  47371. * @param {number} trigger - the trigger to be tested
  47372. * @return {boolean} whether the trigger is handeled by at least one action manager
  47373. **/
  47374. ActionManager.HasSpecificTrigger = function (trigger) {
  47375. for (var t in ActionManager.Triggers) {
  47376. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47377. var t_int = parseInt(t);
  47378. if (t_int === trigger) {
  47379. return true;
  47380. }
  47381. }
  47382. }
  47383. return false;
  47384. };
  47385. /**
  47386. * Registers an action to this action manager
  47387. * @param {BABYLON.Action} action - the action to be registered
  47388. * @return {BABYLON.Action} the action amended (prepared) after registration
  47389. */
  47390. ActionManager.prototype.registerAction = function (action) {
  47391. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47392. if (this.getScene().actionManager !== this) {
  47393. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47394. return null;
  47395. }
  47396. }
  47397. this.actions.push(action);
  47398. if (ActionManager.Triggers[action.trigger]) {
  47399. ActionManager.Triggers[action.trigger]++;
  47400. }
  47401. else {
  47402. ActionManager.Triggers[action.trigger] = 1;
  47403. }
  47404. action._actionManager = this;
  47405. action._prepare();
  47406. return action;
  47407. };
  47408. /**
  47409. * Unregisters an action to this action manager
  47410. * @param action The action to be unregistered
  47411. * @return whether the action has been unregistered
  47412. */
  47413. ActionManager.prototype.unregisterAction = function (action) {
  47414. var index = this.actions.indexOf(action);
  47415. if (index !== -1) {
  47416. this.actions.splice(index, 1);
  47417. ActionManager.Triggers[action.trigger] -= 1;
  47418. if (ActionManager.Triggers[action.trigger] === 0) {
  47419. delete ActionManager.Triggers[action.trigger];
  47420. }
  47421. delete action._actionManager;
  47422. return true;
  47423. }
  47424. return false;
  47425. };
  47426. /**
  47427. * Process a specific trigger
  47428. * @param {number} trigger - the trigger to process
  47429. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47430. */
  47431. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47432. for (var index = 0; index < this.actions.length; index++) {
  47433. var action = this.actions[index];
  47434. if (action.trigger === trigger) {
  47435. if (evt) {
  47436. if (trigger === ActionManager.OnKeyUpTrigger
  47437. || trigger === ActionManager.OnKeyDownTrigger) {
  47438. var parameter = action.getTriggerParameter();
  47439. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47440. if (!parameter.toLowerCase) {
  47441. continue;
  47442. }
  47443. var lowerCase = parameter.toLowerCase();
  47444. if (lowerCase !== evt.sourceEvent.key) {
  47445. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47446. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47447. if (actualkey !== lowerCase) {
  47448. continue;
  47449. }
  47450. }
  47451. }
  47452. }
  47453. }
  47454. action._executeCurrent(evt);
  47455. }
  47456. }
  47457. };
  47458. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47459. var properties = propertyPath.split(".");
  47460. for (var index = 0; index < properties.length - 1; index++) {
  47461. target = target[properties[index]];
  47462. }
  47463. return target;
  47464. };
  47465. ActionManager.prototype._getProperty = function (propertyPath) {
  47466. var properties = propertyPath.split(".");
  47467. return properties[properties.length - 1];
  47468. };
  47469. ActionManager.prototype.serialize = function (name) {
  47470. var root = {
  47471. children: new Array(),
  47472. name: name,
  47473. type: 3,
  47474. properties: new Array() // Empty for root but required
  47475. };
  47476. for (var i = 0; i < this.actions.length; i++) {
  47477. var triggerObject = {
  47478. type: 0,
  47479. children: new Array(),
  47480. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47481. properties: new Array()
  47482. };
  47483. var triggerOptions = this.actions[i].triggerOptions;
  47484. if (triggerOptions && typeof triggerOptions !== "number") {
  47485. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47486. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47487. }
  47488. else {
  47489. var parameter = {};
  47490. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47491. if (triggerOptions.parameter.mesh) {
  47492. parameter._meshId = triggerOptions.parameter.mesh.id;
  47493. }
  47494. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47495. }
  47496. }
  47497. // Serialize child action, recursively
  47498. this.actions[i].serialize(triggerObject);
  47499. // Add serialized trigger
  47500. root.children.push(triggerObject);
  47501. }
  47502. return root;
  47503. };
  47504. ActionManager.Parse = function (parsedActions, object, scene) {
  47505. var actionManager = new ActionManager(scene);
  47506. if (object === null)
  47507. scene.actionManager = actionManager;
  47508. else
  47509. object.actionManager = actionManager;
  47510. // instanciate a new object
  47511. var instanciate = function (name, params) {
  47512. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47513. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47514. newInstance.constructor.apply(newInstance, params);
  47515. return newInstance;
  47516. };
  47517. var parseParameter = function (name, value, target, propertyPath) {
  47518. if (propertyPath === null) {
  47519. // String, boolean or float
  47520. var floatValue = parseFloat(value);
  47521. if (value === "true" || value === "false")
  47522. return value === "true";
  47523. else
  47524. return isNaN(floatValue) ? value : floatValue;
  47525. }
  47526. var effectiveTarget = propertyPath.split(".");
  47527. var values = value.split(",");
  47528. // Get effective Target
  47529. for (var i = 0; i < effectiveTarget.length; i++) {
  47530. target = target[effectiveTarget[i]];
  47531. }
  47532. // Return appropriate value with its type
  47533. if (typeof (target) === "boolean")
  47534. return values[0] === "true";
  47535. if (typeof (target) === "string")
  47536. return values[0];
  47537. // Parameters with multiple values such as Vector3 etc.
  47538. var split = new Array();
  47539. for (var i = 0; i < values.length; i++)
  47540. split.push(parseFloat(values[i]));
  47541. if (target instanceof BABYLON.Vector3)
  47542. return BABYLON.Vector3.FromArray(split);
  47543. if (target instanceof BABYLON.Vector4)
  47544. return BABYLON.Vector4.FromArray(split);
  47545. if (target instanceof BABYLON.Color3)
  47546. return BABYLON.Color3.FromArray(split);
  47547. if (target instanceof BABYLON.Color4)
  47548. return BABYLON.Color4.FromArray(split);
  47549. return parseFloat(values[0]);
  47550. };
  47551. // traverse graph per trigger
  47552. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47553. if (combineArray === void 0) { combineArray = null; }
  47554. if (parsedAction.detached)
  47555. return;
  47556. var parameters = new Array();
  47557. var target = null;
  47558. var propertyPath = null;
  47559. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47560. // Parameters
  47561. if (parsedAction.type === 2)
  47562. parameters.push(actionManager);
  47563. else
  47564. parameters.push(trigger);
  47565. if (combine) {
  47566. var actions = new Array();
  47567. for (var j = 0; j < parsedAction.combine.length; j++) {
  47568. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47569. }
  47570. parameters.push(actions);
  47571. }
  47572. else {
  47573. for (var i = 0; i < parsedAction.properties.length; i++) {
  47574. var value = parsedAction.properties[i].value;
  47575. var name = parsedAction.properties[i].name;
  47576. var targetType = parsedAction.properties[i].targetType;
  47577. if (name === "target")
  47578. if (targetType !== null && targetType === "SceneProperties")
  47579. value = target = scene;
  47580. else
  47581. value = target = scene.getNodeByName(value);
  47582. else if (name === "parent")
  47583. value = scene.getNodeByName(value);
  47584. else if (name === "sound")
  47585. value = scene.getSoundByName(value);
  47586. else if (name !== "propertyPath") {
  47587. if (parsedAction.type === 2 && name === "operator")
  47588. value = BABYLON.ValueCondition[value];
  47589. else
  47590. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47591. }
  47592. else {
  47593. propertyPath = value;
  47594. }
  47595. parameters.push(value);
  47596. }
  47597. }
  47598. if (combineArray === null) {
  47599. parameters.push(condition);
  47600. }
  47601. else {
  47602. parameters.push(null);
  47603. }
  47604. // If interpolate value action
  47605. if (parsedAction.name === "InterpolateValueAction") {
  47606. var param = parameters[parameters.length - 2];
  47607. parameters[parameters.length - 1] = param;
  47608. parameters[parameters.length - 2] = condition;
  47609. }
  47610. // Action or condition(s) and not CombineAction
  47611. var newAction = instanciate(parsedAction.name, parameters);
  47612. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47613. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47614. if (action)
  47615. action.then(nothing);
  47616. else
  47617. actionManager.registerAction(nothing);
  47618. action = nothing;
  47619. }
  47620. if (combineArray === null) {
  47621. if (newAction instanceof BABYLON.Condition) {
  47622. condition = newAction;
  47623. newAction = action;
  47624. }
  47625. else {
  47626. condition = null;
  47627. if (action)
  47628. action.then(newAction);
  47629. else
  47630. actionManager.registerAction(newAction);
  47631. }
  47632. }
  47633. else {
  47634. combineArray.push(newAction);
  47635. }
  47636. for (var i = 0; i < parsedAction.children.length; i++)
  47637. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47638. };
  47639. // triggers
  47640. for (var i = 0; i < parsedActions.children.length; i++) {
  47641. var triggerParams;
  47642. var trigger = parsedActions.children[i];
  47643. if (trigger.properties.length > 0) {
  47644. var param = trigger.properties[0].value;
  47645. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  47646. if (value._meshId) {
  47647. value.mesh = scene.getMeshByID(value._meshId);
  47648. }
  47649. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  47650. }
  47651. else
  47652. triggerParams = ActionManager[trigger.name];
  47653. for (var j = 0; j < trigger.children.length; j++) {
  47654. if (!trigger.detached)
  47655. traverse(trigger.children[j], triggerParams, null, null);
  47656. }
  47657. }
  47658. };
  47659. ActionManager.GetTriggerName = function (trigger) {
  47660. switch (trigger) {
  47661. case 0: return "NothingTrigger";
  47662. case 1: return "OnPickTrigger";
  47663. case 2: return "OnLeftPickTrigger";
  47664. case 3: return "OnRightPickTrigger";
  47665. case 4: return "OnCenterPickTrigger";
  47666. case 5: return "OnPickDownTrigger";
  47667. case 6: return "OnPickUpTrigger";
  47668. case 7: return "OnLongPressTrigger";
  47669. case 8: return "OnPointerOverTrigger";
  47670. case 9: return "OnPointerOutTrigger";
  47671. case 10: return "OnEveryFrameTrigger";
  47672. case 11: return "OnIntersectionEnterTrigger";
  47673. case 12: return "OnIntersectionExitTrigger";
  47674. case 13: return "OnKeyDownTrigger";
  47675. case 14: return "OnKeyUpTrigger";
  47676. case 15: return "OnPickOutTrigger";
  47677. default: return "";
  47678. }
  47679. };
  47680. // Statics
  47681. ActionManager._NothingTrigger = 0;
  47682. ActionManager._OnPickTrigger = 1;
  47683. ActionManager._OnLeftPickTrigger = 2;
  47684. ActionManager._OnRightPickTrigger = 3;
  47685. ActionManager._OnCenterPickTrigger = 4;
  47686. ActionManager._OnPickDownTrigger = 5;
  47687. ActionManager._OnDoublePickTrigger = 6;
  47688. ActionManager._OnPickUpTrigger = 7;
  47689. ActionManager._OnLongPressTrigger = 8;
  47690. ActionManager._OnPointerOverTrigger = 9;
  47691. ActionManager._OnPointerOutTrigger = 10;
  47692. ActionManager._OnEveryFrameTrigger = 11;
  47693. ActionManager._OnIntersectionEnterTrigger = 12;
  47694. ActionManager._OnIntersectionExitTrigger = 13;
  47695. ActionManager._OnKeyDownTrigger = 14;
  47696. ActionManager._OnKeyUpTrigger = 15;
  47697. ActionManager._OnPickOutTrigger = 16;
  47698. ActionManager.Triggers = {};
  47699. return ActionManager;
  47700. }());
  47701. BABYLON.ActionManager = ActionManager;
  47702. })(BABYLON || (BABYLON = {}));
  47703. //# sourceMappingURL=babylon.actionManager.js.map
  47704. var BABYLON;
  47705. (function (BABYLON) {
  47706. var InterpolateValueAction = /** @class */ (function (_super) {
  47707. __extends(InterpolateValueAction, _super);
  47708. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  47709. if (duration === void 0) { duration = 1000; }
  47710. var _this = _super.call(this, triggerOptions, condition) || this;
  47711. _this.propertyPath = propertyPath;
  47712. _this.value = value;
  47713. _this.duration = duration;
  47714. _this.stopOtherAnimations = stopOtherAnimations;
  47715. _this.onInterpolationDone = onInterpolationDone;
  47716. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  47717. _this._target = _this._effectiveTarget = target;
  47718. return _this;
  47719. }
  47720. InterpolateValueAction.prototype._prepare = function () {
  47721. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47722. this._property = this._getProperty(this.propertyPath);
  47723. };
  47724. InterpolateValueAction.prototype.execute = function () {
  47725. var _this = this;
  47726. var scene = this._actionManager.getScene();
  47727. var keys = [
  47728. {
  47729. frame: 0,
  47730. value: this._effectiveTarget[this._property]
  47731. }, {
  47732. frame: 100,
  47733. value: this.value
  47734. }
  47735. ];
  47736. var dataType;
  47737. if (typeof this.value === "number") {
  47738. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  47739. }
  47740. else if (this.value instanceof BABYLON.Color3) {
  47741. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  47742. }
  47743. else if (this.value instanceof BABYLON.Vector3) {
  47744. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  47745. }
  47746. else if (this.value instanceof BABYLON.Matrix) {
  47747. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  47748. }
  47749. else if (this.value instanceof BABYLON.Quaternion) {
  47750. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  47751. }
  47752. else {
  47753. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  47754. return;
  47755. }
  47756. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  47757. animation.setKeys(keys);
  47758. if (this.stopOtherAnimations) {
  47759. scene.stopAnimation(this._effectiveTarget);
  47760. }
  47761. var wrapper = function () {
  47762. _this.onInterpolationDoneObservable.notifyObservers(_this);
  47763. if (_this.onInterpolationDone) {
  47764. _this.onInterpolationDone();
  47765. }
  47766. };
  47767. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  47768. };
  47769. InterpolateValueAction.prototype.serialize = function (parent) {
  47770. return _super.prototype._serialize.call(this, {
  47771. name: "InterpolateValueAction",
  47772. properties: [
  47773. BABYLON.Action._GetTargetProperty(this._target),
  47774. { name: "propertyPath", value: this.propertyPath },
  47775. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47776. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  47777. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  47778. ]
  47779. }, parent);
  47780. };
  47781. return InterpolateValueAction;
  47782. }(BABYLON.Action));
  47783. BABYLON.InterpolateValueAction = InterpolateValueAction;
  47784. })(BABYLON || (BABYLON = {}));
  47785. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  47786. var BABYLON;
  47787. (function (BABYLON) {
  47788. var SwitchBooleanAction = /** @class */ (function (_super) {
  47789. __extends(SwitchBooleanAction, _super);
  47790. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  47791. var _this = _super.call(this, triggerOptions, condition) || this;
  47792. _this.propertyPath = propertyPath;
  47793. _this._target = _this._effectiveTarget = target;
  47794. return _this;
  47795. }
  47796. SwitchBooleanAction.prototype._prepare = function () {
  47797. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47798. this._property = this._getProperty(this.propertyPath);
  47799. };
  47800. SwitchBooleanAction.prototype.execute = function () {
  47801. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  47802. };
  47803. SwitchBooleanAction.prototype.serialize = function (parent) {
  47804. return _super.prototype._serialize.call(this, {
  47805. name: "SwitchBooleanAction",
  47806. properties: [
  47807. BABYLON.Action._GetTargetProperty(this._target),
  47808. { name: "propertyPath", value: this.propertyPath }
  47809. ]
  47810. }, parent);
  47811. };
  47812. return SwitchBooleanAction;
  47813. }(BABYLON.Action));
  47814. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  47815. var SetStateAction = /** @class */ (function (_super) {
  47816. __extends(SetStateAction, _super);
  47817. function SetStateAction(triggerOptions, target, value, condition) {
  47818. var _this = _super.call(this, triggerOptions, condition) || this;
  47819. _this.value = value;
  47820. _this._target = target;
  47821. return _this;
  47822. }
  47823. SetStateAction.prototype.execute = function () {
  47824. this._target.state = this.value;
  47825. };
  47826. SetStateAction.prototype.serialize = function (parent) {
  47827. return _super.prototype._serialize.call(this, {
  47828. name: "SetStateAction",
  47829. properties: [
  47830. BABYLON.Action._GetTargetProperty(this._target),
  47831. { name: "value", value: this.value }
  47832. ]
  47833. }, parent);
  47834. };
  47835. return SetStateAction;
  47836. }(BABYLON.Action));
  47837. BABYLON.SetStateAction = SetStateAction;
  47838. var SetValueAction = /** @class */ (function (_super) {
  47839. __extends(SetValueAction, _super);
  47840. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  47841. var _this = _super.call(this, triggerOptions, condition) || this;
  47842. _this.propertyPath = propertyPath;
  47843. _this.value = value;
  47844. _this._target = _this._effectiveTarget = target;
  47845. return _this;
  47846. }
  47847. SetValueAction.prototype._prepare = function () {
  47848. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47849. this._property = this._getProperty(this.propertyPath);
  47850. };
  47851. SetValueAction.prototype.execute = function () {
  47852. this._effectiveTarget[this._property] = this.value;
  47853. if (this._target.markAsDirty) {
  47854. this._target.markAsDirty(this._property);
  47855. }
  47856. };
  47857. SetValueAction.prototype.serialize = function (parent) {
  47858. return _super.prototype._serialize.call(this, {
  47859. name: "SetValueAction",
  47860. properties: [
  47861. BABYLON.Action._GetTargetProperty(this._target),
  47862. { name: "propertyPath", value: this.propertyPath },
  47863. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47864. ]
  47865. }, parent);
  47866. };
  47867. return SetValueAction;
  47868. }(BABYLON.Action));
  47869. BABYLON.SetValueAction = SetValueAction;
  47870. var IncrementValueAction = /** @class */ (function (_super) {
  47871. __extends(IncrementValueAction, _super);
  47872. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  47873. var _this = _super.call(this, triggerOptions, condition) || this;
  47874. _this.propertyPath = propertyPath;
  47875. _this.value = value;
  47876. _this._target = _this._effectiveTarget = target;
  47877. return _this;
  47878. }
  47879. IncrementValueAction.prototype._prepare = function () {
  47880. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47881. this._property = this._getProperty(this.propertyPath);
  47882. if (typeof this._effectiveTarget[this._property] !== "number") {
  47883. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  47884. }
  47885. };
  47886. IncrementValueAction.prototype.execute = function () {
  47887. this._effectiveTarget[this._property] += this.value;
  47888. if (this._target.markAsDirty) {
  47889. this._target.markAsDirty(this._property);
  47890. }
  47891. };
  47892. IncrementValueAction.prototype.serialize = function (parent) {
  47893. return _super.prototype._serialize.call(this, {
  47894. name: "IncrementValueAction",
  47895. properties: [
  47896. BABYLON.Action._GetTargetProperty(this._target),
  47897. { name: "propertyPath", value: this.propertyPath },
  47898. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47899. ]
  47900. }, parent);
  47901. };
  47902. return IncrementValueAction;
  47903. }(BABYLON.Action));
  47904. BABYLON.IncrementValueAction = IncrementValueAction;
  47905. var PlayAnimationAction = /** @class */ (function (_super) {
  47906. __extends(PlayAnimationAction, _super);
  47907. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  47908. var _this = _super.call(this, triggerOptions, condition) || this;
  47909. _this.from = from;
  47910. _this.to = to;
  47911. _this.loop = loop;
  47912. _this._target = target;
  47913. return _this;
  47914. }
  47915. PlayAnimationAction.prototype._prepare = function () {
  47916. };
  47917. PlayAnimationAction.prototype.execute = function () {
  47918. var scene = this._actionManager.getScene();
  47919. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  47920. };
  47921. PlayAnimationAction.prototype.serialize = function (parent) {
  47922. return _super.prototype._serialize.call(this, {
  47923. name: "PlayAnimationAction",
  47924. properties: [
  47925. BABYLON.Action._GetTargetProperty(this._target),
  47926. { name: "from", value: String(this.from) },
  47927. { name: "to", value: String(this.to) },
  47928. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  47929. ]
  47930. }, parent);
  47931. };
  47932. return PlayAnimationAction;
  47933. }(BABYLON.Action));
  47934. BABYLON.PlayAnimationAction = PlayAnimationAction;
  47935. var StopAnimationAction = /** @class */ (function (_super) {
  47936. __extends(StopAnimationAction, _super);
  47937. function StopAnimationAction(triggerOptions, target, condition) {
  47938. var _this = _super.call(this, triggerOptions, condition) || this;
  47939. _this._target = target;
  47940. return _this;
  47941. }
  47942. StopAnimationAction.prototype._prepare = function () {
  47943. };
  47944. StopAnimationAction.prototype.execute = function () {
  47945. var scene = this._actionManager.getScene();
  47946. scene.stopAnimation(this._target);
  47947. };
  47948. StopAnimationAction.prototype.serialize = function (parent) {
  47949. return _super.prototype._serialize.call(this, {
  47950. name: "StopAnimationAction",
  47951. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  47952. }, parent);
  47953. };
  47954. return StopAnimationAction;
  47955. }(BABYLON.Action));
  47956. BABYLON.StopAnimationAction = StopAnimationAction;
  47957. var DoNothingAction = /** @class */ (function (_super) {
  47958. __extends(DoNothingAction, _super);
  47959. function DoNothingAction(triggerOptions, condition) {
  47960. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  47961. return _super.call(this, triggerOptions, condition) || this;
  47962. }
  47963. DoNothingAction.prototype.execute = function () {
  47964. };
  47965. DoNothingAction.prototype.serialize = function (parent) {
  47966. return _super.prototype._serialize.call(this, {
  47967. name: "DoNothingAction",
  47968. properties: []
  47969. }, parent);
  47970. };
  47971. return DoNothingAction;
  47972. }(BABYLON.Action));
  47973. BABYLON.DoNothingAction = DoNothingAction;
  47974. var CombineAction = /** @class */ (function (_super) {
  47975. __extends(CombineAction, _super);
  47976. function CombineAction(triggerOptions, children, condition) {
  47977. var _this = _super.call(this, triggerOptions, condition) || this;
  47978. _this.children = children;
  47979. return _this;
  47980. }
  47981. CombineAction.prototype._prepare = function () {
  47982. for (var index = 0; index < this.children.length; index++) {
  47983. this.children[index]._actionManager = this._actionManager;
  47984. this.children[index]._prepare();
  47985. }
  47986. };
  47987. CombineAction.prototype.execute = function (evt) {
  47988. for (var index = 0; index < this.children.length; index++) {
  47989. this.children[index].execute(evt);
  47990. }
  47991. };
  47992. CombineAction.prototype.serialize = function (parent) {
  47993. var serializationObject = _super.prototype._serialize.call(this, {
  47994. name: "CombineAction",
  47995. properties: [],
  47996. combine: []
  47997. }, parent);
  47998. for (var i = 0; i < this.children.length; i++) {
  47999. serializationObject.combine.push(this.children[i].serialize(null));
  48000. }
  48001. return serializationObject;
  48002. };
  48003. return CombineAction;
  48004. }(BABYLON.Action));
  48005. BABYLON.CombineAction = CombineAction;
  48006. var ExecuteCodeAction = /** @class */ (function (_super) {
  48007. __extends(ExecuteCodeAction, _super);
  48008. function ExecuteCodeAction(triggerOptions, func, condition) {
  48009. var _this = _super.call(this, triggerOptions, condition) || this;
  48010. _this.func = func;
  48011. return _this;
  48012. }
  48013. ExecuteCodeAction.prototype.execute = function (evt) {
  48014. this.func(evt);
  48015. };
  48016. return ExecuteCodeAction;
  48017. }(BABYLON.Action));
  48018. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48019. var SetParentAction = /** @class */ (function (_super) {
  48020. __extends(SetParentAction, _super);
  48021. function SetParentAction(triggerOptions, target, parent, condition) {
  48022. var _this = _super.call(this, triggerOptions, condition) || this;
  48023. _this._target = target;
  48024. _this._parent = parent;
  48025. return _this;
  48026. }
  48027. SetParentAction.prototype._prepare = function () {
  48028. };
  48029. SetParentAction.prototype.execute = function () {
  48030. if (this._target.parent === this._parent) {
  48031. return;
  48032. }
  48033. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48034. invertParentWorldMatrix.invert();
  48035. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48036. this._target.parent = this._parent;
  48037. };
  48038. SetParentAction.prototype.serialize = function (parent) {
  48039. return _super.prototype._serialize.call(this, {
  48040. name: "SetParentAction",
  48041. properties: [
  48042. BABYLON.Action._GetTargetProperty(this._target),
  48043. BABYLON.Action._GetTargetProperty(this._parent),
  48044. ]
  48045. }, parent);
  48046. };
  48047. return SetParentAction;
  48048. }(BABYLON.Action));
  48049. BABYLON.SetParentAction = SetParentAction;
  48050. var PlaySoundAction = /** @class */ (function (_super) {
  48051. __extends(PlaySoundAction, _super);
  48052. function PlaySoundAction(triggerOptions, sound, condition) {
  48053. var _this = _super.call(this, triggerOptions, condition) || this;
  48054. _this._sound = sound;
  48055. return _this;
  48056. }
  48057. PlaySoundAction.prototype._prepare = function () {
  48058. };
  48059. PlaySoundAction.prototype.execute = function () {
  48060. if (this._sound !== undefined)
  48061. this._sound.play();
  48062. };
  48063. PlaySoundAction.prototype.serialize = function (parent) {
  48064. return _super.prototype._serialize.call(this, {
  48065. name: "PlaySoundAction",
  48066. properties: [{ name: "sound", value: this._sound.name }]
  48067. }, parent);
  48068. };
  48069. return PlaySoundAction;
  48070. }(BABYLON.Action));
  48071. BABYLON.PlaySoundAction = PlaySoundAction;
  48072. var StopSoundAction = /** @class */ (function (_super) {
  48073. __extends(StopSoundAction, _super);
  48074. function StopSoundAction(triggerOptions, sound, condition) {
  48075. var _this = _super.call(this, triggerOptions, condition) || this;
  48076. _this._sound = sound;
  48077. return _this;
  48078. }
  48079. StopSoundAction.prototype._prepare = function () {
  48080. };
  48081. StopSoundAction.prototype.execute = function () {
  48082. if (this._sound !== undefined)
  48083. this._sound.stop();
  48084. };
  48085. StopSoundAction.prototype.serialize = function (parent) {
  48086. return _super.prototype._serialize.call(this, {
  48087. name: "StopSoundAction",
  48088. properties: [{ name: "sound", value: this._sound.name }]
  48089. }, parent);
  48090. };
  48091. return StopSoundAction;
  48092. }(BABYLON.Action));
  48093. BABYLON.StopSoundAction = StopSoundAction;
  48094. })(BABYLON || (BABYLON = {}));
  48095. //# sourceMappingURL=babylon.directActions.js.map
  48096. var BABYLON;
  48097. (function (BABYLON) {
  48098. var SpriteManager = /** @class */ (function () {
  48099. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48100. if (epsilon === void 0) { epsilon = 0.01; }
  48101. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48102. this.name = name;
  48103. this.sprites = new Array();
  48104. this.renderingGroupId = 0;
  48105. this.layerMask = 0x0FFFFFFF;
  48106. this.fogEnabled = true;
  48107. this.isPickable = false;
  48108. /**
  48109. * An event triggered when the manager is disposed.
  48110. * @type {BABYLON.Observable}
  48111. */
  48112. this.onDisposeObservable = new BABYLON.Observable();
  48113. this._vertexBuffers = {};
  48114. this._capacity = capacity;
  48115. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48116. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48117. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48118. if (cellSize.width && cellSize.height) {
  48119. this.cellWidth = cellSize.width;
  48120. this.cellHeight = cellSize.height;
  48121. }
  48122. else if (cellSize !== undefined) {
  48123. this.cellWidth = cellSize;
  48124. this.cellHeight = cellSize;
  48125. }
  48126. else {
  48127. return;
  48128. }
  48129. this._epsilon = epsilon;
  48130. this._scene = scene;
  48131. this._scene.spriteManagers.push(this);
  48132. var indices = [];
  48133. var index = 0;
  48134. for (var count = 0; count < capacity; count++) {
  48135. indices.push(index);
  48136. indices.push(index + 1);
  48137. indices.push(index + 2);
  48138. indices.push(index);
  48139. indices.push(index + 2);
  48140. indices.push(index + 3);
  48141. index += 4;
  48142. }
  48143. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48144. // VBO
  48145. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48146. this._vertexData = new Float32Array(capacity * 16 * 4);
  48147. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48148. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48149. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48150. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48151. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48152. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48153. this._vertexBuffers["options"] = options;
  48154. this._vertexBuffers["cellInfo"] = cellInfo;
  48155. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48156. // Effects
  48157. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48158. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48159. }
  48160. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48161. set: function (callback) {
  48162. if (this._onDisposeObserver) {
  48163. this.onDisposeObservable.remove(this._onDisposeObserver);
  48164. }
  48165. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48166. },
  48167. enumerable: true,
  48168. configurable: true
  48169. });
  48170. Object.defineProperty(SpriteManager.prototype, "texture", {
  48171. get: function () {
  48172. return this._spriteTexture;
  48173. },
  48174. set: function (value) {
  48175. this._spriteTexture = value;
  48176. },
  48177. enumerable: true,
  48178. configurable: true
  48179. });
  48180. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48181. var arrayOffset = index * 16;
  48182. if (offsetX === 0)
  48183. offsetX = this._epsilon;
  48184. else if (offsetX === 1)
  48185. offsetX = 1 - this._epsilon;
  48186. if (offsetY === 0)
  48187. offsetY = this._epsilon;
  48188. else if (offsetY === 1)
  48189. offsetY = 1 - this._epsilon;
  48190. this._vertexData[arrayOffset] = sprite.position.x;
  48191. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48192. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48193. this._vertexData[arrayOffset + 3] = sprite.angle;
  48194. this._vertexData[arrayOffset + 4] = sprite.width;
  48195. this._vertexData[arrayOffset + 5] = sprite.height;
  48196. this._vertexData[arrayOffset + 6] = offsetX;
  48197. this._vertexData[arrayOffset + 7] = offsetY;
  48198. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48199. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48200. var offset = (sprite.cellIndex / rowSize) >> 0;
  48201. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48202. this._vertexData[arrayOffset + 11] = offset;
  48203. // Color
  48204. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48205. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48206. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48207. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48208. };
  48209. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48210. var count = Math.min(this._capacity, this.sprites.length);
  48211. var min = BABYLON.Vector3.Zero();
  48212. var max = BABYLON.Vector3.Zero();
  48213. var distance = Number.MAX_VALUE;
  48214. var currentSprite = null;
  48215. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48216. var cameraView = camera.getViewMatrix();
  48217. for (var index = 0; index < count; index++) {
  48218. var sprite = this.sprites[index];
  48219. if (!sprite) {
  48220. continue;
  48221. }
  48222. if (predicate) {
  48223. if (!predicate(sprite)) {
  48224. continue;
  48225. }
  48226. }
  48227. else if (!sprite.isPickable) {
  48228. continue;
  48229. }
  48230. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48231. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48232. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48233. if (ray.intersectsBoxMinMax(min, max)) {
  48234. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48235. if (distance > currentDistance) {
  48236. distance = currentDistance;
  48237. currentSprite = sprite;
  48238. if (fastCheck) {
  48239. break;
  48240. }
  48241. }
  48242. }
  48243. }
  48244. if (currentSprite) {
  48245. var result = new BABYLON.PickingInfo();
  48246. result.hit = true;
  48247. result.pickedSprite = currentSprite;
  48248. result.distance = distance;
  48249. return result;
  48250. }
  48251. return null;
  48252. };
  48253. SpriteManager.prototype.render = function () {
  48254. // Check
  48255. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48256. return;
  48257. var engine = this._scene.getEngine();
  48258. var baseSize = this._spriteTexture.getBaseSize();
  48259. // Sprites
  48260. var deltaTime = engine.getDeltaTime();
  48261. var max = Math.min(this._capacity, this.sprites.length);
  48262. var rowSize = baseSize.width / this.cellWidth;
  48263. var offset = 0;
  48264. for (var index = 0; index < max; index++) {
  48265. var sprite = this.sprites[index];
  48266. if (!sprite) {
  48267. continue;
  48268. }
  48269. sprite._animate(deltaTime);
  48270. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48271. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48272. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48273. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48274. }
  48275. this._buffer.update(this._vertexData);
  48276. // Render
  48277. var effect = this._effectBase;
  48278. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48279. effect = this._effectFog;
  48280. }
  48281. engine.enableEffect(effect);
  48282. var viewMatrix = this._scene.getViewMatrix();
  48283. effect.setTexture("diffuseSampler", this._spriteTexture);
  48284. effect.setMatrix("view", viewMatrix);
  48285. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48286. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48287. // Fog
  48288. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48289. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48290. effect.setColor3("vFogColor", this._scene.fogColor);
  48291. }
  48292. // VBOs
  48293. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48294. // Draw order
  48295. engine.setDepthFunctionToLessOrEqual();
  48296. effect.setBool("alphaTest", true);
  48297. engine.setColorWrite(false);
  48298. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48299. engine.setColorWrite(true);
  48300. effect.setBool("alphaTest", false);
  48301. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48302. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48303. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48304. };
  48305. SpriteManager.prototype.dispose = function () {
  48306. if (this._buffer) {
  48307. this._buffer.dispose();
  48308. this._buffer = null;
  48309. }
  48310. if (this._indexBuffer) {
  48311. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48312. this._indexBuffer = null;
  48313. }
  48314. if (this._spriteTexture) {
  48315. this._spriteTexture.dispose();
  48316. this._spriteTexture = null;
  48317. }
  48318. // Remove from scene
  48319. var index = this._scene.spriteManagers.indexOf(this);
  48320. this._scene.spriteManagers.splice(index, 1);
  48321. // Callback
  48322. this.onDisposeObservable.notifyObservers(this);
  48323. this.onDisposeObservable.clear();
  48324. };
  48325. return SpriteManager;
  48326. }());
  48327. BABYLON.SpriteManager = SpriteManager;
  48328. })(BABYLON || (BABYLON = {}));
  48329. //# sourceMappingURL=babylon.spriteManager.js.map
  48330. var BABYLON;
  48331. (function (BABYLON) {
  48332. var Sprite = /** @class */ (function () {
  48333. function Sprite(name, manager) {
  48334. this.name = name;
  48335. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48336. this.width = 1.0;
  48337. this.height = 1.0;
  48338. this.angle = 0;
  48339. this.cellIndex = 0;
  48340. this.invertU = 0;
  48341. this.invertV = 0;
  48342. this.animations = new Array();
  48343. this.isPickable = false;
  48344. this._animationStarted = false;
  48345. this._loopAnimation = false;
  48346. this._fromIndex = 0;
  48347. this._toIndex = 0;
  48348. this._delay = 0;
  48349. this._direction = 1;
  48350. this._time = 0;
  48351. this._manager = manager;
  48352. this._manager.sprites.push(this);
  48353. this.position = BABYLON.Vector3.Zero();
  48354. }
  48355. Object.defineProperty(Sprite.prototype, "size", {
  48356. get: function () {
  48357. return this.width;
  48358. },
  48359. set: function (value) {
  48360. this.width = value;
  48361. this.height = value;
  48362. },
  48363. enumerable: true,
  48364. configurable: true
  48365. });
  48366. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48367. this._fromIndex = from;
  48368. this._toIndex = to;
  48369. this._loopAnimation = loop;
  48370. this._delay = delay;
  48371. this._animationStarted = true;
  48372. this._direction = from < to ? 1 : -1;
  48373. this.cellIndex = from;
  48374. this._time = 0;
  48375. this._onAnimationEnd = onAnimationEnd;
  48376. };
  48377. Sprite.prototype.stopAnimation = function () {
  48378. this._animationStarted = false;
  48379. };
  48380. Sprite.prototype._animate = function (deltaTime) {
  48381. if (!this._animationStarted)
  48382. return;
  48383. this._time += deltaTime;
  48384. if (this._time > this._delay) {
  48385. this._time = this._time % this._delay;
  48386. this.cellIndex += this._direction;
  48387. if (this.cellIndex > this._toIndex) {
  48388. if (this._loopAnimation) {
  48389. this.cellIndex = this._fromIndex;
  48390. }
  48391. else {
  48392. this.cellIndex = this._toIndex;
  48393. this._animationStarted = false;
  48394. if (this._onAnimationEnd) {
  48395. this._onAnimationEnd();
  48396. }
  48397. if (this.disposeWhenFinishedAnimating) {
  48398. this.dispose();
  48399. }
  48400. }
  48401. }
  48402. }
  48403. };
  48404. Sprite.prototype.dispose = function () {
  48405. for (var i = 0; i < this._manager.sprites.length; i++) {
  48406. if (this._manager.sprites[i] == this) {
  48407. this._manager.sprites.splice(i, 1);
  48408. }
  48409. }
  48410. };
  48411. return Sprite;
  48412. }());
  48413. BABYLON.Sprite = Sprite;
  48414. })(BABYLON || (BABYLON = {}));
  48415. //# sourceMappingURL=babylon.sprite.js.map
  48416. var BABYLON;
  48417. (function (BABYLON) {
  48418. var IntersectionInfo = /** @class */ (function () {
  48419. function IntersectionInfo(bu, bv, distance) {
  48420. this.bu = bu;
  48421. this.bv = bv;
  48422. this.distance = distance;
  48423. this.faceId = 0;
  48424. this.subMeshId = 0;
  48425. }
  48426. return IntersectionInfo;
  48427. }());
  48428. BABYLON.IntersectionInfo = IntersectionInfo;
  48429. var PickingInfo = /** @class */ (function () {
  48430. function PickingInfo() {
  48431. this.hit = false;
  48432. this.distance = 0;
  48433. this.pickedPoint = null;
  48434. this.pickedMesh = null;
  48435. this.bu = 0;
  48436. this.bv = 0;
  48437. this.faceId = -1;
  48438. this.subMeshId = 0;
  48439. this.pickedSprite = null;
  48440. }
  48441. // Methods
  48442. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48443. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48444. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48445. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48446. return null;
  48447. }
  48448. var indices = this.pickedMesh.getIndices();
  48449. if (!indices) {
  48450. return null;
  48451. }
  48452. var result;
  48453. if (useVerticesNormals) {
  48454. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48455. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48456. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48457. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48458. normal0 = normal0.scale(this.bu);
  48459. normal1 = normal1.scale(this.bv);
  48460. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48461. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48462. }
  48463. else {
  48464. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48465. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48466. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48467. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48468. var p1p2 = vertex1.subtract(vertex2);
  48469. var p3p2 = vertex3.subtract(vertex2);
  48470. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48471. }
  48472. if (useWorldCoordinates) {
  48473. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48474. }
  48475. return BABYLON.Vector3.Normalize(result);
  48476. };
  48477. PickingInfo.prototype.getTextureCoordinates = function () {
  48478. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48479. return null;
  48480. }
  48481. var indices = this.pickedMesh.getIndices();
  48482. if (!indices) {
  48483. return null;
  48484. }
  48485. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48486. if (!uvs) {
  48487. return null;
  48488. }
  48489. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48490. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48491. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48492. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48493. uv1 = uv1.scale(this.bu);
  48494. uv2 = uv2.scale(this.bv);
  48495. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48496. };
  48497. return PickingInfo;
  48498. }());
  48499. BABYLON.PickingInfo = PickingInfo;
  48500. })(BABYLON || (BABYLON = {}));
  48501. //# sourceMappingURL=babylon.pickingInfo.js.map
  48502. var BABYLON;
  48503. (function (BABYLON) {
  48504. var Ray = /** @class */ (function () {
  48505. function Ray(origin, direction, length) {
  48506. if (length === void 0) { length = Number.MAX_VALUE; }
  48507. this.origin = origin;
  48508. this.direction = direction;
  48509. this.length = length;
  48510. }
  48511. // Methods
  48512. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48513. var d = 0.0;
  48514. var maxValue = Number.MAX_VALUE;
  48515. var inv;
  48516. var min;
  48517. var max;
  48518. var temp;
  48519. if (Math.abs(this.direction.x) < 0.0000001) {
  48520. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48521. return false;
  48522. }
  48523. }
  48524. else {
  48525. inv = 1.0 / this.direction.x;
  48526. min = (minimum.x - this.origin.x) * inv;
  48527. max = (maximum.x - this.origin.x) * inv;
  48528. if (max === -Infinity) {
  48529. max = Infinity;
  48530. }
  48531. if (min > max) {
  48532. temp = min;
  48533. min = max;
  48534. max = temp;
  48535. }
  48536. d = Math.max(min, d);
  48537. maxValue = Math.min(max, maxValue);
  48538. if (d > maxValue) {
  48539. return false;
  48540. }
  48541. }
  48542. if (Math.abs(this.direction.y) < 0.0000001) {
  48543. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48544. return false;
  48545. }
  48546. }
  48547. else {
  48548. inv = 1.0 / this.direction.y;
  48549. min = (minimum.y - this.origin.y) * inv;
  48550. max = (maximum.y - this.origin.y) * inv;
  48551. if (max === -Infinity) {
  48552. max = Infinity;
  48553. }
  48554. if (min > max) {
  48555. temp = min;
  48556. min = max;
  48557. max = temp;
  48558. }
  48559. d = Math.max(min, d);
  48560. maxValue = Math.min(max, maxValue);
  48561. if (d > maxValue) {
  48562. return false;
  48563. }
  48564. }
  48565. if (Math.abs(this.direction.z) < 0.0000001) {
  48566. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48567. return false;
  48568. }
  48569. }
  48570. else {
  48571. inv = 1.0 / this.direction.z;
  48572. min = (minimum.z - this.origin.z) * inv;
  48573. max = (maximum.z - this.origin.z) * inv;
  48574. if (max === -Infinity) {
  48575. max = Infinity;
  48576. }
  48577. if (min > max) {
  48578. temp = min;
  48579. min = max;
  48580. max = temp;
  48581. }
  48582. d = Math.max(min, d);
  48583. maxValue = Math.min(max, maxValue);
  48584. if (d > maxValue) {
  48585. return false;
  48586. }
  48587. }
  48588. return true;
  48589. };
  48590. Ray.prototype.intersectsBox = function (box) {
  48591. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48592. };
  48593. Ray.prototype.intersectsSphere = function (sphere) {
  48594. var x = sphere.center.x - this.origin.x;
  48595. var y = sphere.center.y - this.origin.y;
  48596. var z = sphere.center.z - this.origin.z;
  48597. var pyth = (x * x) + (y * y) + (z * z);
  48598. var rr = sphere.radius * sphere.radius;
  48599. if (pyth <= rr) {
  48600. return true;
  48601. }
  48602. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48603. if (dot < 0.0) {
  48604. return false;
  48605. }
  48606. var temp = pyth - (dot * dot);
  48607. return temp <= rr;
  48608. };
  48609. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48610. if (!this._edge1) {
  48611. this._edge1 = BABYLON.Vector3.Zero();
  48612. this._edge2 = BABYLON.Vector3.Zero();
  48613. this._pvec = BABYLON.Vector3.Zero();
  48614. this._tvec = BABYLON.Vector3.Zero();
  48615. this._qvec = BABYLON.Vector3.Zero();
  48616. }
  48617. vertex1.subtractToRef(vertex0, this._edge1);
  48618. vertex2.subtractToRef(vertex0, this._edge2);
  48619. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48620. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48621. if (det === 0) {
  48622. return null;
  48623. }
  48624. var invdet = 1 / det;
  48625. this.origin.subtractToRef(vertex0, this._tvec);
  48626. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48627. if (bu < 0 || bu > 1.0) {
  48628. return null;
  48629. }
  48630. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48631. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48632. if (bv < 0 || bu + bv > 1.0) {
  48633. return null;
  48634. }
  48635. //check if the distance is longer than the predefined length.
  48636. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48637. if (distance > this.length) {
  48638. return null;
  48639. }
  48640. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48641. };
  48642. Ray.prototype.intersectsPlane = function (plane) {
  48643. var distance;
  48644. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  48645. if (Math.abs(result1) < 9.99999997475243E-07) {
  48646. return null;
  48647. }
  48648. else {
  48649. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  48650. distance = (-plane.d - result2) / result1;
  48651. if (distance < 0.0) {
  48652. if (distance < -9.99999997475243E-07) {
  48653. return null;
  48654. }
  48655. else {
  48656. return 0;
  48657. }
  48658. }
  48659. return distance;
  48660. }
  48661. };
  48662. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  48663. var tm = BABYLON.Tmp.Matrix[0];
  48664. mesh.getWorldMatrix().invertToRef(tm);
  48665. if (this._tmpRay) {
  48666. Ray.TransformToRef(this, tm, this._tmpRay);
  48667. }
  48668. else {
  48669. this._tmpRay = Ray.Transform(this, tm);
  48670. }
  48671. return mesh.intersects(this._tmpRay, fastCheck);
  48672. };
  48673. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  48674. if (results) {
  48675. results.length = 0;
  48676. }
  48677. else {
  48678. results = [];
  48679. }
  48680. for (var i = 0; i < meshes.length; i++) {
  48681. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  48682. if (pickInfo.hit) {
  48683. results.push(pickInfo);
  48684. }
  48685. }
  48686. results.sort(this._comparePickingInfo);
  48687. return results;
  48688. };
  48689. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  48690. if (pickingInfoA.distance < pickingInfoB.distance) {
  48691. return -1;
  48692. }
  48693. else if (pickingInfoA.distance > pickingInfoB.distance) {
  48694. return 1;
  48695. }
  48696. else {
  48697. return 0;
  48698. }
  48699. };
  48700. /**
  48701. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  48702. * @param sega the first point of the segment to test the intersection against
  48703. * @param segb the second point of the segment to test the intersection against
  48704. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  48705. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  48706. */
  48707. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  48708. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  48709. var u = segb.subtract(sega);
  48710. var v = rsegb.subtract(this.origin);
  48711. var w = sega.subtract(this.origin);
  48712. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  48713. var b = BABYLON.Vector3.Dot(u, v);
  48714. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  48715. var d = BABYLON.Vector3.Dot(u, w);
  48716. var e = BABYLON.Vector3.Dot(v, w);
  48717. var D = a * c - b * b; // always >= 0
  48718. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  48719. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  48720. // compute the line parameters of the two closest points
  48721. if (D < Ray.smallnum) {
  48722. sN = 0.0; // force using point P0 on segment S1
  48723. sD = 1.0; // to prevent possible division by 0.0 later
  48724. tN = e;
  48725. tD = c;
  48726. }
  48727. else {
  48728. sN = (b * e - c * d);
  48729. tN = (a * e - b * d);
  48730. if (sN < 0.0) {
  48731. sN = 0.0;
  48732. tN = e;
  48733. tD = c;
  48734. }
  48735. else if (sN > sD) {
  48736. sN = sD;
  48737. tN = e + b;
  48738. tD = c;
  48739. }
  48740. }
  48741. if (tN < 0.0) {
  48742. tN = 0.0;
  48743. // recompute sc for this edge
  48744. if (-d < 0.0) {
  48745. sN = 0.0;
  48746. }
  48747. else if (-d > a)
  48748. sN = sD;
  48749. else {
  48750. sN = -d;
  48751. sD = a;
  48752. }
  48753. }
  48754. else if (tN > tD) {
  48755. tN = tD;
  48756. // recompute sc for this edge
  48757. if ((-d + b) < 0.0) {
  48758. sN = 0;
  48759. }
  48760. else if ((-d + b) > a) {
  48761. sN = sD;
  48762. }
  48763. else {
  48764. sN = (-d + b);
  48765. sD = a;
  48766. }
  48767. }
  48768. // finally do the division to get sc and tc
  48769. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  48770. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  48771. // get the difference of the two closest points
  48772. var qtc = v.multiplyByFloats(tc, tc, tc);
  48773. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  48774. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  48775. if (isIntersected) {
  48776. return qtc.length();
  48777. }
  48778. return -1;
  48779. };
  48780. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  48781. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  48782. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  48783. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  48784. this.direction.normalize();
  48785. return this;
  48786. };
  48787. // Statics
  48788. Ray.Zero = function () {
  48789. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  48790. };
  48791. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  48792. var result = Ray.Zero();
  48793. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  48794. };
  48795. /**
  48796. * 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
  48797. * transformed to the given world matrix.
  48798. * @param origin The origin point
  48799. * @param end The end point
  48800. * @param world a matrix to transform the ray to. Default is the identity matrix.
  48801. */
  48802. Ray.CreateNewFromTo = function (origin, end, world) {
  48803. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  48804. var direction = end.subtract(origin);
  48805. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  48806. direction.normalize();
  48807. return Ray.Transform(new Ray(origin, direction, length), world);
  48808. };
  48809. Ray.Transform = function (ray, matrix) {
  48810. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  48811. Ray.TransformToRef(ray, matrix, result);
  48812. return result;
  48813. };
  48814. Ray.TransformToRef = function (ray, matrix, result) {
  48815. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  48816. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  48817. result.length = ray.length;
  48818. var dir = result.direction;
  48819. var len = dir.length();
  48820. if (!(len === 0 || len === 1)) {
  48821. var num = 1.0 / len;
  48822. dir.x *= num;
  48823. dir.y *= num;
  48824. dir.z *= num;
  48825. result.length *= len;
  48826. }
  48827. };
  48828. Ray.smallnum = 0.00000001;
  48829. Ray.rayl = 10e8;
  48830. return Ray;
  48831. }());
  48832. BABYLON.Ray = Ray;
  48833. })(BABYLON || (BABYLON = {}));
  48834. //# sourceMappingURL=babylon.ray.js.map
  48835. var BABYLON;
  48836. (function (BABYLON) {
  48837. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  48838. if (boxMin.x > sphereCenter.x + sphereRadius)
  48839. return false;
  48840. if (sphereCenter.x - sphereRadius > boxMax.x)
  48841. return false;
  48842. if (boxMin.y > sphereCenter.y + sphereRadius)
  48843. return false;
  48844. if (sphereCenter.y - sphereRadius > boxMax.y)
  48845. return false;
  48846. if (boxMin.z > sphereCenter.z + sphereRadius)
  48847. return false;
  48848. if (sphereCenter.z - sphereRadius > boxMax.z)
  48849. return false;
  48850. return true;
  48851. };
  48852. var getLowestRoot = (function () {
  48853. var result = { root: 0, found: false };
  48854. return function (a, b, c, maxR) {
  48855. result.root = 0;
  48856. result.found = false;
  48857. var determinant = b * b - 4.0 * a * c;
  48858. if (determinant < 0)
  48859. return result;
  48860. var sqrtD = Math.sqrt(determinant);
  48861. var r1 = (-b - sqrtD) / (2.0 * a);
  48862. var r2 = (-b + sqrtD) / (2.0 * a);
  48863. if (r1 > r2) {
  48864. var temp = r2;
  48865. r2 = r1;
  48866. r1 = temp;
  48867. }
  48868. if (r1 > 0 && r1 < maxR) {
  48869. result.root = r1;
  48870. result.found = true;
  48871. return result;
  48872. }
  48873. if (r2 > 0 && r2 < maxR) {
  48874. result.root = r2;
  48875. result.found = true;
  48876. return result;
  48877. }
  48878. return result;
  48879. };
  48880. })();
  48881. var Collider = /** @class */ (function () {
  48882. function Collider() {
  48883. this._collisionPoint = BABYLON.Vector3.Zero();
  48884. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  48885. this._tempVector = BABYLON.Vector3.Zero();
  48886. this._tempVector2 = BABYLON.Vector3.Zero();
  48887. this._tempVector3 = BABYLON.Vector3.Zero();
  48888. this._tempVector4 = BABYLON.Vector3.Zero();
  48889. this._edge = BABYLON.Vector3.Zero();
  48890. this._baseToVertex = BABYLON.Vector3.Zero();
  48891. this._destinationPoint = BABYLON.Vector3.Zero();
  48892. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  48893. this._displacementVector = BABYLON.Vector3.Zero();
  48894. this._radius = BABYLON.Vector3.One();
  48895. this._retry = 0;
  48896. this._basePointWorld = BABYLON.Vector3.Zero();
  48897. this._velocityWorld = BABYLON.Vector3.Zero();
  48898. this._normalizedVelocity = BABYLON.Vector3.Zero();
  48899. this._collisionMask = -1;
  48900. }
  48901. Object.defineProperty(Collider.prototype, "collisionMask", {
  48902. get: function () {
  48903. return this._collisionMask;
  48904. },
  48905. set: function (mask) {
  48906. this._collisionMask = !isNaN(mask) ? mask : -1;
  48907. },
  48908. enumerable: true,
  48909. configurable: true
  48910. });
  48911. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  48912. /**
  48913. * Gets the plane normal used to compute the sliding response (in local space)
  48914. */
  48915. get: function () {
  48916. return this._slidePlaneNormal;
  48917. },
  48918. enumerable: true,
  48919. configurable: true
  48920. });
  48921. // Methods
  48922. Collider.prototype._initialize = function (source, dir, e) {
  48923. this._velocity = dir;
  48924. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  48925. this._basePoint = source;
  48926. source.multiplyToRef(this._radius, this._basePointWorld);
  48927. dir.multiplyToRef(this._radius, this._velocityWorld);
  48928. this._velocityWorldLength = this._velocityWorld.length();
  48929. this._epsilon = e;
  48930. this.collisionFound = false;
  48931. };
  48932. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  48933. pa.subtractToRef(point, this._tempVector);
  48934. pb.subtractToRef(point, this._tempVector2);
  48935. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  48936. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  48937. if (d < 0)
  48938. return false;
  48939. pc.subtractToRef(point, this._tempVector3);
  48940. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  48941. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  48942. if (d < 0)
  48943. return false;
  48944. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  48945. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  48946. return d >= 0;
  48947. };
  48948. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  48949. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  48950. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  48951. if (distance > this._velocityWorldLength + max + sphereRadius) {
  48952. return false;
  48953. }
  48954. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  48955. return false;
  48956. return true;
  48957. };
  48958. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  48959. var t0;
  48960. var embeddedInPlane = false;
  48961. //defensive programming, actually not needed.
  48962. if (!trianglePlaneArray) {
  48963. trianglePlaneArray = [];
  48964. }
  48965. if (!trianglePlaneArray[faceIndex]) {
  48966. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  48967. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  48968. }
  48969. var trianglePlane = trianglePlaneArray[faceIndex];
  48970. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  48971. return;
  48972. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  48973. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  48974. if (normalDotVelocity == 0) {
  48975. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  48976. return;
  48977. embeddedInPlane = true;
  48978. t0 = 0;
  48979. }
  48980. else {
  48981. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  48982. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  48983. if (t0 > t1) {
  48984. var temp = t1;
  48985. t1 = t0;
  48986. t0 = temp;
  48987. }
  48988. if (t0 > 1.0 || t1 < 0.0)
  48989. return;
  48990. if (t0 < 0)
  48991. t0 = 0;
  48992. if (t0 > 1.0)
  48993. t0 = 1.0;
  48994. }
  48995. this._collisionPoint.copyFromFloats(0, 0, 0);
  48996. var found = false;
  48997. var t = 1.0;
  48998. if (!embeddedInPlane) {
  48999. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49000. this._velocity.scaleToRef(t0, this._tempVector);
  49001. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49002. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49003. found = true;
  49004. t = t0;
  49005. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49006. }
  49007. }
  49008. if (!found) {
  49009. var velocitySquaredLength = this._velocity.lengthSquared();
  49010. var a = velocitySquaredLength;
  49011. this._basePoint.subtractToRef(p1, this._tempVector);
  49012. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49013. var c = this._tempVector.lengthSquared() - 1.0;
  49014. var lowestRoot = getLowestRoot(a, b, c, t);
  49015. if (lowestRoot.found) {
  49016. t = lowestRoot.root;
  49017. found = true;
  49018. this._collisionPoint.copyFrom(p1);
  49019. }
  49020. this._basePoint.subtractToRef(p2, this._tempVector);
  49021. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49022. c = this._tempVector.lengthSquared() - 1.0;
  49023. lowestRoot = getLowestRoot(a, b, c, t);
  49024. if (lowestRoot.found) {
  49025. t = lowestRoot.root;
  49026. found = true;
  49027. this._collisionPoint.copyFrom(p2);
  49028. }
  49029. this._basePoint.subtractToRef(p3, this._tempVector);
  49030. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49031. c = this._tempVector.lengthSquared() - 1.0;
  49032. lowestRoot = getLowestRoot(a, b, c, t);
  49033. if (lowestRoot.found) {
  49034. t = lowestRoot.root;
  49035. found = true;
  49036. this._collisionPoint.copyFrom(p3);
  49037. }
  49038. p2.subtractToRef(p1, this._edge);
  49039. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49040. var edgeSquaredLength = this._edge.lengthSquared();
  49041. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49042. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49043. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49044. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49045. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49046. lowestRoot = getLowestRoot(a, b, c, t);
  49047. if (lowestRoot.found) {
  49048. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49049. if (f >= 0.0 && f <= 1.0) {
  49050. t = lowestRoot.root;
  49051. found = true;
  49052. this._edge.scaleInPlace(f);
  49053. p1.addToRef(this._edge, this._collisionPoint);
  49054. }
  49055. }
  49056. p3.subtractToRef(p2, this._edge);
  49057. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49058. edgeSquaredLength = this._edge.lengthSquared();
  49059. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49060. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49061. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49062. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49063. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49064. lowestRoot = getLowestRoot(a, b, c, t);
  49065. if (lowestRoot.found) {
  49066. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49067. if (f >= 0.0 && f <= 1.0) {
  49068. t = lowestRoot.root;
  49069. found = true;
  49070. this._edge.scaleInPlace(f);
  49071. p2.addToRef(this._edge, this._collisionPoint);
  49072. }
  49073. }
  49074. p1.subtractToRef(p3, this._edge);
  49075. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49076. edgeSquaredLength = this._edge.lengthSquared();
  49077. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49078. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49079. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49080. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49081. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49082. lowestRoot = getLowestRoot(a, b, c, t);
  49083. if (lowestRoot.found) {
  49084. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49085. if (f >= 0.0 && f <= 1.0) {
  49086. t = lowestRoot.root;
  49087. found = true;
  49088. this._edge.scaleInPlace(f);
  49089. p3.addToRef(this._edge, this._collisionPoint);
  49090. }
  49091. }
  49092. }
  49093. if (found) {
  49094. var distToCollision = t * this._velocity.length();
  49095. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49096. if (!this.intersectionPoint) {
  49097. this.intersectionPoint = this._collisionPoint.clone();
  49098. }
  49099. else {
  49100. this.intersectionPoint.copyFrom(this._collisionPoint);
  49101. }
  49102. this._nearestDistance = distToCollision;
  49103. this.collisionFound = true;
  49104. }
  49105. }
  49106. };
  49107. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49108. for (var i = indexStart; i < indexEnd; i += 3) {
  49109. var p1 = pts[indices[i] - decal];
  49110. var p2 = pts[indices[i + 1] - decal];
  49111. var p3 = pts[indices[i + 2] - decal];
  49112. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49113. }
  49114. };
  49115. Collider.prototype._getResponse = function (pos, vel) {
  49116. pos.addToRef(vel, this._destinationPoint);
  49117. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49118. this._basePoint.addToRef(vel, pos);
  49119. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49120. this._slidePlaneNormal.normalize();
  49121. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49122. pos.addInPlace(this._displacementVector);
  49123. this.intersectionPoint.addInPlace(this._displacementVector);
  49124. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49125. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49126. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49127. };
  49128. return Collider;
  49129. }());
  49130. BABYLON.Collider = Collider;
  49131. })(BABYLON || (BABYLON = {}));
  49132. //# sourceMappingURL=babylon.collider.js.map
  49133. var BABYLON;
  49134. (function (BABYLON) {
  49135. //WebWorker code will be inserted to this variable.
  49136. BABYLON.CollisionWorker = "";
  49137. var WorkerTaskType;
  49138. (function (WorkerTaskType) {
  49139. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49140. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49141. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49142. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49143. var WorkerReplyType;
  49144. (function (WorkerReplyType) {
  49145. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49146. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49147. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49148. var CollisionCoordinatorWorker = /** @class */ (function () {
  49149. function CollisionCoordinatorWorker() {
  49150. var _this = this;
  49151. this._scaledPosition = BABYLON.Vector3.Zero();
  49152. this._scaledVelocity = BABYLON.Vector3.Zero();
  49153. this.onMeshUpdated = function (transformNode) {
  49154. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49155. };
  49156. this.onGeometryUpdated = function (geometry) {
  49157. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49158. };
  49159. this._afterRender = function () {
  49160. if (!_this._init)
  49161. return;
  49162. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49163. return;
  49164. }
  49165. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49166. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49167. if (_this._runningUpdated > 4) {
  49168. return;
  49169. }
  49170. ++_this._runningUpdated;
  49171. var payload = {
  49172. updatedMeshes: _this._addUpdateMeshesList,
  49173. updatedGeometries: _this._addUpdateGeometriesList,
  49174. removedGeometries: _this._toRemoveGeometryArray,
  49175. removedMeshes: _this._toRemoveMeshesArray
  49176. };
  49177. var message = {
  49178. payload: payload,
  49179. taskType: WorkerTaskType.UPDATE
  49180. };
  49181. var serializable = [];
  49182. for (var id in payload.updatedGeometries) {
  49183. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49184. //prepare transferables
  49185. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49186. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49187. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49188. }
  49189. }
  49190. _this._worker.postMessage(message, serializable);
  49191. _this._addUpdateMeshesList = {};
  49192. _this._addUpdateGeometriesList = {};
  49193. _this._toRemoveGeometryArray = [];
  49194. _this._toRemoveMeshesArray = [];
  49195. };
  49196. this._onMessageFromWorker = function (e) {
  49197. var returnData = e.data;
  49198. if (returnData.error != WorkerReplyType.SUCCESS) {
  49199. //TODO what errors can be returned from the worker?
  49200. BABYLON.Tools.Warn("error returned from worker!");
  49201. return;
  49202. }
  49203. switch (returnData.taskType) {
  49204. case WorkerTaskType.INIT:
  49205. _this._init = true;
  49206. //Update the worked with ALL of the scene's current state
  49207. _this._scene.meshes.forEach(function (mesh) {
  49208. _this.onMeshAdded(mesh);
  49209. });
  49210. _this._scene.getGeometries().forEach(function (geometry) {
  49211. _this.onGeometryAdded(geometry);
  49212. });
  49213. break;
  49214. case WorkerTaskType.UPDATE:
  49215. _this._runningUpdated--;
  49216. break;
  49217. case WorkerTaskType.COLLIDE:
  49218. var returnPayload = returnData.payload;
  49219. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49220. return;
  49221. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49222. if (callback) {
  49223. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49224. if (mesh) {
  49225. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49226. }
  49227. }
  49228. //cleanup
  49229. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49230. break;
  49231. }
  49232. };
  49233. this._collisionsCallbackArray = [];
  49234. this._init = false;
  49235. this._runningUpdated = 0;
  49236. this._addUpdateMeshesList = {};
  49237. this._addUpdateGeometriesList = {};
  49238. this._toRemoveGeometryArray = [];
  49239. this._toRemoveMeshesArray = [];
  49240. }
  49241. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49242. if (!this._init)
  49243. return;
  49244. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49245. return;
  49246. position.divideToRef(collider._radius, this._scaledPosition);
  49247. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49248. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49249. var payload = {
  49250. collider: {
  49251. position: this._scaledPosition.asArray(),
  49252. velocity: this._scaledVelocity.asArray(),
  49253. radius: collider._radius.asArray()
  49254. },
  49255. collisionId: collisionIndex,
  49256. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49257. maximumRetry: maximumRetry
  49258. };
  49259. var message = {
  49260. payload: payload,
  49261. taskType: WorkerTaskType.COLLIDE
  49262. };
  49263. this._worker.postMessage(message);
  49264. };
  49265. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49266. this._scene = scene;
  49267. this._scene.registerAfterRender(this._afterRender);
  49268. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49269. this._worker = new Worker(workerUrl);
  49270. this._worker.onmessage = this._onMessageFromWorker;
  49271. var message = {
  49272. payload: {},
  49273. taskType: WorkerTaskType.INIT
  49274. };
  49275. this._worker.postMessage(message);
  49276. };
  49277. CollisionCoordinatorWorker.prototype.destroy = function () {
  49278. this._scene.unregisterAfterRender(this._afterRender);
  49279. this._worker.terminate();
  49280. };
  49281. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49282. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49283. this.onMeshUpdated(mesh);
  49284. };
  49285. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49286. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49287. };
  49288. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49289. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49290. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49291. this.onGeometryUpdated(geometry);
  49292. };
  49293. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49294. this._toRemoveGeometryArray.push(geometry.id);
  49295. };
  49296. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49297. var submeshes = [];
  49298. if (mesh.subMeshes) {
  49299. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49300. var boundingInfo = sm.getBoundingInfo();
  49301. return {
  49302. position: idx,
  49303. verticesStart: sm.verticesStart,
  49304. verticesCount: sm.verticesCount,
  49305. indexStart: sm.indexStart,
  49306. indexCount: sm.indexCount,
  49307. hasMaterial: !!sm.getMaterial(),
  49308. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49309. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49310. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49311. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49312. };
  49313. });
  49314. }
  49315. var geometryId = null;
  49316. if (mesh instanceof BABYLON.Mesh) {
  49317. var geometry = mesh.geometry;
  49318. geometryId = geometry ? geometry.id : null;
  49319. }
  49320. else if (mesh instanceof BABYLON.InstancedMesh) {
  49321. var geometry = mesh.sourceMesh.geometry;
  49322. geometryId = geometry ? geometry.id : null;
  49323. }
  49324. var boundingInfo = mesh.getBoundingInfo();
  49325. return {
  49326. uniqueId: mesh.uniqueId,
  49327. id: mesh.id,
  49328. name: mesh.name,
  49329. geometryId: geometryId,
  49330. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49331. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49332. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49333. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49334. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49335. subMeshes: submeshes,
  49336. checkCollisions: mesh.checkCollisions
  49337. };
  49338. };
  49339. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49340. return {
  49341. id: geometry.id,
  49342. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49343. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49344. indices: new Uint32Array(geometry.getIndices() || []),
  49345. };
  49346. };
  49347. return CollisionCoordinatorWorker;
  49348. }());
  49349. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49350. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49351. function CollisionCoordinatorLegacy() {
  49352. this._scaledPosition = BABYLON.Vector3.Zero();
  49353. this._scaledVelocity = BABYLON.Vector3.Zero();
  49354. this._finalPosition = BABYLON.Vector3.Zero();
  49355. }
  49356. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49357. position.divideToRef(collider._radius, this._scaledPosition);
  49358. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49359. collider.collidedMesh = null;
  49360. collider._retry = 0;
  49361. collider._initialVelocity = this._scaledVelocity;
  49362. collider._initialPosition = this._scaledPosition;
  49363. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49364. this._finalPosition.multiplyInPlace(collider._radius);
  49365. //run the callback
  49366. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49367. };
  49368. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49369. this._scene = scene;
  49370. };
  49371. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49372. //Legacy need no destruction method.
  49373. };
  49374. //No update in legacy mode
  49375. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49376. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49377. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49378. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49379. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49380. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49381. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49382. if (excludedMesh === void 0) { excludedMesh = null; }
  49383. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49384. if (collider._retry >= maximumRetry) {
  49385. finalPosition.copyFrom(position);
  49386. return;
  49387. }
  49388. // Check if this is a mesh else camera or -1
  49389. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49390. collider._initialize(position, velocity, closeDistance);
  49391. // Check all meshes
  49392. for (var index = 0; index < this._scene.meshes.length; index++) {
  49393. var mesh = this._scene.meshes[index];
  49394. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49395. mesh._checkCollision(collider);
  49396. }
  49397. }
  49398. if (!collider.collisionFound) {
  49399. position.addToRef(velocity, finalPosition);
  49400. return;
  49401. }
  49402. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49403. collider._getResponse(position, velocity);
  49404. }
  49405. if (velocity.length() <= closeDistance) {
  49406. finalPosition.copyFrom(position);
  49407. return;
  49408. }
  49409. collider._retry++;
  49410. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49411. };
  49412. return CollisionCoordinatorLegacy;
  49413. }());
  49414. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49415. })(BABYLON || (BABYLON = {}));
  49416. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49417. var BABYLON;
  49418. (function (BABYLON) {
  49419. /**
  49420. * A particle represents one of the element emitted by a particle system.
  49421. * This is mainly define by its coordinates, direction, velocity and age.
  49422. */
  49423. var Particle = /** @class */ (function () {
  49424. /**
  49425. * Creates a new instance of @see Particle
  49426. * @param particleSystem the particle system the particle belongs to
  49427. */
  49428. function Particle(particleSystem) {
  49429. this.particleSystem = particleSystem;
  49430. /**
  49431. * The world position of the particle in the scene.
  49432. */
  49433. this.position = BABYLON.Vector3.Zero();
  49434. /**
  49435. * The world direction of the particle in the scene.
  49436. */
  49437. this.direction = BABYLON.Vector3.Zero();
  49438. /**
  49439. * The color of the particle.
  49440. */
  49441. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49442. /**
  49443. * The color change of the particle per step.
  49444. */
  49445. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49446. /**
  49447. * Defines how long will the life of the particle be.
  49448. */
  49449. this.lifeTime = 1.0;
  49450. /**
  49451. * The current age of the particle.
  49452. */
  49453. this.age = 0;
  49454. /**
  49455. * The current size of the particle.
  49456. */
  49457. this.size = 0;
  49458. /**
  49459. * The current angle of the particle.
  49460. */
  49461. this.angle = 0;
  49462. /**
  49463. * Defines how fast is the angle changing.
  49464. */
  49465. this.angularSpeed = 0;
  49466. /**
  49467. * Defines the cell index used by the particle to be rendered from a sprite.
  49468. */
  49469. this.cellIndex = 0;
  49470. this._currentFrameCounter = 0;
  49471. if (!this.particleSystem.isAnimationSheetEnabled) {
  49472. return;
  49473. }
  49474. this.cellIndex = this.particleSystem.startSpriteCellID;
  49475. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49476. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49477. }
  49478. else {
  49479. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49480. }
  49481. }
  49482. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49483. // (ageOffset / scaledUpdateSpeed) / available cells
  49484. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49485. this._currentFrameCounter += scaledUpdateSpeed;
  49486. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49487. this._currentFrameCounter = 0;
  49488. this.cellIndex++;
  49489. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49490. this.cellIndex = this.particleSystem.endSpriteCellID;
  49491. }
  49492. }
  49493. };
  49494. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49495. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49496. this.cellIndex++;
  49497. this._currentFrameCounter = 0;
  49498. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49499. if (this.particleSystem.spriteCellLoop) {
  49500. this.cellIndex = this.particleSystem.startSpriteCellID;
  49501. }
  49502. else {
  49503. this.cellIndex = this.particleSystem.endSpriteCellID;
  49504. }
  49505. }
  49506. }
  49507. else {
  49508. this._currentFrameCounter++;
  49509. }
  49510. };
  49511. /**
  49512. * Copy the properties of particle to another one.
  49513. * @param other the particle to copy the information to.
  49514. */
  49515. Particle.prototype.copyTo = function (other) {
  49516. other.position.copyFrom(this.position);
  49517. other.direction.copyFrom(this.direction);
  49518. other.color.copyFrom(this.color);
  49519. other.colorStep.copyFrom(this.colorStep);
  49520. other.lifeTime = this.lifeTime;
  49521. other.age = this.age;
  49522. other.size = this.size;
  49523. other.angle = this.angle;
  49524. other.angularSpeed = this.angularSpeed;
  49525. other.particleSystem = this.particleSystem;
  49526. other.cellIndex = this.cellIndex;
  49527. };
  49528. return Particle;
  49529. }());
  49530. BABYLON.Particle = Particle;
  49531. })(BABYLON || (BABYLON = {}));
  49532. //# sourceMappingURL=babylon.particle.js.map
  49533. var BABYLON;
  49534. (function (BABYLON) {
  49535. /**
  49536. * This represents a particle system in Babylon.
  49537. * 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.
  49538. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49539. * @example https://doc.babylonjs.com/babylon101/particles
  49540. */
  49541. var ParticleSystem = /** @class */ (function () {
  49542. /**
  49543. * Instantiates a particle system.
  49544. * 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.
  49545. * @param name The name of the particle system
  49546. * @param capacity The max number of particles alive at the same time
  49547. * @param scene The scene the particle system belongs to
  49548. * @param customEffect a custom effect used to change the way particles are rendered by default
  49549. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49550. * @param epsilon Offset used to render the particles
  49551. */
  49552. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49553. if (customEffect === void 0) { customEffect = null; }
  49554. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49555. if (epsilon === void 0) { epsilon = 0.01; }
  49556. var _this = this;
  49557. /**
  49558. * List of animations used by the particle system.
  49559. */
  49560. this.animations = [];
  49561. /**
  49562. * The rendering group used by the Particle system to chose when to render.
  49563. */
  49564. this.renderingGroupId = 0;
  49565. /**
  49566. * The emitter represents the Mesh or position we are attaching the particle system to.
  49567. */
  49568. this.emitter = null;
  49569. /**
  49570. * The density of particles, the rate of particle flow
  49571. */
  49572. this.emitRate = 10;
  49573. /**
  49574. * If you want to launch only a few particles at once, that can be done, as well.
  49575. */
  49576. this.manualEmitCount = -1;
  49577. /**
  49578. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49579. */
  49580. this.updateSpeed = 0.01;
  49581. /**
  49582. * The amount of time the particle system is running (depends of the overall speed above).
  49583. */
  49584. this.targetStopDuration = 0;
  49585. /**
  49586. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49587. */
  49588. this.disposeOnStop = false;
  49589. /**
  49590. * Minimum power of emitting particles.
  49591. */
  49592. this.minEmitPower = 1;
  49593. /**
  49594. * Maximum power of emitting particles.
  49595. */
  49596. this.maxEmitPower = 1;
  49597. /**
  49598. * Minimum life time of emitting particles.
  49599. */
  49600. this.minLifeTime = 1;
  49601. /**
  49602. * Maximum life time of emitting particles.
  49603. */
  49604. this.maxLifeTime = 1;
  49605. /**
  49606. * Minimum Size of emitting particles.
  49607. */
  49608. this.minSize = 1;
  49609. /**
  49610. * Maximum Size of emitting particles.
  49611. */
  49612. this.maxSize = 1;
  49613. /**
  49614. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49615. */
  49616. this.minAngularSpeed = 0;
  49617. /**
  49618. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49619. */
  49620. this.maxAngularSpeed = 0;
  49621. /**
  49622. * The layer mask we are rendering the particles through.
  49623. */
  49624. this.layerMask = 0x0FFFFFFF;
  49625. /**
  49626. * This can help using your own shader to render the particle system.
  49627. * The according effect will be created
  49628. */
  49629. this.customShader = null;
  49630. /**
  49631. * By default particle system starts as soon as they are created. This prevents the
  49632. * automatic start to happen and let you decide when to start emitting particles.
  49633. */
  49634. this.preventAutoStart = false;
  49635. /**
  49636. * Callback triggered when the particle animation is ending.
  49637. */
  49638. this.onAnimationEnd = null;
  49639. /**
  49640. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49641. */
  49642. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49643. /**
  49644. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  49645. * to override the particles.
  49646. */
  49647. this.forceDepthWrite = false;
  49648. /**
  49649. * You can use gravity if you want to give an orientation to your particles.
  49650. */
  49651. this.gravity = BABYLON.Vector3.Zero();
  49652. /**
  49653. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49654. */
  49655. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  49656. /**
  49657. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49658. */
  49659. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  49660. /**
  49661. * 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.
  49662. */
  49663. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  49664. /**
  49665. * 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.
  49666. */
  49667. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49668. /**
  49669. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49670. */
  49671. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49672. /**
  49673. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49674. */
  49675. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49676. /**
  49677. * Color the particle will have at the end of its lifetime.
  49678. */
  49679. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  49680. /**
  49681. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  49682. */
  49683. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49684. /**
  49685. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  49686. */
  49687. this.spriteCellLoop = true;
  49688. /**
  49689. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  49690. */
  49691. this.spriteCellChangeSpeed = 0;
  49692. /**
  49693. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  49694. */
  49695. this.startSpriteCellID = 0;
  49696. /**
  49697. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  49698. */
  49699. this.endSpriteCellID = 0;
  49700. /**
  49701. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  49702. */
  49703. this.spriteCellWidth = 0;
  49704. /**
  49705. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  49706. */
  49707. this.spriteCellHeight = 0;
  49708. /**
  49709. * An event triggered when the system is disposed.
  49710. */
  49711. this.onDisposeObservable = new BABYLON.Observable();
  49712. this._particles = new Array();
  49713. this._stockParticles = new Array();
  49714. this._newPartsExcess = 0;
  49715. this._vertexBuffers = {};
  49716. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  49717. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  49718. this._scaledDirection = BABYLON.Vector3.Zero();
  49719. this._scaledGravity = BABYLON.Vector3.Zero();
  49720. this._currentRenderId = -1;
  49721. this._started = false;
  49722. this._stopped = false;
  49723. this._actualFrame = 0;
  49724. this._vertexBufferSize = 11;
  49725. this._appendParticleVertexes = null;
  49726. this.id = name;
  49727. this.name = name;
  49728. this._capacity = capacity;
  49729. this._epsilon = epsilon;
  49730. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  49731. if (isAnimationSheetEnabled) {
  49732. this._vertexBufferSize = 12;
  49733. }
  49734. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49735. this._customEffect = customEffect;
  49736. scene.particleSystems.push(this);
  49737. this._createIndexBuffer();
  49738. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  49739. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  49740. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  49741. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  49742. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  49743. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  49744. if (this._isAnimationSheetEnabled) {
  49745. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  49746. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  49747. }
  49748. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49749. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49750. this._vertexBuffers["options"] = options;
  49751. // Default behaviors
  49752. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  49753. this.updateFunction = function (particles) {
  49754. for (var index = 0; index < particles.length; index++) {
  49755. var particle = particles[index];
  49756. particle.age += _this._scaledUpdateSpeed;
  49757. if (particle.age >= particle.lifeTime) {
  49758. _this.recycleParticle(particle);
  49759. index--;
  49760. continue;
  49761. }
  49762. else {
  49763. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  49764. particle.color.addInPlace(_this._scaledColorStep);
  49765. if (particle.color.a < 0)
  49766. particle.color.a = 0;
  49767. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  49768. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  49769. particle.position.addInPlace(_this._scaledDirection);
  49770. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  49771. particle.direction.addInPlace(_this._scaledGravity);
  49772. if (_this._isAnimationSheetEnabled) {
  49773. particle.updateCellIndex(_this._scaledUpdateSpeed);
  49774. }
  49775. }
  49776. }
  49777. };
  49778. }
  49779. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  49780. /**
  49781. * Sets a callback that will be triggered when the system is disposed.
  49782. */
  49783. set: function (callback) {
  49784. if (this._onDisposeObserver) {
  49785. this.onDisposeObservable.remove(this._onDisposeObserver);
  49786. }
  49787. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49788. },
  49789. enumerable: true,
  49790. configurable: true
  49791. });
  49792. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  49793. /**
  49794. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  49795. */
  49796. get: function () {
  49797. return this._isAnimationSheetEnabled;
  49798. },
  49799. enumerable: true,
  49800. configurable: true
  49801. });
  49802. ParticleSystem.prototype._createIndexBuffer = function () {
  49803. var indices = [];
  49804. var index = 0;
  49805. for (var count = 0; count < this._capacity; count++) {
  49806. indices.push(index);
  49807. indices.push(index + 1);
  49808. indices.push(index + 2);
  49809. indices.push(index);
  49810. indices.push(index + 2);
  49811. indices.push(index + 3);
  49812. index += 4;
  49813. }
  49814. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  49815. };
  49816. /**
  49817. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  49818. * Its lifetime will start back at 0.
  49819. * @param particle The particle to recycle
  49820. */
  49821. ParticleSystem.prototype.recycleParticle = function (particle) {
  49822. var lastParticle = this._particles.pop();
  49823. if (lastParticle !== particle) {
  49824. lastParticle.copyTo(particle);
  49825. this._stockParticles.push(lastParticle);
  49826. }
  49827. };
  49828. /**
  49829. * Gets the maximum number of particles active at the same time.
  49830. * @returns The max number of active particles.
  49831. */
  49832. ParticleSystem.prototype.getCapacity = function () {
  49833. return this._capacity;
  49834. };
  49835. /**
  49836. * Gets Wether there are still active particles in the system.
  49837. * @returns True if it is alive, otherwise false.
  49838. */
  49839. ParticleSystem.prototype.isAlive = function () {
  49840. return this._alive;
  49841. };
  49842. /**
  49843. * Gets Wether the system has been started.
  49844. * @returns True if it has been started, otherwise false.
  49845. */
  49846. ParticleSystem.prototype.isStarted = function () {
  49847. return this._started;
  49848. };
  49849. /**
  49850. * Starts the particle system and begins to emit.
  49851. */
  49852. ParticleSystem.prototype.start = function () {
  49853. this._started = true;
  49854. this._stopped = false;
  49855. this._actualFrame = 0;
  49856. };
  49857. /**
  49858. * Stops the particle system.
  49859. */
  49860. ParticleSystem.prototype.stop = function () {
  49861. this._stopped = true;
  49862. };
  49863. /**
  49864. * @ignore (for internal use only)
  49865. */
  49866. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  49867. var offset = index * this._vertexBufferSize;
  49868. this._vertexData[offset] = particle.position.x;
  49869. this._vertexData[offset + 1] = particle.position.y;
  49870. this._vertexData[offset + 2] = particle.position.z;
  49871. this._vertexData[offset + 3] = particle.color.r;
  49872. this._vertexData[offset + 4] = particle.color.g;
  49873. this._vertexData[offset + 5] = particle.color.b;
  49874. this._vertexData[offset + 6] = particle.color.a;
  49875. this._vertexData[offset + 7] = particle.angle;
  49876. this._vertexData[offset + 8] = particle.size;
  49877. this._vertexData[offset + 9] = offsetX;
  49878. this._vertexData[offset + 10] = offsetY;
  49879. };
  49880. /**
  49881. * @ignore (for internal use only)
  49882. */
  49883. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  49884. if (offsetX === 0)
  49885. offsetX = this._epsilon;
  49886. else if (offsetX === 1)
  49887. offsetX = 1 - this._epsilon;
  49888. if (offsetY === 0)
  49889. offsetY = this._epsilon;
  49890. else if (offsetY === 1)
  49891. offsetY = 1 - this._epsilon;
  49892. var offset = index * this._vertexBufferSize;
  49893. this._vertexData[offset] = particle.position.x;
  49894. this._vertexData[offset + 1] = particle.position.y;
  49895. this._vertexData[offset + 2] = particle.position.z;
  49896. this._vertexData[offset + 3] = particle.color.r;
  49897. this._vertexData[offset + 4] = particle.color.g;
  49898. this._vertexData[offset + 5] = particle.color.b;
  49899. this._vertexData[offset + 6] = particle.color.a;
  49900. this._vertexData[offset + 7] = particle.angle;
  49901. this._vertexData[offset + 8] = particle.size;
  49902. this._vertexData[offset + 9] = offsetX;
  49903. this._vertexData[offset + 10] = offsetY;
  49904. this._vertexData[offset + 11] = particle.cellIndex;
  49905. };
  49906. ParticleSystem.prototype._update = function (newParticles) {
  49907. // Update current
  49908. this._alive = this._particles.length > 0;
  49909. this.updateFunction(this._particles);
  49910. // Add new ones
  49911. var worldMatrix;
  49912. if (this.emitter.position) {
  49913. var emitterMesh = this.emitter;
  49914. worldMatrix = emitterMesh.getWorldMatrix();
  49915. }
  49916. else {
  49917. var emitterPosition = this.emitter;
  49918. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  49919. }
  49920. var particle;
  49921. for (var index = 0; index < newParticles; index++) {
  49922. if (this._particles.length === this._capacity) {
  49923. break;
  49924. }
  49925. if (this._stockParticles.length !== 0) {
  49926. particle = this._stockParticles.pop();
  49927. particle.age = 0;
  49928. particle.cellIndex = this.startSpriteCellID;
  49929. }
  49930. else {
  49931. particle = new BABYLON.Particle(this);
  49932. }
  49933. this._particles.push(particle);
  49934. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  49935. if (this.startPositionFunction) {
  49936. this.startPositionFunction(worldMatrix, particle.position, particle);
  49937. }
  49938. else {
  49939. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  49940. }
  49941. if (this.startDirectionFunction) {
  49942. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  49943. }
  49944. else {
  49945. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  49946. }
  49947. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  49948. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  49949. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  49950. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  49951. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  49952. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  49953. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  49954. }
  49955. };
  49956. ParticleSystem.prototype._getEffect = function () {
  49957. if (this._customEffect) {
  49958. return this._customEffect;
  49959. }
  49960. ;
  49961. var defines = [];
  49962. if (this._scene.clipPlane) {
  49963. defines.push("#define CLIPPLANE");
  49964. }
  49965. if (this._isAnimationSheetEnabled) {
  49966. defines.push("#define ANIMATESHEET");
  49967. }
  49968. // Effect
  49969. var join = defines.join("\n");
  49970. if (this._cachedDefines !== join) {
  49971. this._cachedDefines = join;
  49972. var attributesNamesOrOptions;
  49973. var effectCreationOption;
  49974. if (this._isAnimationSheetEnabled) {
  49975. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  49976. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  49977. }
  49978. else {
  49979. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  49980. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  49981. }
  49982. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  49983. }
  49984. return this._effect;
  49985. };
  49986. /**
  49987. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  49988. */
  49989. ParticleSystem.prototype.animate = function () {
  49990. if (!this._started)
  49991. return;
  49992. var effect = this._getEffect();
  49993. // Check
  49994. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  49995. return;
  49996. if (this._currentRenderId === this._scene.getRenderId()) {
  49997. return;
  49998. }
  49999. this._currentRenderId = this._scene.getRenderId();
  50000. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50001. // determine the number of particles we need to create
  50002. var newParticles;
  50003. if (this.manualEmitCount > -1) {
  50004. newParticles = this.manualEmitCount;
  50005. this._newPartsExcess = 0;
  50006. this.manualEmitCount = 0;
  50007. }
  50008. else {
  50009. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50010. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50011. }
  50012. if (this._newPartsExcess > 1.0) {
  50013. newParticles += this._newPartsExcess >> 0;
  50014. this._newPartsExcess -= this._newPartsExcess >> 0;
  50015. }
  50016. this._alive = false;
  50017. if (!this._stopped) {
  50018. this._actualFrame += this._scaledUpdateSpeed;
  50019. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50020. this.stop();
  50021. }
  50022. else {
  50023. newParticles = 0;
  50024. }
  50025. this._update(newParticles);
  50026. // Stopped?
  50027. if (this._stopped) {
  50028. if (!this._alive) {
  50029. this._started = false;
  50030. if (this.onAnimationEnd) {
  50031. this.onAnimationEnd();
  50032. }
  50033. if (this.disposeOnStop) {
  50034. this._scene._toBeDisposed.push(this);
  50035. }
  50036. }
  50037. }
  50038. // Animation sheet
  50039. if (this._isAnimationSheetEnabled) {
  50040. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50041. }
  50042. else {
  50043. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50044. }
  50045. // Update VBO
  50046. var offset = 0;
  50047. for (var index = 0; index < this._particles.length; index++) {
  50048. var particle = this._particles[index];
  50049. this._appendParticleVertexes(offset, particle);
  50050. offset += 4;
  50051. }
  50052. if (this._vertexBuffer) {
  50053. this._vertexBuffer.update(this._vertexData);
  50054. }
  50055. };
  50056. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50057. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50058. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50059. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50060. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50061. };
  50062. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50063. this._appendParticleVertex(offset++, particle, 0, 0);
  50064. this._appendParticleVertex(offset++, particle, 1, 0);
  50065. this._appendParticleVertex(offset++, particle, 1, 1);
  50066. this._appendParticleVertex(offset++, particle, 0, 1);
  50067. };
  50068. /**
  50069. * Rebuilds the particle system.
  50070. */
  50071. ParticleSystem.prototype.rebuild = function () {
  50072. this._createIndexBuffer();
  50073. if (this._vertexBuffer) {
  50074. this._vertexBuffer._rebuild();
  50075. }
  50076. };
  50077. /**
  50078. * Renders the particle system in its current state.
  50079. * @returns the current number of particles.
  50080. */
  50081. ParticleSystem.prototype.render = function () {
  50082. var effect = this._getEffect();
  50083. // Check
  50084. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50085. return 0;
  50086. var engine = this._scene.getEngine();
  50087. // Render
  50088. engine.enableEffect(effect);
  50089. engine.setState(false);
  50090. var viewMatrix = this._scene.getViewMatrix();
  50091. effect.setTexture("diffuseSampler", this.particleTexture);
  50092. effect.setMatrix("view", viewMatrix);
  50093. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50094. if (this._isAnimationSheetEnabled) {
  50095. var baseSize = this.particleTexture.getBaseSize();
  50096. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50097. }
  50098. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50099. if (this._scene.clipPlane) {
  50100. var clipPlane = this._scene.clipPlane;
  50101. var invView = viewMatrix.clone();
  50102. invView.invert();
  50103. effect.setMatrix("invView", invView);
  50104. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50105. }
  50106. // VBOs
  50107. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50108. // Draw order
  50109. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50110. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50111. }
  50112. else {
  50113. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50114. }
  50115. if (this.forceDepthWrite) {
  50116. engine.setDepthWrite(true);
  50117. }
  50118. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50119. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50120. return this._particles.length;
  50121. };
  50122. /**
  50123. * Disposes the particle system and free the associated resources.
  50124. */
  50125. ParticleSystem.prototype.dispose = function () {
  50126. if (this._vertexBuffer) {
  50127. this._vertexBuffer.dispose();
  50128. this._vertexBuffer = null;
  50129. }
  50130. if (this._indexBuffer) {
  50131. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50132. this._indexBuffer = null;
  50133. }
  50134. if (this.particleTexture) {
  50135. this.particleTexture.dispose();
  50136. this.particleTexture = null;
  50137. }
  50138. // Remove from scene
  50139. var index = this._scene.particleSystems.indexOf(this);
  50140. if (index > -1) {
  50141. this._scene.particleSystems.splice(index, 1);
  50142. }
  50143. // Callback
  50144. this.onDisposeObservable.notifyObservers(this);
  50145. this.onDisposeObservable.clear();
  50146. };
  50147. /**
  50148. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50149. * @param radius The radius of the sphere to emit from
  50150. * @returns the emitter
  50151. */
  50152. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50153. if (radius === void 0) { radius = 1; }
  50154. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50155. this.particleEmitterType = particleEmitter;
  50156. return particleEmitter;
  50157. };
  50158. /**
  50159. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50160. * @param radius The radius of the sphere to emit from
  50161. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50162. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50163. * @returns the emitter
  50164. */
  50165. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50166. if (radius === void 0) { radius = 1; }
  50167. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50168. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50169. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50170. this.particleEmitterType = particleEmitter;
  50171. return particleEmitter;
  50172. };
  50173. /**
  50174. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50175. * @param radius The radius of the cone to emit from
  50176. * @param angle The base angle of the cone
  50177. * @returns the emitter
  50178. */
  50179. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50180. if (radius === void 0) { radius = 1; }
  50181. if (angle === void 0) { angle = Math.PI / 4; }
  50182. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50183. this.particleEmitterType = particleEmitter;
  50184. return particleEmitter;
  50185. };
  50186. // 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.
  50187. /**
  50188. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50189. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50190. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50191. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50192. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50193. * @returns the emitter
  50194. */
  50195. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50196. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50197. this.direction1 = direction1;
  50198. this.direction2 = direction2;
  50199. this.minEmitBox = minEmitBox;
  50200. this.maxEmitBox = maxEmitBox;
  50201. this.particleEmitterType = particleEmitter;
  50202. return particleEmitter;
  50203. };
  50204. /**
  50205. * Clones the particle system.
  50206. * @param name The name of the cloned object
  50207. * @param newEmitter The new emitter to use
  50208. * @returns the cloned particle system
  50209. */
  50210. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50211. var custom = null;
  50212. var program = null;
  50213. if (this.customShader != null) {
  50214. program = this.customShader;
  50215. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50216. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50217. }
  50218. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50219. result.customShader = program;
  50220. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50221. if (newEmitter === undefined) {
  50222. newEmitter = this.emitter;
  50223. }
  50224. result.emitter = newEmitter;
  50225. if (this.particleTexture) {
  50226. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50227. }
  50228. if (!this.preventAutoStart) {
  50229. result.start();
  50230. }
  50231. return result;
  50232. };
  50233. /**
  50234. * Serializes the particle system to a JSON object.
  50235. * @returns the JSON object
  50236. */
  50237. ParticleSystem.prototype.serialize = function () {
  50238. var serializationObject = {};
  50239. serializationObject.name = this.name;
  50240. serializationObject.id = this.id;
  50241. // Emitter
  50242. if (this.emitter.position) {
  50243. var emitterMesh = this.emitter;
  50244. serializationObject.emitterId = emitterMesh.id;
  50245. }
  50246. else {
  50247. var emitterPosition = this.emitter;
  50248. serializationObject.emitter = emitterPosition.asArray();
  50249. }
  50250. serializationObject.capacity = this.getCapacity();
  50251. if (this.particleTexture) {
  50252. serializationObject.textureName = this.particleTexture.name;
  50253. }
  50254. // Animations
  50255. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50256. // Particle system
  50257. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50258. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50259. serializationObject.minSize = this.minSize;
  50260. serializationObject.maxSize = this.maxSize;
  50261. serializationObject.minEmitPower = this.minEmitPower;
  50262. serializationObject.maxEmitPower = this.maxEmitPower;
  50263. serializationObject.minLifeTime = this.minLifeTime;
  50264. serializationObject.maxLifeTime = this.maxLifeTime;
  50265. serializationObject.emitRate = this.emitRate;
  50266. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50267. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50268. serializationObject.gravity = this.gravity.asArray();
  50269. serializationObject.direction1 = this.direction1.asArray();
  50270. serializationObject.direction2 = this.direction2.asArray();
  50271. serializationObject.color1 = this.color1.asArray();
  50272. serializationObject.color2 = this.color2.asArray();
  50273. serializationObject.colorDead = this.colorDead.asArray();
  50274. serializationObject.updateSpeed = this.updateSpeed;
  50275. serializationObject.targetStopDuration = this.targetStopDuration;
  50276. serializationObject.textureMask = this.textureMask.asArray();
  50277. serializationObject.blendMode = this.blendMode;
  50278. serializationObject.customShader = this.customShader;
  50279. serializationObject.preventAutoStart = this.preventAutoStart;
  50280. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50281. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50282. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50283. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50284. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50285. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50286. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50287. return serializationObject;
  50288. };
  50289. /**
  50290. * Parses a JSON object to create a particle system.
  50291. * @param parsedParticleSystem The JSON object to parse
  50292. * @param scene The scene to create the particle system in
  50293. * @param rootUrl The root url to use to load external dependencies like texture
  50294. * @returns the Parsed particle system
  50295. */
  50296. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50297. var name = parsedParticleSystem.name;
  50298. var custom = null;
  50299. var program = null;
  50300. if (parsedParticleSystem.customShader) {
  50301. program = parsedParticleSystem.customShader;
  50302. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50303. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50304. }
  50305. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50306. particleSystem.customShader = program;
  50307. if (parsedParticleSystem.id) {
  50308. particleSystem.id = parsedParticleSystem.id;
  50309. }
  50310. // Auto start
  50311. if (parsedParticleSystem.preventAutoStart) {
  50312. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50313. }
  50314. // Texture
  50315. if (parsedParticleSystem.textureName) {
  50316. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50317. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50318. }
  50319. // Emitter
  50320. if (parsedParticleSystem.emitterId) {
  50321. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50322. }
  50323. else {
  50324. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50325. }
  50326. // Animations
  50327. if (parsedParticleSystem.animations) {
  50328. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50329. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50330. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50331. }
  50332. }
  50333. if (parsedParticleSystem.autoAnimate) {
  50334. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50335. }
  50336. // Particle system
  50337. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50338. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50339. particleSystem.minSize = parsedParticleSystem.minSize;
  50340. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50341. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50342. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50343. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50344. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50345. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50346. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50347. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50348. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50349. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50350. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50351. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50352. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50353. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50354. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50355. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50356. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50357. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50358. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50359. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50360. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50361. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50362. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50363. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50364. if (!particleSystem.preventAutoStart) {
  50365. particleSystem.start();
  50366. }
  50367. return particleSystem;
  50368. };
  50369. /**
  50370. * Source color is added to the destination color without alpha affecting the result.
  50371. */
  50372. ParticleSystem.BLENDMODE_ONEONE = 0;
  50373. /**
  50374. * Blend current color and particle color using particle’s alpha.
  50375. */
  50376. ParticleSystem.BLENDMODE_STANDARD = 1;
  50377. return ParticleSystem;
  50378. }());
  50379. BABYLON.ParticleSystem = ParticleSystem;
  50380. })(BABYLON || (BABYLON = {}));
  50381. //# sourceMappingURL=babylon.particleSystem.js.map
  50382. var BABYLON;
  50383. (function (BABYLON) {
  50384. /**
  50385. * Particle emitter emitting particles from the inside of a box.
  50386. * It emits the particles randomly between 2 given directions.
  50387. */
  50388. var BoxParticleEmitter = /** @class */ (function () {
  50389. // to be updated like the rest of emitters when breaking changes.
  50390. // all property should be come public variables and passed through constructor.
  50391. /**
  50392. * Creates a new instance of @see BoxParticleEmitter
  50393. * @param _particleSystem the particle system associated with the emitter
  50394. */
  50395. function BoxParticleEmitter(_particleSystem) {
  50396. this._particleSystem = _particleSystem;
  50397. }
  50398. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50399. /**
  50400. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50401. */
  50402. get: function () {
  50403. return this._particleSystem.direction1;
  50404. },
  50405. /**
  50406. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50407. */
  50408. set: function (value) {
  50409. this._particleSystem.direction1 = value;
  50410. },
  50411. enumerable: true,
  50412. configurable: true
  50413. });
  50414. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50415. /**
  50416. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50417. */
  50418. get: function () {
  50419. return this._particleSystem.direction2;
  50420. },
  50421. /**
  50422. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50423. */
  50424. set: function (value) {
  50425. this._particleSystem.direction2 = value;
  50426. },
  50427. enumerable: true,
  50428. configurable: true
  50429. });
  50430. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50431. /**
  50432. * 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.
  50433. */
  50434. get: function () {
  50435. return this._particleSystem.minEmitBox;
  50436. },
  50437. /**
  50438. * 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.
  50439. */
  50440. set: function (value) {
  50441. this._particleSystem.minEmitBox = value;
  50442. },
  50443. enumerable: true,
  50444. configurable: true
  50445. });
  50446. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50447. /**
  50448. * 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.
  50449. */
  50450. get: function () {
  50451. return this._particleSystem.maxEmitBox;
  50452. },
  50453. /**
  50454. * 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.
  50455. */
  50456. set: function (value) {
  50457. this._particleSystem.maxEmitBox = value;
  50458. },
  50459. enumerable: true,
  50460. configurable: true
  50461. });
  50462. /**
  50463. * Called by the particle System when the direction is computed for the created particle.
  50464. * @param emitPower is the power of the particle (speed)
  50465. * @param worldMatrix is the world matrix of the particle system
  50466. * @param directionToUpdate is the direction vector to update with the result
  50467. * @param particle is the particle we are computed the direction for
  50468. */
  50469. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50470. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50471. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50472. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50473. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50474. };
  50475. /**
  50476. * Called by the particle System when the position is computed for the created particle.
  50477. * @param worldMatrix is the world matrix of the particle system
  50478. * @param positionToUpdate is the position vector to update with the result
  50479. * @param particle is the particle we are computed the position for
  50480. */
  50481. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50482. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50483. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50484. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50485. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50486. };
  50487. /**
  50488. * Clones the current emitter and returns a copy of it
  50489. * @returns the new emitter
  50490. */
  50491. BoxParticleEmitter.prototype.clone = function () {
  50492. var newOne = new BoxParticleEmitter(this._particleSystem);
  50493. BABYLON.Tools.DeepCopy(this, newOne);
  50494. return newOne;
  50495. };
  50496. return BoxParticleEmitter;
  50497. }());
  50498. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50499. })(BABYLON || (BABYLON = {}));
  50500. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50501. var BABYLON;
  50502. (function (BABYLON) {
  50503. /**
  50504. * Particle emitter emitting particles from the inside of a cone.
  50505. * It emits the particles alongside the cone volume from the base to the particle.
  50506. * The emission direction might be randomized.
  50507. */
  50508. var ConeParticleEmitter = /** @class */ (function () {
  50509. /**
  50510. * Creates a new instance of @see ConeParticleEmitter
  50511. * @param radius the radius of the emission cone
  50512. * @param angles the cone base angle
  50513. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50514. */
  50515. function ConeParticleEmitter(radius,
  50516. /**
  50517. * The radius of the emission cone.
  50518. */
  50519. angle,
  50520. /**
  50521. * The cone base angle.
  50522. */
  50523. directionRandomizer) {
  50524. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50525. this.angle = angle;
  50526. this.directionRandomizer = directionRandomizer;
  50527. this.radius = radius;
  50528. }
  50529. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50530. /**
  50531. * Gets the radius of the emission cone.
  50532. */
  50533. get: function () {
  50534. return this._radius;
  50535. },
  50536. /**
  50537. * Sets the radius of the emission cone.
  50538. */
  50539. set: function (value) {
  50540. this._radius = value;
  50541. if (this.angle !== 0) {
  50542. this._height = value / Math.tan(this.angle / 2);
  50543. }
  50544. else {
  50545. this._height = 1;
  50546. }
  50547. },
  50548. enumerable: true,
  50549. configurable: true
  50550. });
  50551. /**
  50552. * Called by the particle System when the direction is computed for the created particle.
  50553. * @param emitPower is the power of the particle (speed)
  50554. * @param worldMatrix is the world matrix of the particle system
  50555. * @param directionToUpdate is the direction vector to update with the result
  50556. * @param particle is the particle we are computed the direction for
  50557. */
  50558. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50559. if (this.angle === 0) {
  50560. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50561. }
  50562. else {
  50563. // measure the direction Vector from the emitter to the particle.
  50564. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50565. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50566. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50567. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50568. direction.x += randX;
  50569. direction.y += randY;
  50570. direction.z += randZ;
  50571. direction.normalize();
  50572. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50573. }
  50574. };
  50575. /**
  50576. * Called by the particle System when the position is computed for the created particle.
  50577. * @param worldMatrix is the world matrix of the particle system
  50578. * @param positionToUpdate is the position vector to update with the result
  50579. * @param particle is the particle we are computed the position for
  50580. */
  50581. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50582. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50583. var h = BABYLON.Scalar.RandomRange(0, 1);
  50584. // Better distribution in a cone at normal angles.
  50585. h = 1 - h * h;
  50586. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50587. radius = radius * h / this._height;
  50588. var randX = radius * Math.sin(s);
  50589. var randZ = radius * Math.cos(s);
  50590. var randY = h;
  50591. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50592. };
  50593. /**
  50594. * Clones the current emitter and returns a copy of it
  50595. * @returns the new emitter
  50596. */
  50597. ConeParticleEmitter.prototype.clone = function () {
  50598. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50599. BABYLON.Tools.DeepCopy(this, newOne);
  50600. return newOne;
  50601. };
  50602. return ConeParticleEmitter;
  50603. }());
  50604. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50605. })(BABYLON || (BABYLON = {}));
  50606. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50607. var BABYLON;
  50608. (function (BABYLON) {
  50609. /**
  50610. * Particle emitter emitting particles from the inside of a sphere.
  50611. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50612. */
  50613. var SphereParticleEmitter = /** @class */ (function () {
  50614. /**
  50615. * Creates a new instance of @see SphereParticleEmitter
  50616. * @param radius the radius of the emission sphere
  50617. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50618. */
  50619. function SphereParticleEmitter(
  50620. /**
  50621. * The radius of the emission sphere.
  50622. */
  50623. radius,
  50624. /**
  50625. * How much to randomize the particle direction [0-1].
  50626. */
  50627. directionRandomizer) {
  50628. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50629. this.radius = radius;
  50630. this.directionRandomizer = directionRandomizer;
  50631. }
  50632. /**
  50633. * Called by the particle System when the direction is computed for the created particle.
  50634. * @param emitPower is the power of the particle (speed)
  50635. * @param worldMatrix is the world matrix of the particle system
  50636. * @param directionToUpdate is the direction vector to update with the result
  50637. * @param particle is the particle we are computed the direction for
  50638. */
  50639. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50640. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50641. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50642. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50643. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50644. direction.x += randX;
  50645. direction.y += randY;
  50646. direction.z += randZ;
  50647. direction.normalize();
  50648. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50649. };
  50650. /**
  50651. * Called by the particle System when the position is computed for the created particle.
  50652. * @param worldMatrix is the world matrix of the particle system
  50653. * @param positionToUpdate is the position vector to update with the result
  50654. * @param particle is the particle we are computed the position for
  50655. */
  50656. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50657. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  50658. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  50659. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  50660. var randY = this.radius * Math.cos(theta);
  50661. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  50662. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50663. };
  50664. /**
  50665. * Clones the current emitter and returns a copy of it
  50666. * @returns the new emitter
  50667. */
  50668. SphereParticleEmitter.prototype.clone = function () {
  50669. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  50670. BABYLON.Tools.DeepCopy(this, newOne);
  50671. return newOne;
  50672. };
  50673. return SphereParticleEmitter;
  50674. }());
  50675. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  50676. /**
  50677. * Particle emitter emitting particles from the inside of a sphere.
  50678. * It emits the particles randomly between two vectors.
  50679. */
  50680. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  50681. __extends(SphereDirectedParticleEmitter, _super);
  50682. /**
  50683. * Creates a new instance of @see SphereDirectedParticleEmitter
  50684. * @param radius the radius of the emission sphere
  50685. * @param direction1 the min limit of the emission direction
  50686. * @param direction2 the max limit of the emission direction
  50687. */
  50688. function SphereDirectedParticleEmitter(radius,
  50689. /**
  50690. * The min limit of the emission direction.
  50691. */
  50692. direction1,
  50693. /**
  50694. * The max limit of the emission direction.
  50695. */
  50696. direction2) {
  50697. var _this = _super.call(this, radius) || this;
  50698. _this.direction1 = direction1;
  50699. _this.direction2 = direction2;
  50700. return _this;
  50701. }
  50702. /**
  50703. * Called by the particle System when the direction is computed for the created particle.
  50704. * @param emitPower is the power of the particle (speed)
  50705. * @param worldMatrix is the world matrix of the particle system
  50706. * @param directionToUpdate is the direction vector to update with the result
  50707. * @param particle is the particle we are computed the direction for
  50708. */
  50709. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50710. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50711. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50712. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50713. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50714. };
  50715. /**
  50716. * Clones the current emitter and returns a copy of it
  50717. * @returns the new emitter
  50718. */
  50719. SphereDirectedParticleEmitter.prototype.clone = function () {
  50720. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  50721. BABYLON.Tools.DeepCopy(this, newOne);
  50722. return newOne;
  50723. };
  50724. return SphereDirectedParticleEmitter;
  50725. }(SphereParticleEmitter));
  50726. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  50727. })(BABYLON || (BABYLON = {}));
  50728. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  50729. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  50730. var BABYLON;
  50731. (function (BABYLON) {
  50732. /**
  50733. * Represents one particle of a solid particle system.
  50734. * @see SolidParticleSystem
  50735. */
  50736. var SolidParticle = /** @class */ (function () {
  50737. /**
  50738. * Creates a Solid Particle object.
  50739. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  50740. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  50741. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  50742. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  50743. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  50744. * @param shapeId (integer) is the model shape identifier in the SPS.
  50745. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  50746. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  50747. */
  50748. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  50749. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  50750. /**
  50751. * particle global index
  50752. */
  50753. this.idx = 0;
  50754. /**
  50755. * The color of the particle
  50756. */
  50757. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50758. /**
  50759. * The world space position of the particle.
  50760. */
  50761. this.position = BABYLON.Vector3.Zero();
  50762. /**
  50763. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  50764. */
  50765. this.rotation = BABYLON.Vector3.Zero();
  50766. /**
  50767. * The scaling of the particle.
  50768. */
  50769. this.scaling = BABYLON.Vector3.One();
  50770. /**
  50771. * The uvs of the particle.
  50772. */
  50773. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  50774. /**
  50775. * The current speed of the particle.
  50776. */
  50777. this.velocity = BABYLON.Vector3.Zero();
  50778. /**
  50779. * The pivot point in the particle local space.
  50780. */
  50781. this.pivot = BABYLON.Vector3.Zero();
  50782. /**
  50783. * Must the particle be translated from its pivot point in its local space ?
  50784. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  50785. * Default : false
  50786. */
  50787. this.translateFromPivot = false;
  50788. /**
  50789. * Is the particle active or not ?
  50790. */
  50791. this.alive = true;
  50792. /**
  50793. * Is the particle visible or not ?
  50794. */
  50795. this.isVisible = true;
  50796. /**
  50797. * Index of this particle in the global "positions" array (Internal use)
  50798. */
  50799. this._pos = 0;
  50800. /**
  50801. * Index of this particle in the global "indices" array (Internal use)
  50802. */
  50803. this._ind = 0;
  50804. /**
  50805. * ModelShape id of this particle
  50806. */
  50807. this.shapeId = 0;
  50808. /**
  50809. * Index of the particle in its shape id (Internal use)
  50810. */
  50811. this.idxInShape = 0;
  50812. /**
  50813. * Still set as invisible in order to skip useless computations (Internal use)
  50814. */
  50815. this._stillInvisible = false;
  50816. /**
  50817. * Last computed particle rotation matrix
  50818. */
  50819. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  50820. this.idx = particleIndex;
  50821. this._pos = positionIndex;
  50822. this._ind = indiceIndex;
  50823. this._model = model;
  50824. this.shapeId = shapeId;
  50825. this.idxInShape = idxInShape;
  50826. this._sps = sps;
  50827. if (modelBoundingInfo) {
  50828. this._modelBoundingInfo = modelBoundingInfo;
  50829. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  50830. }
  50831. }
  50832. Object.defineProperty(SolidParticle.prototype, "scale", {
  50833. /**
  50834. * Legacy support, changed scale to scaling
  50835. */
  50836. get: function () {
  50837. return this.scaling;
  50838. },
  50839. /**
  50840. * Legacy support, changed scale to scaling
  50841. */
  50842. set: function (scale) {
  50843. this.scaling = scale;
  50844. },
  50845. enumerable: true,
  50846. configurable: true
  50847. });
  50848. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  50849. /**
  50850. * Legacy support, changed quaternion to rotationQuaternion
  50851. */
  50852. get: function () {
  50853. return this.rotationQuaternion;
  50854. },
  50855. /**
  50856. * Legacy support, changed quaternion to rotationQuaternion
  50857. */
  50858. set: function (q) {
  50859. this.rotationQuaternion = q;
  50860. },
  50861. enumerable: true,
  50862. configurable: true
  50863. });
  50864. /**
  50865. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  50866. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  50867. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  50868. * @returns true if it intersects
  50869. */
  50870. SolidParticle.prototype.intersectsMesh = function (target) {
  50871. if (!this._boundingInfo || !target._boundingInfo) {
  50872. return false;
  50873. }
  50874. if (this._sps._bSphereOnly) {
  50875. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  50876. }
  50877. return this._boundingInfo.intersects(target._boundingInfo, false);
  50878. };
  50879. return SolidParticle;
  50880. }());
  50881. BABYLON.SolidParticle = SolidParticle;
  50882. /**
  50883. * Represents the shape of the model used by one particle of a solid particle system.
  50884. * SPS internal tool, don't use it manually.
  50885. * @see SolidParticleSystem
  50886. */
  50887. var ModelShape = /** @class */ (function () {
  50888. /**
  50889. * 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.
  50890. * SPS internal tool, don't use it manually.
  50891. * @ignore
  50892. */
  50893. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  50894. /**
  50895. * length of the shape in the model indices array (internal use)
  50896. */
  50897. this._indicesLength = 0;
  50898. this.shapeID = id;
  50899. this._shape = shape;
  50900. this._indicesLength = indicesLength;
  50901. this._shapeUV = shapeUV;
  50902. this._positionFunction = posFunction;
  50903. this._vertexFunction = vtxFunction;
  50904. }
  50905. return ModelShape;
  50906. }());
  50907. BABYLON.ModelShape = ModelShape;
  50908. /**
  50909. * Represents a Depth Sorted Particle in the solid particle system.
  50910. * @see SolidParticleSystem
  50911. */
  50912. var DepthSortedParticle = /** @class */ (function () {
  50913. function DepthSortedParticle() {
  50914. /**
  50915. * Index of the particle in the "indices" array
  50916. */
  50917. this.ind = 0;
  50918. /**
  50919. * Length of the particle shape in the "indices" array
  50920. */
  50921. this.indicesLength = 0;
  50922. /**
  50923. * Squared distance from the particle to the camera
  50924. */
  50925. this.sqDistance = 0.0;
  50926. }
  50927. return DepthSortedParticle;
  50928. }());
  50929. BABYLON.DepthSortedParticle = DepthSortedParticle;
  50930. })(BABYLON || (BABYLON = {}));
  50931. //# sourceMappingURL=babylon.solidParticle.js.map
  50932. var BABYLON;
  50933. (function (BABYLON) {
  50934. /**
  50935. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  50936. *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.
  50937. * The SPS is also a particle system. It provides some methods to manage the particles.
  50938. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  50939. *
  50940. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  50941. */
  50942. var SolidParticleSystem = /** @class */ (function () {
  50943. /**
  50944. * Creates a SPS (Solid Particle System) object.
  50945. * @param name (String) is the SPS name, this will be the underlying mesh name.
  50946. * @param scene (Scene) is the scene in which the SPS is added.
  50947. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  50948. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  50949. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  50950. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  50951. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  50952. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  50953. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  50954. */
  50955. function SolidParticleSystem(name, scene, options) {
  50956. /**
  50957. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  50958. * Example : var p = SPS.particles[i];
  50959. */
  50960. this.particles = new Array();
  50961. /**
  50962. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  50963. */
  50964. this.nbParticles = 0;
  50965. /**
  50966. * If the particles must ever face the camera (default false). Useful for planar particles.
  50967. */
  50968. this.billboard = false;
  50969. /**
  50970. * Recompute normals when adding a shape
  50971. */
  50972. this.recomputeNormals = true;
  50973. /**
  50974. * This a counter ofr your own usage. It's not set by any SPS functions.
  50975. */
  50976. this.counter = 0;
  50977. /**
  50978. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  50979. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  50980. */
  50981. this.vars = {};
  50982. /**
  50983. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  50984. */
  50985. this._bSphereOnly = false;
  50986. /**
  50987. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  50988. */
  50989. this._bSphereRadiusFactor = 1.0;
  50990. this._positions = new Array();
  50991. this._indices = new Array();
  50992. this._normals = new Array();
  50993. this._colors = new Array();
  50994. this._uvs = new Array();
  50995. this._index = 0; // indices index
  50996. this._updatable = true;
  50997. this._pickable = false;
  50998. this._isVisibilityBoxLocked = false;
  50999. this._alwaysVisible = false;
  51000. this._depthSort = false;
  51001. this._shapeCounter = 0;
  51002. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51003. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51004. this._computeParticleColor = true;
  51005. this._computeParticleTexture = true;
  51006. this._computeParticleRotation = true;
  51007. this._computeParticleVertex = false;
  51008. this._computeBoundingBox = false;
  51009. this._depthSortParticles = true;
  51010. this._cam_axisZ = BABYLON.Vector3.Zero();
  51011. this._cam_axisY = BABYLON.Vector3.Zero();
  51012. this._cam_axisX = BABYLON.Vector3.Zero();
  51013. this._axisZ = BABYLON.Axis.Z;
  51014. this._camDir = BABYLON.Vector3.Zero();
  51015. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51016. this._rotMatrix = new BABYLON.Matrix();
  51017. this._invertMatrix = new BABYLON.Matrix();
  51018. this._rotated = BABYLON.Vector3.Zero();
  51019. this._quaternion = new BABYLON.Quaternion();
  51020. this._vertex = BABYLON.Vector3.Zero();
  51021. this._normal = BABYLON.Vector3.Zero();
  51022. this._yaw = 0.0;
  51023. this._pitch = 0.0;
  51024. this._roll = 0.0;
  51025. this._halfroll = 0.0;
  51026. this._halfpitch = 0.0;
  51027. this._halfyaw = 0.0;
  51028. this._sinRoll = 0.0;
  51029. this._cosRoll = 0.0;
  51030. this._sinPitch = 0.0;
  51031. this._cosPitch = 0.0;
  51032. this._sinYaw = 0.0;
  51033. this._cosYaw = 0.0;
  51034. this._mustUnrotateFixedNormals = false;
  51035. this._minimum = BABYLON.Tmp.Vector3[0];
  51036. this._maximum = BABYLON.Tmp.Vector3[1];
  51037. this._minBbox = BABYLON.Tmp.Vector3[4];
  51038. this._maxBbox = BABYLON.Tmp.Vector3[5];
  51039. this._particlesIntersect = false;
  51040. this._depthSortFunction = function (p1, p2) {
  51041. return (p2.sqDistance - p1.sqDistance);
  51042. };
  51043. this._needs32Bits = false;
  51044. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51045. this.name = name;
  51046. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51047. this._camera = scene.activeCamera;
  51048. this._pickable = options ? options.isPickable : false;
  51049. this._depthSort = options ? options.enableDepthSort : false;
  51050. this._particlesIntersect = options ? options.particleIntersection : false;
  51051. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51052. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51053. if (options && options.updatable) {
  51054. this._updatable = options.updatable;
  51055. }
  51056. else {
  51057. this._updatable = true;
  51058. }
  51059. if (this._pickable) {
  51060. this.pickedParticles = [];
  51061. }
  51062. if (this._depthSort) {
  51063. this.depthSortedParticles = [];
  51064. }
  51065. }
  51066. /**
  51067. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51068. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51069. * @returns the created mesh
  51070. */
  51071. SolidParticleSystem.prototype.buildMesh = function () {
  51072. if (this.nbParticles === 0) {
  51073. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51074. this.addShape(triangle, 1);
  51075. triangle.dispose();
  51076. }
  51077. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51078. this._positions32 = new Float32Array(this._positions);
  51079. this._uvs32 = new Float32Array(this._uvs);
  51080. this._colors32 = new Float32Array(this._colors);
  51081. if (this.recomputeNormals) {
  51082. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51083. }
  51084. this._normals32 = new Float32Array(this._normals);
  51085. this._fixedNormal32 = new Float32Array(this._normals);
  51086. if (this._mustUnrotateFixedNormals) {
  51087. this._unrotateFixedNormals();
  51088. }
  51089. var vertexData = new BABYLON.VertexData();
  51090. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51091. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51092. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51093. if (this._uvs32) {
  51094. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51095. ;
  51096. }
  51097. if (this._colors32) {
  51098. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51099. }
  51100. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51101. vertexData.applyToMesh(mesh, this._updatable);
  51102. this.mesh = mesh;
  51103. this.mesh.isPickable = this._pickable;
  51104. // free memory
  51105. if (!this._depthSort) {
  51106. this._indices = null;
  51107. }
  51108. this._positions = null;
  51109. this._normals = null;
  51110. this._uvs = null;
  51111. this._colors = null;
  51112. if (!this._updatable) {
  51113. this.particles.length = 0;
  51114. }
  51115. return mesh;
  51116. };
  51117. /**
  51118. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51119. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51120. * Thus the particles generated from `digest()` have their property `position` set yet.
  51121. * @param mesh ( Mesh ) is the mesh to be digested
  51122. * @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
  51123. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51124. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51125. * @returns the current SPS
  51126. */
  51127. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51128. var size = (options && options.facetNb) || 1;
  51129. var number = (options && options.number) || 0;
  51130. var delta = (options && options.delta) || 0;
  51131. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51132. var meshInd = mesh.getIndices();
  51133. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51134. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51135. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51136. var f = 0; // facet counter
  51137. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51138. // compute size from number
  51139. if (number) {
  51140. number = (number > totalFacets) ? totalFacets : number;
  51141. size = Math.round(totalFacets / number);
  51142. delta = 0;
  51143. }
  51144. else {
  51145. size = (size > totalFacets) ? totalFacets : size;
  51146. }
  51147. var facetPos = []; // submesh positions
  51148. var facetInd = []; // submesh indices
  51149. var facetUV = []; // submesh UV
  51150. var facetCol = []; // submesh colors
  51151. var barycenter = BABYLON.Tmp.Vector3[0];
  51152. var sizeO = size;
  51153. while (f < totalFacets) {
  51154. size = sizeO + Math.floor((1 + delta) * Math.random());
  51155. if (f > totalFacets - size) {
  51156. size = totalFacets - f;
  51157. }
  51158. // reset temp arrays
  51159. facetPos.length = 0;
  51160. facetInd.length = 0;
  51161. facetUV.length = 0;
  51162. facetCol.length = 0;
  51163. // iterate over "size" facets
  51164. var fi = 0;
  51165. for (var j = f * 3; j < (f + size) * 3; j++) {
  51166. facetInd.push(fi);
  51167. var i = meshInd[j];
  51168. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51169. if (meshUV) {
  51170. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51171. }
  51172. if (meshCol) {
  51173. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51174. }
  51175. fi++;
  51176. }
  51177. // create a model shape for each single particle
  51178. var idx = this.nbParticles;
  51179. var shape = this._posToShape(facetPos);
  51180. var shapeUV = this._uvsToShapeUV(facetUV);
  51181. // compute the barycenter of the shape
  51182. var v;
  51183. for (v = 0; v < shape.length; v++) {
  51184. barycenter.addInPlace(shape[v]);
  51185. }
  51186. barycenter.scaleInPlace(1 / shape.length);
  51187. // shift the shape from its barycenter to the origin
  51188. for (v = 0; v < shape.length; v++) {
  51189. shape[v].subtractInPlace(barycenter);
  51190. }
  51191. var bInfo;
  51192. if (this._particlesIntersect) {
  51193. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51194. }
  51195. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51196. // add the particle in the SPS
  51197. var currentPos = this._positions.length;
  51198. var currentInd = this._indices.length;
  51199. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51200. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51201. // initialize the particle position
  51202. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51203. this._index += shape.length;
  51204. idx++;
  51205. this.nbParticles++;
  51206. this._shapeCounter++;
  51207. f += size;
  51208. }
  51209. return this;
  51210. };
  51211. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51212. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51213. var index = 0;
  51214. var idx = 0;
  51215. for (var p = 0; p < this.particles.length; p++) {
  51216. this._particle = this.particles[p];
  51217. this._shape = this._particle._model._shape;
  51218. if (this._particle.rotationQuaternion) {
  51219. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51220. }
  51221. else {
  51222. this._yaw = this._particle.rotation.y;
  51223. this._pitch = this._particle.rotation.x;
  51224. this._roll = this._particle.rotation.z;
  51225. this._quaternionRotationYPR();
  51226. }
  51227. this._quaternionToRotationMatrix();
  51228. this._rotMatrix.invertToRef(this._invertMatrix);
  51229. for (var pt = 0; pt < this._shape.length; pt++) {
  51230. idx = index + pt * 3;
  51231. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51232. this._fixedNormal32[idx] = this._normal.x;
  51233. this._fixedNormal32[idx + 1] = this._normal.y;
  51234. this._fixedNormal32[idx + 2] = this._normal.z;
  51235. }
  51236. index = idx + 3;
  51237. }
  51238. };
  51239. //reset copy
  51240. SolidParticleSystem.prototype._resetCopy = function () {
  51241. this._copy.position.x = 0;
  51242. this._copy.position.y = 0;
  51243. this._copy.position.z = 0;
  51244. this._copy.rotation.x = 0;
  51245. this._copy.rotation.y = 0;
  51246. this._copy.rotation.z = 0;
  51247. this._copy.rotationQuaternion = null;
  51248. this._copy.scaling.x = 1.0;
  51249. this._copy.scaling.y = 1.0;
  51250. this._copy.scaling.z = 1.0;
  51251. this._copy.uvs.x = 0;
  51252. this._copy.uvs.y = 0;
  51253. this._copy.uvs.z = 1.0;
  51254. this._copy.uvs.w = 1.0;
  51255. this._copy.color = null;
  51256. this._copy.translateFromPivot = false;
  51257. };
  51258. // _meshBuilder : inserts the shape model in the global SPS mesh
  51259. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51260. var i;
  51261. var u = 0;
  51262. var c = 0;
  51263. var n = 0;
  51264. this._resetCopy();
  51265. if (options && options.positionFunction) {
  51266. options.positionFunction(this._copy, idx, idxInShape);
  51267. this._mustUnrotateFixedNormals = true;
  51268. }
  51269. if (this._copy.rotationQuaternion) {
  51270. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51271. }
  51272. else {
  51273. this._yaw = this._copy.rotation.y;
  51274. this._pitch = this._copy.rotation.x;
  51275. this._roll = this._copy.rotation.z;
  51276. this._quaternionRotationYPR();
  51277. }
  51278. this._quaternionToRotationMatrix();
  51279. if (this._copy.translateFromPivot) {
  51280. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51281. }
  51282. else {
  51283. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51284. }
  51285. for (i = 0; i < shape.length; i++) {
  51286. this._vertex.x = shape[i].x;
  51287. this._vertex.y = shape[i].y;
  51288. this._vertex.z = shape[i].z;
  51289. if (options && options.vertexFunction) {
  51290. options.vertexFunction(this._copy, this._vertex, i);
  51291. }
  51292. this._vertex.x *= this._copy.scaling.x;
  51293. this._vertex.y *= this._copy.scaling.y;
  51294. this._vertex.z *= this._copy.scaling.z;
  51295. this._vertex.x -= this._copy.pivot.x;
  51296. this._vertex.y -= this._copy.pivot.y;
  51297. this._vertex.z -= this._copy.pivot.z;
  51298. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51299. this._rotated.addInPlace(this._pivotBackTranslation);
  51300. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51301. if (meshUV) {
  51302. 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);
  51303. u += 2;
  51304. }
  51305. if (this._copy.color) {
  51306. this._color = this._copy.color;
  51307. }
  51308. else if (meshCol && meshCol[c] !== undefined) {
  51309. this._color.r = meshCol[c];
  51310. this._color.g = meshCol[c + 1];
  51311. this._color.b = meshCol[c + 2];
  51312. this._color.a = meshCol[c + 3];
  51313. }
  51314. else {
  51315. this._color.r = 1.0;
  51316. this._color.g = 1.0;
  51317. this._color.b = 1.0;
  51318. this._color.a = 1.0;
  51319. }
  51320. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51321. c += 4;
  51322. if (!this.recomputeNormals && meshNor) {
  51323. this._normal.x = meshNor[n];
  51324. this._normal.y = meshNor[n + 1];
  51325. this._normal.z = meshNor[n + 2];
  51326. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51327. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51328. n += 3;
  51329. }
  51330. }
  51331. for (i = 0; i < meshInd.length; i++) {
  51332. var current_ind = p + meshInd[i];
  51333. indices.push(current_ind);
  51334. if (current_ind > 65535) {
  51335. this._needs32Bits = true;
  51336. }
  51337. }
  51338. if (this._pickable) {
  51339. var nbfaces = meshInd.length / 3;
  51340. for (i = 0; i < nbfaces; i++) {
  51341. this.pickedParticles.push({ idx: idx, faceId: i });
  51342. }
  51343. }
  51344. if (this._depthSort) {
  51345. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51346. }
  51347. return this._copy;
  51348. };
  51349. // returns a shape array from positions array
  51350. SolidParticleSystem.prototype._posToShape = function (positions) {
  51351. var shape = [];
  51352. for (var i = 0; i < positions.length; i += 3) {
  51353. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51354. }
  51355. return shape;
  51356. };
  51357. // returns a shapeUV array from a Vector4 uvs
  51358. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51359. var shapeUV = [];
  51360. if (uvs) {
  51361. for (var i = 0; i < uvs.length; i++)
  51362. shapeUV.push(uvs[i]);
  51363. }
  51364. return shapeUV;
  51365. };
  51366. // adds a new particle object in the particles array
  51367. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51368. if (bInfo === void 0) { bInfo = null; }
  51369. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51370. this.particles.push(sp);
  51371. return sp;
  51372. };
  51373. /**
  51374. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51375. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51376. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51377. * @param nb (positive integer) the number of particles to be created from this model
  51378. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51379. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51380. * @returns the number of shapes in the system
  51381. */
  51382. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51383. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51384. var meshInd = mesh.getIndices();
  51385. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51386. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51387. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51388. var bbInfo;
  51389. if (this._particlesIntersect) {
  51390. bbInfo = mesh.getBoundingInfo();
  51391. }
  51392. var shape = this._posToShape(meshPos);
  51393. var shapeUV = this._uvsToShapeUV(meshUV);
  51394. var posfunc = options ? options.positionFunction : null;
  51395. var vtxfunc = options ? options.vertexFunction : null;
  51396. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51397. // particles
  51398. var sp;
  51399. var currentCopy;
  51400. var idx = this.nbParticles;
  51401. for (var i = 0; i < nb; i++) {
  51402. var currentPos = this._positions.length;
  51403. var currentInd = this._indices.length;
  51404. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51405. if (this._updatable) {
  51406. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51407. sp.position.copyFrom(currentCopy.position);
  51408. sp.rotation.copyFrom(currentCopy.rotation);
  51409. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51410. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51411. }
  51412. if (currentCopy.color && sp.color) {
  51413. sp.color.copyFrom(currentCopy.color);
  51414. }
  51415. sp.scaling.copyFrom(currentCopy.scaling);
  51416. sp.uvs.copyFrom(currentCopy.uvs);
  51417. }
  51418. this._index += shape.length;
  51419. idx++;
  51420. }
  51421. this.nbParticles += nb;
  51422. this._shapeCounter++;
  51423. return this._shapeCounter - 1;
  51424. };
  51425. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51426. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51427. this._resetCopy();
  51428. if (particle._model._positionFunction) {
  51429. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51430. }
  51431. if (this._copy.rotationQuaternion) {
  51432. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51433. }
  51434. else {
  51435. this._yaw = this._copy.rotation.y;
  51436. this._pitch = this._copy.rotation.x;
  51437. this._roll = this._copy.rotation.z;
  51438. this._quaternionRotationYPR();
  51439. }
  51440. this._quaternionToRotationMatrix();
  51441. if (this._copy.translateFromPivot) {
  51442. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51443. }
  51444. else {
  51445. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51446. }
  51447. this._shape = particle._model._shape;
  51448. for (var pt = 0; pt < this._shape.length; pt++) {
  51449. this._vertex.x = this._shape[pt].x;
  51450. this._vertex.y = this._shape[pt].y;
  51451. this._vertex.z = this._shape[pt].z;
  51452. if (particle._model._vertexFunction) {
  51453. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51454. }
  51455. this._vertex.x *= this._copy.scaling.x;
  51456. this._vertex.y *= this._copy.scaling.y;
  51457. this._vertex.z *= this._copy.scaling.z;
  51458. this._vertex.x -= this._copy.pivot.x;
  51459. this._vertex.y -= this._copy.pivot.y;
  51460. this._vertex.z -= this._copy.pivot.z;
  51461. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51462. this._rotated.addInPlace(this._pivotBackTranslation);
  51463. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51464. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51465. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51466. }
  51467. particle.position.x = 0.0;
  51468. particle.position.y = 0.0;
  51469. particle.position.z = 0.0;
  51470. particle.rotation.x = 0.0;
  51471. particle.rotation.y = 0.0;
  51472. particle.rotation.z = 0.0;
  51473. particle.rotationQuaternion = null;
  51474. particle.scaling.x = 1.0;
  51475. particle.scaling.y = 1.0;
  51476. particle.scaling.z = 1.0;
  51477. };
  51478. /**
  51479. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51480. * @returns the SPS.
  51481. */
  51482. SolidParticleSystem.prototype.rebuildMesh = function () {
  51483. for (var p = 0; p < this.particles.length; p++) {
  51484. this._rebuildParticle(this.particles[p]);
  51485. }
  51486. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51487. return this;
  51488. };
  51489. /**
  51490. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51491. * This method calls `updateParticle()` for each particle of the SPS.
  51492. * For an animated SPS, it is usually called within the render loop.
  51493. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51494. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51495. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51496. * @returns the SPS.
  51497. */
  51498. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51499. if (start === void 0) { start = 0; }
  51500. if (end === void 0) { end = this.nbParticles - 1; }
  51501. if (update === void 0) { update = true; }
  51502. if (!this._updatable) {
  51503. return this;
  51504. }
  51505. // custom beforeUpdate
  51506. this.beforeUpdateParticles(start, end, update);
  51507. this._cam_axisX.x = 1.0;
  51508. this._cam_axisX.y = 0.0;
  51509. this._cam_axisX.z = 0.0;
  51510. this._cam_axisY.x = 0.0;
  51511. this._cam_axisY.y = 1.0;
  51512. this._cam_axisY.z = 0.0;
  51513. this._cam_axisZ.x = 0.0;
  51514. this._cam_axisZ.y = 0.0;
  51515. this._cam_axisZ.z = 1.0;
  51516. // cases when the World Matrix is to be computed first
  51517. if (this.billboard || this._depthSort) {
  51518. this.mesh.computeWorldMatrix(true);
  51519. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51520. }
  51521. // if the particles will always face the camera
  51522. if (this.billboard) {
  51523. // compute the camera position and un-rotate it by the current mesh rotation
  51524. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51525. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51526. this._cam_axisZ.normalize();
  51527. // same for camera up vector extracted from the cam view matrix
  51528. var view = this._camera.getViewMatrix(true);
  51529. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51530. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51531. this._cam_axisY.normalize();
  51532. this._cam_axisX.normalize();
  51533. }
  51534. // if depthSort, compute the camera global position in the mesh local system
  51535. if (this._depthSort) {
  51536. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  51537. }
  51538. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51539. var idx = 0; // current position index in the global array positions32
  51540. var index = 0; // position start index in the global array positions32 of the current particle
  51541. var colidx = 0; // current color index in the global array colors32
  51542. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  51543. var uvidx = 0; // current uv index in the global array uvs32
  51544. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  51545. var pt = 0; // current index in the particle model shape
  51546. if (this.mesh.isFacetDataEnabled) {
  51547. this._computeBoundingBox = true;
  51548. }
  51549. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  51550. if (this._computeBoundingBox) {
  51551. if (start == 0 && end == this.nbParticles - 1) {
  51552. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  51553. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  51554. }
  51555. else {
  51556. if (this.mesh._boundingInfo) {
  51557. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  51558. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  51559. }
  51560. }
  51561. }
  51562. // particle loop
  51563. index = this.particles[start]._pos;
  51564. var vpos = (index / 3) | 0;
  51565. colorIndex = vpos * 4;
  51566. uvIndex = vpos * 2;
  51567. for (var p = start; p <= end; p++) {
  51568. this._particle = this.particles[p];
  51569. this._shape = this._particle._model._shape;
  51570. this._shapeUV = this._particle._model._shapeUV;
  51571. // call to custom user function to update the particle properties
  51572. this.updateParticle(this._particle);
  51573. // camera-particle distance for depth sorting
  51574. if (this._depthSort && this._depthSortParticles) {
  51575. var dsp = this.depthSortedParticles[p];
  51576. dsp.ind = this._particle._ind;
  51577. dsp.indicesLength = this._particle._model._indicesLength;
  51578. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  51579. }
  51580. // skip the computations for inactive or already invisible particles
  51581. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  51582. // increment indexes for the next particle
  51583. pt = this._shape.length;
  51584. index += pt * 3;
  51585. colorIndex += pt * 4;
  51586. uvIndex += pt * 2;
  51587. continue;
  51588. }
  51589. if (this._particle.isVisible) {
  51590. this._particle._stillInvisible = false; // un-mark permanent invisibility
  51591. // particle rotation matrix
  51592. if (this.billboard) {
  51593. this._particle.rotation.x = 0.0;
  51594. this._particle.rotation.y = 0.0;
  51595. }
  51596. if (this._computeParticleRotation || this.billboard) {
  51597. if (this._particle.rotationQuaternion) {
  51598. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51599. }
  51600. else {
  51601. this._yaw = this._particle.rotation.y;
  51602. this._pitch = this._particle.rotation.x;
  51603. this._roll = this._particle.rotation.z;
  51604. this._quaternionRotationYPR();
  51605. }
  51606. this._quaternionToRotationMatrix();
  51607. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  51608. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  51609. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  51610. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  51611. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  51612. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  51613. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  51614. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  51615. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  51616. }
  51617. if (this._particle.translateFromPivot) {
  51618. this._pivotBackTranslation.x = 0.0;
  51619. this._pivotBackTranslation.y = 0.0;
  51620. this._pivotBackTranslation.z = 0.0;
  51621. }
  51622. else {
  51623. this._pivotBackTranslation.x = this._particle.pivot.x;
  51624. this._pivotBackTranslation.y = this._particle.pivot.y;
  51625. this._pivotBackTranslation.z = this._particle.pivot.z;
  51626. }
  51627. // particle vertex loop
  51628. for (pt = 0; pt < this._shape.length; pt++) {
  51629. idx = index + pt * 3;
  51630. colidx = colorIndex + pt * 4;
  51631. uvidx = uvIndex + pt * 2;
  51632. this._vertex.x = this._shape[pt].x;
  51633. this._vertex.y = this._shape[pt].y;
  51634. this._vertex.z = this._shape[pt].z;
  51635. if (this._computeParticleVertex) {
  51636. this.updateParticleVertex(this._particle, this._vertex, pt);
  51637. }
  51638. // positions
  51639. this._vertex.x *= this._particle.scaling.x;
  51640. this._vertex.y *= this._particle.scaling.y;
  51641. this._vertex.z *= this._particle.scaling.z;
  51642. this._vertex.x -= this._particle.pivot.x;
  51643. this._vertex.y -= this._particle.pivot.y;
  51644. this._vertex.z -= this._particle.pivot.z;
  51645. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51646. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51647. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51648. this._rotated.x += this._pivotBackTranslation.x;
  51649. this._rotated.y += this._pivotBackTranslation.y;
  51650. this._rotated.z += this._pivotBackTranslation.z;
  51651. this._positions32[idx] = 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;
  51652. this._positions32[idx + 1] = 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;
  51653. this._positions32[idx + 2] = 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;
  51654. if (this._computeBoundingBox) {
  51655. if (this._positions32[idx] < this._minimum.x) {
  51656. this._minimum.x = this._positions32[idx];
  51657. }
  51658. if (this._positions32[idx] > this._maximum.x) {
  51659. this._maximum.x = this._positions32[idx];
  51660. }
  51661. if (this._positions32[idx + 1] < this._minimum.y) {
  51662. this._minimum.y = this._positions32[idx + 1];
  51663. }
  51664. if (this._positions32[idx + 1] > this._maximum.y) {
  51665. this._maximum.y = this._positions32[idx + 1];
  51666. }
  51667. if (this._positions32[idx + 2] < this._minimum.z) {
  51668. this._minimum.z = this._positions32[idx + 2];
  51669. }
  51670. if (this._positions32[idx + 2] > this._maximum.z) {
  51671. this._maximum.z = this._positions32[idx + 2];
  51672. }
  51673. }
  51674. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  51675. if (!this._computeParticleVertex) {
  51676. this._normal.x = this._fixedNormal32[idx];
  51677. this._normal.y = this._fixedNormal32[idx + 1];
  51678. this._normal.z = this._fixedNormal32[idx + 2];
  51679. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  51680. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  51681. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  51682. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  51683. 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;
  51684. 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;
  51685. }
  51686. if (this._computeParticleColor && this._particle.color) {
  51687. this._colors32[colidx] = this._particle.color.r;
  51688. this._colors32[colidx + 1] = this._particle.color.g;
  51689. this._colors32[colidx + 2] = this._particle.color.b;
  51690. this._colors32[colidx + 3] = this._particle.color.a;
  51691. }
  51692. if (this._computeParticleTexture) {
  51693. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51694. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51695. }
  51696. }
  51697. }
  51698. else {
  51699. this._particle._stillInvisible = true; // mark the particle as invisible
  51700. for (pt = 0; pt < this._shape.length; pt++) {
  51701. idx = index + pt * 3;
  51702. colidx = colorIndex + pt * 4;
  51703. uvidx = uvIndex + pt * 2;
  51704. this._positions32[idx] = 0.0;
  51705. this._positions32[idx + 1] = 0.0;
  51706. this._positions32[idx + 2] = 0.0;
  51707. this._normals32[idx] = 0.0;
  51708. this._normals32[idx + 1] = 0.0;
  51709. this._normals32[idx + 2] = 0.0;
  51710. if (this._computeParticleColor && this._particle.color) {
  51711. this._colors32[colidx] = this._particle.color.r;
  51712. this._colors32[colidx + 1] = this._particle.color.g;
  51713. this._colors32[colidx + 2] = this._particle.color.b;
  51714. this._colors32[colidx + 3] = this._particle.color.a;
  51715. }
  51716. if (this._computeParticleTexture) {
  51717. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51718. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51719. }
  51720. }
  51721. }
  51722. // if the particle intersections must be computed : update the bbInfo
  51723. if (this._particlesIntersect) {
  51724. var bInfo = this._particle._boundingInfo;
  51725. var bBox = bInfo.boundingBox;
  51726. var bSphere = bInfo.boundingSphere;
  51727. if (!this._bSphereOnly) {
  51728. // place, scale and rotate the particle bbox within the SPS local system, then update it
  51729. for (var b = 0; b < bBox.vectors.length; b++) {
  51730. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  51731. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  51732. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  51733. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51734. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51735. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51736. 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;
  51737. 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;
  51738. 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;
  51739. }
  51740. bBox._update(this.mesh._worldMatrix);
  51741. }
  51742. // place and scale the particle bouding sphere in the SPS local system, then update it
  51743. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  51744. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  51745. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  51746. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  51747. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  51748. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  51749. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  51750. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  51751. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  51752. 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));
  51753. bSphere._update(this.mesh._worldMatrix);
  51754. }
  51755. // increment indexes for the next particle
  51756. index = idx + 3;
  51757. colorIndex = colidx + 4;
  51758. uvIndex = uvidx + 2;
  51759. }
  51760. // if the VBO must be updated
  51761. if (update) {
  51762. if (this._computeParticleColor) {
  51763. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  51764. }
  51765. if (this._computeParticleTexture) {
  51766. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  51767. }
  51768. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51769. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  51770. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  51771. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  51772. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  51773. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  51774. for (var i = 0; i < this._normals32.length; i++) {
  51775. this._fixedNormal32[i] = this._normals32[i];
  51776. }
  51777. }
  51778. if (!this.mesh.areNormalsFrozen) {
  51779. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  51780. }
  51781. }
  51782. if (this._depthSort && this._depthSortParticles) {
  51783. this.depthSortedParticles.sort(this._depthSortFunction);
  51784. var dspl = this.depthSortedParticles.length;
  51785. var sorted = 0;
  51786. var lind = 0;
  51787. var sind = 0;
  51788. var sid = 0;
  51789. for (sorted = 0; sorted < dspl; sorted++) {
  51790. lind = this.depthSortedParticles[sorted].indicesLength;
  51791. sind = this.depthSortedParticles[sorted].ind;
  51792. for (var i = 0; i < lind; i++) {
  51793. this._indices32[sid] = this._indices[sind + i];
  51794. sid++;
  51795. }
  51796. }
  51797. this.mesh.updateIndices(this._indices32);
  51798. }
  51799. }
  51800. if (this._computeBoundingBox) {
  51801. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  51802. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  51803. }
  51804. this.afterUpdateParticles(start, end, update);
  51805. return this;
  51806. };
  51807. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  51808. this._halfroll = this._roll * 0.5;
  51809. this._halfpitch = this._pitch * 0.5;
  51810. this._halfyaw = this._yaw * 0.5;
  51811. this._sinRoll = Math.sin(this._halfroll);
  51812. this._cosRoll = Math.cos(this._halfroll);
  51813. this._sinPitch = Math.sin(this._halfpitch);
  51814. this._cosPitch = Math.cos(this._halfpitch);
  51815. this._sinYaw = Math.sin(this._halfyaw);
  51816. this._cosYaw = Math.cos(this._halfyaw);
  51817. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  51818. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  51819. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  51820. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  51821. };
  51822. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  51823. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  51824. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  51825. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  51826. this._rotMatrix.m[3] = 0;
  51827. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  51828. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  51829. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  51830. this._rotMatrix.m[7] = 0;
  51831. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  51832. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  51833. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  51834. this._rotMatrix.m[11] = 0;
  51835. this._rotMatrix.m[12] = 0;
  51836. this._rotMatrix.m[13] = 0;
  51837. this._rotMatrix.m[14] = 0;
  51838. this._rotMatrix.m[15] = 1.0;
  51839. };
  51840. /**
  51841. * Disposes the SPS.
  51842. */
  51843. SolidParticleSystem.prototype.dispose = function () {
  51844. this.mesh.dispose();
  51845. this.vars = null;
  51846. // drop references to internal big arrays for the GC
  51847. this._positions = null;
  51848. this._indices = null;
  51849. this._normals = null;
  51850. this._uvs = null;
  51851. this._colors = null;
  51852. this._indices32 = null;
  51853. this._positions32 = null;
  51854. this._normals32 = null;
  51855. this._fixedNormal32 = null;
  51856. this._uvs32 = null;
  51857. this._colors32 = null;
  51858. this.pickedParticles = null;
  51859. };
  51860. /**
  51861. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  51862. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51863. * @returns the SPS.
  51864. */
  51865. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  51866. if (!this._isVisibilityBoxLocked) {
  51867. this.mesh.refreshBoundingInfo();
  51868. }
  51869. return this;
  51870. };
  51871. /**
  51872. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  51873. * @param size the size (float) of the visibility box
  51874. * note : this doesn't lock the SPS mesh bounding box.
  51875. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51876. */
  51877. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  51878. var vis = size / 2;
  51879. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  51880. };
  51881. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  51882. /**
  51883. * Gets whether the SPS as always visible or not
  51884. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51885. */
  51886. get: function () {
  51887. return this._alwaysVisible;
  51888. },
  51889. /**
  51890. * Sets the SPS as always visible or not
  51891. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51892. */
  51893. set: function (val) {
  51894. this._alwaysVisible = val;
  51895. this.mesh.alwaysSelectAsActiveMesh = val;
  51896. },
  51897. enumerable: true,
  51898. configurable: true
  51899. });
  51900. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  51901. /**
  51902. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  51903. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51904. */
  51905. get: function () {
  51906. return this._isVisibilityBoxLocked;
  51907. },
  51908. /**
  51909. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  51910. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51911. */
  51912. set: function (val) {
  51913. this._isVisibilityBoxLocked = val;
  51914. var boundingInfo = this.mesh.getBoundingInfo();
  51915. boundingInfo.isLocked = val;
  51916. },
  51917. enumerable: true,
  51918. configurable: true
  51919. });
  51920. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  51921. /**
  51922. * Gets if `setParticles()` computes the particle rotations or not.
  51923. * Default value : true. The SPS is faster when it's set to false.
  51924. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  51925. */
  51926. get: function () {
  51927. return this._computeParticleRotation;
  51928. },
  51929. /**
  51930. * Tells to `setParticles()` to compute the particle rotations or not.
  51931. * Default value : true. The SPS is faster when it's set to false.
  51932. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  51933. */
  51934. set: function (val) {
  51935. this._computeParticleRotation = val;
  51936. },
  51937. enumerable: true,
  51938. configurable: true
  51939. });
  51940. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  51941. /**
  51942. * Gets if `setParticles()` computes the particle colors or not.
  51943. * Default value : true. The SPS is faster when it's set to false.
  51944. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  51945. */
  51946. get: function () {
  51947. return this._computeParticleColor;
  51948. },
  51949. /**
  51950. * Tells to `setParticles()` to compute the particle colors or not.
  51951. * Default value : true. The SPS is faster when it's set to false.
  51952. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  51953. */
  51954. set: function (val) {
  51955. this._computeParticleColor = val;
  51956. },
  51957. enumerable: true,
  51958. configurable: true
  51959. });
  51960. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  51961. /**
  51962. * Gets if `setParticles()` computes the particle textures or not.
  51963. * Default value : true. The SPS is faster when it's set to false.
  51964. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  51965. */
  51966. get: function () {
  51967. return this._computeParticleTexture;
  51968. },
  51969. set: function (val) {
  51970. this._computeParticleTexture = val;
  51971. },
  51972. enumerable: true,
  51973. configurable: true
  51974. });
  51975. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  51976. /**
  51977. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  51978. * Default value : false. The SPS is faster when it's set to false.
  51979. * Note : the particle custom vertex positions aren't stored values.
  51980. */
  51981. get: function () {
  51982. return this._computeParticleVertex;
  51983. },
  51984. /**
  51985. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  51986. * Default value : false. The SPS is faster when it's set to false.
  51987. * Note : the particle custom vertex positions aren't stored values.
  51988. */
  51989. set: function (val) {
  51990. this._computeParticleVertex = val;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  51996. /**
  51997. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  51998. */
  51999. get: function () {
  52000. return this._computeBoundingBox;
  52001. },
  52002. /**
  52003. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52004. */
  52005. set: function (val) {
  52006. this._computeBoundingBox = val;
  52007. },
  52008. enumerable: true,
  52009. configurable: true
  52010. });
  52011. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52012. /**
  52013. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52014. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52015. * Default : `true`
  52016. */
  52017. get: function () {
  52018. return this._depthSortParticles;
  52019. },
  52020. /**
  52021. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52022. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52023. * Default : `true`
  52024. */
  52025. set: function (val) {
  52026. this._depthSortParticles = val;
  52027. },
  52028. enumerable: true,
  52029. configurable: true
  52030. });
  52031. // =======================================================================
  52032. // Particle behavior logic
  52033. // these following methods may be overwritten by the user to fit his needs
  52034. /**
  52035. * This function does nothing. It may be overwritten to set all the particle first values.
  52036. * The SPS doesn't call this function, you may have to call it by your own.
  52037. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52038. */
  52039. SolidParticleSystem.prototype.initParticles = function () {
  52040. };
  52041. /**
  52042. * This function does nothing. It may be overwritten to recycle a particle.
  52043. * The SPS doesn't call this function, you may have to call it by your own.
  52044. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52045. * @param particle The particle to recycle
  52046. * @returns the recycled particle
  52047. */
  52048. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52049. return particle;
  52050. };
  52051. /**
  52052. * Updates a particle : this function should be overwritten by the user.
  52053. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52054. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52055. * @example : just set a particle position or velocity and recycle conditions
  52056. * @param particle The particle to update
  52057. * @returns the updated particle
  52058. */
  52059. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52060. return particle;
  52061. };
  52062. /**
  52063. * Updates a vertex of a particle : it can be overwritten by the user.
  52064. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52065. * @param particle the current particle
  52066. * @param vertex the current index of the current particle
  52067. * @param pt the index of the current vertex in the particle shape
  52068. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52069. * @example : just set a vertex particle position
  52070. * @returns the updated vertex
  52071. */
  52072. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52073. return vertex;
  52074. };
  52075. /**
  52076. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52077. * This does nothing and may be overwritten by the user.
  52078. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52079. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52080. * @param update the boolean update value actually passed to setParticles()
  52081. */
  52082. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52083. };
  52084. /**
  52085. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52086. * This will be passed three parameters.
  52087. * This does nothing and may be overwritten by the user.
  52088. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52089. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52090. * @param update the boolean update value actually passed to setParticles()
  52091. */
  52092. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52093. };
  52094. return SolidParticleSystem;
  52095. }());
  52096. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52097. })(BABYLON || (BABYLON = {}));
  52098. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52099. var BABYLON;
  52100. (function (BABYLON) {
  52101. var ShaderMaterial = /** @class */ (function (_super) {
  52102. __extends(ShaderMaterial, _super);
  52103. function ShaderMaterial(name, scene, shaderPath, options) {
  52104. var _this = _super.call(this, name, scene) || this;
  52105. _this._textures = {};
  52106. _this._textureArrays = {};
  52107. _this._floats = {};
  52108. _this._ints = {};
  52109. _this._floatsArrays = {};
  52110. _this._colors3 = {};
  52111. _this._colors3Arrays = {};
  52112. _this._colors4 = {};
  52113. _this._vectors2 = {};
  52114. _this._vectors3 = {};
  52115. _this._vectors4 = {};
  52116. _this._matrices = {};
  52117. _this._matrices3x3 = {};
  52118. _this._matrices2x2 = {};
  52119. _this._vectors2Arrays = {};
  52120. _this._vectors3Arrays = {};
  52121. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52122. _this._shaderPath = shaderPath;
  52123. options.needAlphaBlending = options.needAlphaBlending || false;
  52124. options.needAlphaTesting = options.needAlphaTesting || false;
  52125. options.attributes = options.attributes || ["position", "normal", "uv"];
  52126. options.uniforms = options.uniforms || ["worldViewProjection"];
  52127. options.uniformBuffers = options.uniformBuffers || [];
  52128. options.samplers = options.samplers || [];
  52129. options.defines = options.defines || [];
  52130. _this._options = options;
  52131. return _this;
  52132. }
  52133. ShaderMaterial.prototype.getClassName = function () {
  52134. return "ShaderMaterial";
  52135. };
  52136. ShaderMaterial.prototype.needAlphaBlending = function () {
  52137. return this._options.needAlphaBlending;
  52138. };
  52139. ShaderMaterial.prototype.needAlphaTesting = function () {
  52140. return this._options.needAlphaTesting;
  52141. };
  52142. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52143. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52144. this._options.uniforms.push(uniformName);
  52145. }
  52146. };
  52147. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52148. if (this._options.samplers.indexOf(name) === -1) {
  52149. this._options.samplers.push(name);
  52150. }
  52151. this._textures[name] = texture;
  52152. return this;
  52153. };
  52154. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52155. if (this._options.samplers.indexOf(name) === -1) {
  52156. this._options.samplers.push(name);
  52157. }
  52158. this._checkUniform(name);
  52159. this._textureArrays[name] = textures;
  52160. return this;
  52161. };
  52162. ShaderMaterial.prototype.setFloat = function (name, value) {
  52163. this._checkUniform(name);
  52164. this._floats[name] = value;
  52165. return this;
  52166. };
  52167. ShaderMaterial.prototype.setInt = function (name, value) {
  52168. this._checkUniform(name);
  52169. this._ints[name] = value;
  52170. return this;
  52171. };
  52172. ShaderMaterial.prototype.setFloats = function (name, value) {
  52173. this._checkUniform(name);
  52174. this._floatsArrays[name] = value;
  52175. return this;
  52176. };
  52177. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52178. this._checkUniform(name);
  52179. this._colors3[name] = value;
  52180. return this;
  52181. };
  52182. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52183. this._checkUniform(name);
  52184. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52185. color.toArray(arr, arr.length);
  52186. return arr;
  52187. }, []);
  52188. return this;
  52189. };
  52190. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52191. this._checkUniform(name);
  52192. this._colors4[name] = value;
  52193. return this;
  52194. };
  52195. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52196. this._checkUniform(name);
  52197. this._vectors2[name] = value;
  52198. return this;
  52199. };
  52200. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52201. this._checkUniform(name);
  52202. this._vectors3[name] = value;
  52203. return this;
  52204. };
  52205. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52206. this._checkUniform(name);
  52207. this._vectors4[name] = value;
  52208. return this;
  52209. };
  52210. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52211. this._checkUniform(name);
  52212. this._matrices[name] = value;
  52213. return this;
  52214. };
  52215. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52216. this._checkUniform(name);
  52217. this._matrices3x3[name] = value;
  52218. return this;
  52219. };
  52220. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52221. this._checkUniform(name);
  52222. this._matrices2x2[name] = value;
  52223. return this;
  52224. };
  52225. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52226. this._checkUniform(name);
  52227. this._vectors2Arrays[name] = value;
  52228. return this;
  52229. };
  52230. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52231. this._checkUniform(name);
  52232. this._vectors3Arrays[name] = value;
  52233. return this;
  52234. };
  52235. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52236. if (!mesh) {
  52237. return true;
  52238. }
  52239. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52240. return false;
  52241. }
  52242. return false;
  52243. };
  52244. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52245. var scene = this.getScene();
  52246. var engine = scene.getEngine();
  52247. if (!this.checkReadyOnEveryCall) {
  52248. if (this._renderId === scene.getRenderId()) {
  52249. if (this._checkCache(scene, mesh, useInstances)) {
  52250. return true;
  52251. }
  52252. }
  52253. }
  52254. // Instances
  52255. var defines = [];
  52256. var attribs = [];
  52257. var fallbacks = new BABYLON.EffectFallbacks();
  52258. if (useInstances) {
  52259. defines.push("#define INSTANCES");
  52260. }
  52261. for (var index = 0; index < this._options.defines.length; index++) {
  52262. defines.push(this._options.defines[index]);
  52263. }
  52264. for (var index = 0; index < this._options.attributes.length; index++) {
  52265. attribs.push(this._options.attributes[index]);
  52266. }
  52267. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52268. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52269. defines.push("#define VERTEXCOLOR");
  52270. }
  52271. // Bones
  52272. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52273. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52274. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52275. if (mesh.numBoneInfluencers > 4) {
  52276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52278. }
  52279. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52280. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52281. fallbacks.addCPUSkinningFallback(0, mesh);
  52282. if (this._options.uniforms.indexOf("mBones") === -1) {
  52283. this._options.uniforms.push("mBones");
  52284. }
  52285. }
  52286. else {
  52287. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52288. }
  52289. // Textures
  52290. for (var name in this._textures) {
  52291. if (!this._textures[name].isReady()) {
  52292. return false;
  52293. }
  52294. }
  52295. // Alpha test
  52296. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52297. defines.push("#define ALPHATEST");
  52298. }
  52299. var previousEffect = this._effect;
  52300. var join = defines.join("\n");
  52301. this._effect = engine.createEffect(this._shaderPath, {
  52302. attributes: attribs,
  52303. uniformsNames: this._options.uniforms,
  52304. uniformBuffersNames: this._options.uniformBuffers,
  52305. samplers: this._options.samplers,
  52306. defines: join,
  52307. fallbacks: fallbacks,
  52308. onCompiled: this.onCompiled,
  52309. onError: this.onError
  52310. }, engine);
  52311. if (!this._effect.isReady()) {
  52312. return false;
  52313. }
  52314. if (previousEffect !== this._effect) {
  52315. scene.resetCachedMaterial();
  52316. }
  52317. this._renderId = scene.getRenderId();
  52318. return true;
  52319. };
  52320. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52321. var scene = this.getScene();
  52322. if (!this._effect) {
  52323. return;
  52324. }
  52325. if (this._options.uniforms.indexOf("world") !== -1) {
  52326. this._effect.setMatrix("world", world);
  52327. }
  52328. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52329. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52330. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52331. }
  52332. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52333. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52334. }
  52335. };
  52336. ShaderMaterial.prototype.bind = function (world, mesh) {
  52337. // Std values
  52338. this.bindOnlyWorldMatrix(world);
  52339. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52340. if (this._options.uniforms.indexOf("view") !== -1) {
  52341. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52342. }
  52343. if (this._options.uniforms.indexOf("projection") !== -1) {
  52344. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52345. }
  52346. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52347. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52348. }
  52349. // Bones
  52350. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52351. var name;
  52352. // Texture
  52353. for (name in this._textures) {
  52354. this._effect.setTexture(name, this._textures[name]);
  52355. }
  52356. // Texture arrays
  52357. for (name in this._textureArrays) {
  52358. this._effect.setTextureArray(name, this._textureArrays[name]);
  52359. }
  52360. // Int
  52361. for (name in this._ints) {
  52362. this._effect.setInt(name, this._ints[name]);
  52363. }
  52364. // Float
  52365. for (name in this._floats) {
  52366. this._effect.setFloat(name, this._floats[name]);
  52367. }
  52368. // Floats
  52369. for (name in this._floatsArrays) {
  52370. this._effect.setArray(name, this._floatsArrays[name]);
  52371. }
  52372. // Color3
  52373. for (name in this._colors3) {
  52374. this._effect.setColor3(name, this._colors3[name]);
  52375. }
  52376. for (name in this._colors3Arrays) {
  52377. this._effect.setArray3(name, this._colors3Arrays[name]);
  52378. }
  52379. // Color4
  52380. for (name in this._colors4) {
  52381. var color = this._colors4[name];
  52382. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52383. }
  52384. // Vector2
  52385. for (name in this._vectors2) {
  52386. this._effect.setVector2(name, this._vectors2[name]);
  52387. }
  52388. // Vector3
  52389. for (name in this._vectors3) {
  52390. this._effect.setVector3(name, this._vectors3[name]);
  52391. }
  52392. // Vector4
  52393. for (name in this._vectors4) {
  52394. this._effect.setVector4(name, this._vectors4[name]);
  52395. }
  52396. // Matrix
  52397. for (name in this._matrices) {
  52398. this._effect.setMatrix(name, this._matrices[name]);
  52399. }
  52400. // Matrix 3x3
  52401. for (name in this._matrices3x3) {
  52402. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52403. }
  52404. // Matrix 2x2
  52405. for (name in this._matrices2x2) {
  52406. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52407. }
  52408. // Vector2Array
  52409. for (name in this._vectors2Arrays) {
  52410. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52411. }
  52412. // Vector3Array
  52413. for (name in this._vectors3Arrays) {
  52414. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52415. }
  52416. }
  52417. this._afterBind(mesh);
  52418. };
  52419. ShaderMaterial.prototype.getActiveTextures = function () {
  52420. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52421. for (var name in this._textures) {
  52422. activeTextures.push(this._textures[name]);
  52423. }
  52424. for (var name in this._textureArrays) {
  52425. var array = this._textureArrays[name];
  52426. for (var index = 0; index < array.length; index++) {
  52427. activeTextures.push(array[index]);
  52428. }
  52429. }
  52430. return activeTextures;
  52431. };
  52432. ShaderMaterial.prototype.hasTexture = function (texture) {
  52433. if (_super.prototype.hasTexture.call(this, texture)) {
  52434. return true;
  52435. }
  52436. for (var name in this._textures) {
  52437. if (this._textures[name] === texture) {
  52438. return true;
  52439. }
  52440. }
  52441. for (var name in this._textureArrays) {
  52442. var array = this._textureArrays[name];
  52443. for (var index = 0; index < array.length; index++) {
  52444. if (array[index] === texture) {
  52445. return true;
  52446. }
  52447. }
  52448. }
  52449. return false;
  52450. };
  52451. ShaderMaterial.prototype.clone = function (name) {
  52452. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52453. return newShaderMaterial;
  52454. };
  52455. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52456. if (forceDisposeTextures) {
  52457. var name;
  52458. for (name in this._textures) {
  52459. this._textures[name].dispose();
  52460. }
  52461. for (name in this._textureArrays) {
  52462. var array = this._textureArrays[name];
  52463. for (var index = 0; index < array.length; index++) {
  52464. array[index].dispose();
  52465. }
  52466. }
  52467. }
  52468. this._textures = {};
  52469. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52470. };
  52471. ShaderMaterial.prototype.serialize = function () {
  52472. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52473. serializationObject.customType = "BABYLON.ShaderMaterial";
  52474. serializationObject.options = this._options;
  52475. serializationObject.shaderPath = this._shaderPath;
  52476. var name;
  52477. // Texture
  52478. serializationObject.textures = {};
  52479. for (name in this._textures) {
  52480. serializationObject.textures[name] = this._textures[name].serialize();
  52481. }
  52482. // Texture arrays
  52483. serializationObject.textureArrays = {};
  52484. for (name in this._textureArrays) {
  52485. serializationObject.textureArrays[name] = [];
  52486. var array = this._textureArrays[name];
  52487. for (var index = 0; index < array.length; index++) {
  52488. serializationObject.textureArrays[name].push(array[index].serialize());
  52489. }
  52490. }
  52491. // Float
  52492. serializationObject.floats = {};
  52493. for (name in this._floats) {
  52494. serializationObject.floats[name] = this._floats[name];
  52495. }
  52496. // Float s
  52497. serializationObject.FloatArrays = {};
  52498. for (name in this._floatsArrays) {
  52499. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52500. }
  52501. // Color3
  52502. serializationObject.colors3 = {};
  52503. for (name in this._colors3) {
  52504. serializationObject.colors3[name] = this._colors3[name].asArray();
  52505. }
  52506. // Color3 array
  52507. serializationObject.colors3Arrays = {};
  52508. for (name in this._colors3Arrays) {
  52509. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52510. }
  52511. // Color4
  52512. serializationObject.colors4 = {};
  52513. for (name in this._colors4) {
  52514. serializationObject.colors4[name] = this._colors4[name].asArray();
  52515. }
  52516. // Vector2
  52517. serializationObject.vectors2 = {};
  52518. for (name in this._vectors2) {
  52519. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  52520. }
  52521. // Vector3
  52522. serializationObject.vectors3 = {};
  52523. for (name in this._vectors3) {
  52524. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  52525. }
  52526. // Vector4
  52527. serializationObject.vectors4 = {};
  52528. for (name in this._vectors4) {
  52529. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  52530. }
  52531. // Matrix
  52532. serializationObject.matrices = {};
  52533. for (name in this._matrices) {
  52534. serializationObject.matrices[name] = this._matrices[name].asArray();
  52535. }
  52536. // Matrix 3x3
  52537. serializationObject.matrices3x3 = {};
  52538. for (name in this._matrices3x3) {
  52539. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  52540. }
  52541. // Matrix 2x2
  52542. serializationObject.matrices2x2 = {};
  52543. for (name in this._matrices2x2) {
  52544. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  52545. }
  52546. // Vector2Array
  52547. serializationObject.vectors2Arrays = {};
  52548. for (name in this._vectors2Arrays) {
  52549. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  52550. }
  52551. // Vector3Array
  52552. serializationObject.vectors3Arrays = {};
  52553. for (name in this._vectors3Arrays) {
  52554. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  52555. }
  52556. return serializationObject;
  52557. };
  52558. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  52559. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  52560. var name;
  52561. // Texture
  52562. for (name in source.textures) {
  52563. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  52564. }
  52565. // Texture arrays
  52566. for (name in source.textureArrays) {
  52567. var array = source.textureArrays[name];
  52568. var textureArray = new Array();
  52569. for (var index = 0; index < array.length; index++) {
  52570. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  52571. }
  52572. material.setTextureArray(name, textureArray);
  52573. }
  52574. // Float
  52575. for (name in source.floats) {
  52576. material.setFloat(name, source.floats[name]);
  52577. }
  52578. // Float s
  52579. for (name in source.floatsArrays) {
  52580. material.setFloats(name, source.floatsArrays[name]);
  52581. }
  52582. // Color3
  52583. for (name in source.colors3) {
  52584. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  52585. }
  52586. // Color3 arrays
  52587. for (name in source.colors3Arrays) {
  52588. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  52589. if (i % 3 === 0) {
  52590. arr.push([num]);
  52591. }
  52592. else {
  52593. arr[arr.length - 1].push(num);
  52594. }
  52595. return arr;
  52596. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  52597. material.setColor3Array(name, colors);
  52598. }
  52599. // Color4
  52600. for (name in source.colors4) {
  52601. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  52602. }
  52603. // Vector2
  52604. for (name in source.vectors2) {
  52605. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  52606. }
  52607. // Vector3
  52608. for (name in source.vectors3) {
  52609. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  52610. }
  52611. // Vector4
  52612. for (name in source.vectors4) {
  52613. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  52614. }
  52615. // Matrix
  52616. for (name in source.matrices) {
  52617. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  52618. }
  52619. // Matrix 3x3
  52620. for (name in source.matrices3x3) {
  52621. material.setMatrix3x3(name, source.matrices3x3[name]);
  52622. }
  52623. // Matrix 2x2
  52624. for (name in source.matrices2x2) {
  52625. material.setMatrix2x2(name, source.matrices2x2[name]);
  52626. }
  52627. // Vector2Array
  52628. for (name in source.vectors2Arrays) {
  52629. material.setArray2(name, source.vectors2Arrays[name]);
  52630. }
  52631. // Vector3Array
  52632. for (name in source.vectors3Arrays) {
  52633. material.setArray3(name, source.vectors3Arrays[name]);
  52634. }
  52635. return material;
  52636. };
  52637. return ShaderMaterial;
  52638. }(BABYLON.Material));
  52639. BABYLON.ShaderMaterial = ShaderMaterial;
  52640. })(BABYLON || (BABYLON = {}));
  52641. //# sourceMappingURL=babylon.shaderMaterial.js.map
  52642. var BABYLON;
  52643. (function (BABYLON) {
  52644. var GroundMesh = /** @class */ (function (_super) {
  52645. __extends(GroundMesh, _super);
  52646. function GroundMesh(name, scene) {
  52647. var _this = _super.call(this, name, scene) || this;
  52648. _this.generateOctree = false;
  52649. return _this;
  52650. }
  52651. GroundMesh.prototype.getClassName = function () {
  52652. return "GroundMesh";
  52653. };
  52654. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  52655. get: function () {
  52656. return Math.min(this._subdivisionsX, this._subdivisionsY);
  52657. },
  52658. enumerable: true,
  52659. configurable: true
  52660. });
  52661. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  52662. get: function () {
  52663. return this._subdivisionsX;
  52664. },
  52665. enumerable: true,
  52666. configurable: true
  52667. });
  52668. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  52669. get: function () {
  52670. return this._subdivisionsY;
  52671. },
  52672. enumerable: true,
  52673. configurable: true
  52674. });
  52675. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  52676. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  52677. this._subdivisionsX = chunksCount;
  52678. this._subdivisionsY = chunksCount;
  52679. this.subdivide(chunksCount);
  52680. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  52681. };
  52682. /**
  52683. * Returns a height (y) value in the Worl system :
  52684. * the ground altitude at the coordinates (x, z) expressed in the World system.
  52685. * Returns the ground y position if (x, z) are outside the ground surface.
  52686. */
  52687. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  52688. var world = this.getWorldMatrix();
  52689. var invMat = BABYLON.Tmp.Matrix[5];
  52690. world.invertToRef(invMat);
  52691. var tmpVect = BABYLON.Tmp.Vector3[8];
  52692. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  52693. x = tmpVect.x;
  52694. z = tmpVect.z;
  52695. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  52696. return this.position.y;
  52697. }
  52698. if (!this._heightQuads || this._heightQuads.length == 0) {
  52699. this._initHeightQuads();
  52700. this._computeHeightQuads();
  52701. }
  52702. var facet = this._getFacetAt(x, z);
  52703. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  52704. // return y in the World system
  52705. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  52706. return tmpVect.y;
  52707. };
  52708. /**
  52709. * Returns a normalized vector (Vector3) orthogonal to the ground
  52710. * at the ground coordinates (x, z) expressed in the World system.
  52711. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  52712. */
  52713. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  52714. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  52715. this.getNormalAtCoordinatesToRef(x, z, normal);
  52716. return normal;
  52717. };
  52718. /**
  52719. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  52720. * at the ground coordinates (x, z) expressed in the World system.
  52721. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  52722. * Returns the GroundMesh.
  52723. */
  52724. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  52725. var world = this.getWorldMatrix();
  52726. var tmpMat = BABYLON.Tmp.Matrix[5];
  52727. world.invertToRef(tmpMat);
  52728. var tmpVect = BABYLON.Tmp.Vector3[8];
  52729. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  52730. x = tmpVect.x;
  52731. z = tmpVect.z;
  52732. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  52733. return this;
  52734. }
  52735. if (!this._heightQuads || this._heightQuads.length == 0) {
  52736. this._initHeightQuads();
  52737. this._computeHeightQuads();
  52738. }
  52739. var facet = this._getFacetAt(x, z);
  52740. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  52741. return this;
  52742. };
  52743. /**
  52744. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  52745. * if the ground has been updated.
  52746. * This can be used in the render loop.
  52747. * Returns the GroundMesh.
  52748. */
  52749. GroundMesh.prototype.updateCoordinateHeights = function () {
  52750. if (!this._heightQuads || this._heightQuads.length == 0) {
  52751. this._initHeightQuads();
  52752. }
  52753. this._computeHeightQuads();
  52754. return this;
  52755. };
  52756. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  52757. GroundMesh.prototype._getFacetAt = function (x, z) {
  52758. // retrieve col and row from x, z coordinates in the ground local system
  52759. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  52760. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  52761. var quad = this._heightQuads[row * this._subdivisionsX + col];
  52762. var facet;
  52763. if (z < quad.slope.x * x + quad.slope.y) {
  52764. facet = quad.facet1;
  52765. }
  52766. else {
  52767. facet = quad.facet2;
  52768. }
  52769. return facet;
  52770. };
  52771. // Creates and populates the heightMap array with "facet" elements :
  52772. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  52773. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  52774. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  52775. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  52776. // Returns the GroundMesh.
  52777. GroundMesh.prototype._initHeightQuads = function () {
  52778. var subdivisionsX = this._subdivisionsX;
  52779. var subdivisionsY = this._subdivisionsY;
  52780. this._heightQuads = new Array();
  52781. for (var row = 0; row < subdivisionsY; row++) {
  52782. for (var col = 0; col < subdivisionsX; col++) {
  52783. 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) };
  52784. this._heightQuads[row * subdivisionsX + col] = quad;
  52785. }
  52786. }
  52787. return this;
  52788. };
  52789. // Compute each quad element values and update the the heightMap array :
  52790. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  52791. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  52792. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  52793. // Returns the GroundMesh.
  52794. GroundMesh.prototype._computeHeightQuads = function () {
  52795. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52796. if (!positions) {
  52797. return this;
  52798. }
  52799. var v1 = BABYLON.Tmp.Vector3[3];
  52800. var v2 = BABYLON.Tmp.Vector3[2];
  52801. var v3 = BABYLON.Tmp.Vector3[1];
  52802. var v4 = BABYLON.Tmp.Vector3[0];
  52803. var v1v2 = BABYLON.Tmp.Vector3[4];
  52804. var v1v3 = BABYLON.Tmp.Vector3[5];
  52805. var v1v4 = BABYLON.Tmp.Vector3[6];
  52806. var norm1 = BABYLON.Tmp.Vector3[7];
  52807. var norm2 = BABYLON.Tmp.Vector3[8];
  52808. var i = 0;
  52809. var j = 0;
  52810. var k = 0;
  52811. var cd = 0; // 2D slope coefficient : z = cd * x + h
  52812. var h = 0;
  52813. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  52814. var d2 = 0;
  52815. var subdivisionsX = this._subdivisionsX;
  52816. var subdivisionsY = this._subdivisionsY;
  52817. for (var row = 0; row < subdivisionsY; row++) {
  52818. for (var col = 0; col < subdivisionsX; col++) {
  52819. i = col * 3;
  52820. j = row * (subdivisionsX + 1) * 3;
  52821. k = (row + 1) * (subdivisionsX + 1) * 3;
  52822. v1.x = positions[j + i];
  52823. v1.y = positions[j + i + 1];
  52824. v1.z = positions[j + i + 2];
  52825. v2.x = positions[j + i + 3];
  52826. v2.y = positions[j + i + 4];
  52827. v2.z = positions[j + i + 5];
  52828. v3.x = positions[k + i];
  52829. v3.y = positions[k + i + 1];
  52830. v3.z = positions[k + i + 2];
  52831. v4.x = positions[k + i + 3];
  52832. v4.y = positions[k + i + 4];
  52833. v4.z = positions[k + i + 5];
  52834. // 2D slope V1V4
  52835. cd = (v4.z - v1.z) / (v4.x - v1.x);
  52836. h = v1.z - cd * v1.x; // v1 belongs to the slope
  52837. // facet equations :
  52838. // we compute each facet normal vector
  52839. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  52840. // we compute the value d by applying the equation to v1 which belongs to the plane
  52841. // then we store the facet equation in a Vector4
  52842. v2.subtractToRef(v1, v1v2);
  52843. v3.subtractToRef(v1, v1v3);
  52844. v4.subtractToRef(v1, v1v4);
  52845. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  52846. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  52847. norm1.normalize();
  52848. norm2.normalize();
  52849. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  52850. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  52851. var quad = this._heightQuads[row * subdivisionsX + col];
  52852. quad.slope.copyFromFloats(cd, h);
  52853. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  52854. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  52855. }
  52856. }
  52857. return this;
  52858. };
  52859. GroundMesh.prototype.serialize = function (serializationObject) {
  52860. _super.prototype.serialize.call(this, serializationObject);
  52861. serializationObject.subdivisionsX = this._subdivisionsX;
  52862. serializationObject.subdivisionsY = this._subdivisionsY;
  52863. serializationObject.minX = this._minX;
  52864. serializationObject.maxX = this._maxX;
  52865. serializationObject.minZ = this._minZ;
  52866. serializationObject.maxZ = this._maxZ;
  52867. serializationObject.width = this._width;
  52868. serializationObject.height = this._height;
  52869. };
  52870. GroundMesh.Parse = function (parsedMesh, scene) {
  52871. var result = new GroundMesh(parsedMesh.name, scene);
  52872. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  52873. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  52874. result._minX = parsedMesh.minX;
  52875. result._maxX = parsedMesh.maxX;
  52876. result._minZ = parsedMesh.minZ;
  52877. result._maxZ = parsedMesh.maxZ;
  52878. result._width = parsedMesh.width;
  52879. result._height = parsedMesh.height;
  52880. return result;
  52881. };
  52882. return GroundMesh;
  52883. }(BABYLON.Mesh));
  52884. BABYLON.GroundMesh = GroundMesh;
  52885. })(BABYLON || (BABYLON = {}));
  52886. //# sourceMappingURL=babylon.groundMesh.js.map
  52887. var BABYLON;
  52888. (function (BABYLON) {
  52889. /**
  52890. * Creates an instance based on a source mesh.
  52891. */
  52892. var InstancedMesh = /** @class */ (function (_super) {
  52893. __extends(InstancedMesh, _super);
  52894. function InstancedMesh(name, source) {
  52895. var _this = _super.call(this, name, source.getScene()) || this;
  52896. source.instances.push(_this);
  52897. _this._sourceMesh = source;
  52898. _this.position.copyFrom(source.position);
  52899. _this.rotation.copyFrom(source.rotation);
  52900. _this.scaling.copyFrom(source.scaling);
  52901. if (source.rotationQuaternion) {
  52902. _this.rotationQuaternion = source.rotationQuaternion.clone();
  52903. }
  52904. _this.infiniteDistance = source.infiniteDistance;
  52905. _this.setPivotMatrix(source.getPivotMatrix());
  52906. _this.refreshBoundingInfo();
  52907. _this._syncSubMeshes();
  52908. return _this;
  52909. }
  52910. /**
  52911. * Returns the string "InstancedMesh".
  52912. */
  52913. InstancedMesh.prototype.getClassName = function () {
  52914. return "InstancedMesh";
  52915. };
  52916. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  52917. // Methods
  52918. get: function () {
  52919. return this._sourceMesh.receiveShadows;
  52920. },
  52921. enumerable: true,
  52922. configurable: true
  52923. });
  52924. Object.defineProperty(InstancedMesh.prototype, "material", {
  52925. get: function () {
  52926. return this._sourceMesh.material;
  52927. },
  52928. enumerable: true,
  52929. configurable: true
  52930. });
  52931. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  52932. get: function () {
  52933. return this._sourceMesh.visibility;
  52934. },
  52935. enumerable: true,
  52936. configurable: true
  52937. });
  52938. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  52939. get: function () {
  52940. return this._sourceMesh.skeleton;
  52941. },
  52942. enumerable: true,
  52943. configurable: true
  52944. });
  52945. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  52946. get: function () {
  52947. return this._sourceMesh.renderingGroupId;
  52948. },
  52949. enumerable: true,
  52950. configurable: true
  52951. });
  52952. /**
  52953. * Returns the total number of vertices (integer).
  52954. */
  52955. InstancedMesh.prototype.getTotalVertices = function () {
  52956. return this._sourceMesh.getTotalVertices();
  52957. };
  52958. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  52959. get: function () {
  52960. return this._sourceMesh;
  52961. },
  52962. enumerable: true,
  52963. configurable: true
  52964. });
  52965. /**
  52966. * Is this node ready to be used/rendered
  52967. * @return {boolean} is it ready
  52968. */
  52969. InstancedMesh.prototype.isReady = function () {
  52970. return this._sourceMesh.isReady(true);
  52971. };
  52972. /**
  52973. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  52974. */
  52975. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  52976. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  52977. };
  52978. /**
  52979. * Sets the vertex data of the mesh geometry for the requested `kind`.
  52980. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  52981. * The `data` are either a numeric array either a Float32Array.
  52982. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  52983. * 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).
  52984. * Note that a new underlying VertexBuffer object is created each call.
  52985. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  52986. *
  52987. * Possible `kind` values :
  52988. * - BABYLON.VertexBuffer.PositionKind
  52989. * - BABYLON.VertexBuffer.UVKind
  52990. * - BABYLON.VertexBuffer.UV2Kind
  52991. * - BABYLON.VertexBuffer.UV3Kind
  52992. * - BABYLON.VertexBuffer.UV4Kind
  52993. * - BABYLON.VertexBuffer.UV5Kind
  52994. * - BABYLON.VertexBuffer.UV6Kind
  52995. * - BABYLON.VertexBuffer.ColorKind
  52996. * - BABYLON.VertexBuffer.MatricesIndicesKind
  52997. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  52998. * - BABYLON.VertexBuffer.MatricesWeightsKind
  52999. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53000. *
  53001. * Returns the Mesh.
  53002. */
  53003. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53004. if (this.sourceMesh) {
  53005. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53006. }
  53007. return this.sourceMesh;
  53008. };
  53009. /**
  53010. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53011. * If the mesh has no geometry, it is simply returned as it is.
  53012. * The `data` are either a numeric array either a Float32Array.
  53013. * No new underlying VertexBuffer object is created.
  53014. * 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.
  53015. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53016. *
  53017. * Possible `kind` values :
  53018. * - BABYLON.VertexBuffer.PositionKind
  53019. * - BABYLON.VertexBuffer.UVKind
  53020. * - BABYLON.VertexBuffer.UV2Kind
  53021. * - BABYLON.VertexBuffer.UV3Kind
  53022. * - BABYLON.VertexBuffer.UV4Kind
  53023. * - BABYLON.VertexBuffer.UV5Kind
  53024. * - BABYLON.VertexBuffer.UV6Kind
  53025. * - BABYLON.VertexBuffer.ColorKind
  53026. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53027. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53028. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53029. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53030. *
  53031. * Returns the Mesh.
  53032. */
  53033. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53034. if (this.sourceMesh) {
  53035. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53036. }
  53037. return this.sourceMesh;
  53038. };
  53039. /**
  53040. * Sets the mesh indices.
  53041. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53042. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53043. * This method creates a new index buffer each call.
  53044. * Returns the Mesh.
  53045. */
  53046. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53047. if (totalVertices === void 0) { totalVertices = null; }
  53048. if (this.sourceMesh) {
  53049. this.sourceMesh.setIndices(indices, totalVertices);
  53050. }
  53051. return this.sourceMesh;
  53052. };
  53053. /**
  53054. * Boolean : True if the mesh owns the requested kind of data.
  53055. */
  53056. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53057. return this._sourceMesh.isVerticesDataPresent(kind);
  53058. };
  53059. /**
  53060. * Returns an array of indices (IndicesArray).
  53061. */
  53062. InstancedMesh.prototype.getIndices = function () {
  53063. return this._sourceMesh.getIndices();
  53064. };
  53065. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53066. get: function () {
  53067. return this._sourceMesh._positions;
  53068. },
  53069. enumerable: true,
  53070. configurable: true
  53071. });
  53072. /**
  53073. * Sets a new updated BoundingInfo to the mesh.
  53074. * Returns the mesh.
  53075. */
  53076. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53077. var meshBB = this._sourceMesh.getBoundingInfo();
  53078. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53079. this._updateBoundingInfo();
  53080. return this;
  53081. };
  53082. InstancedMesh.prototype._preActivate = function () {
  53083. if (this._currentLOD) {
  53084. this._currentLOD._preActivate();
  53085. }
  53086. return this;
  53087. };
  53088. InstancedMesh.prototype._activate = function (renderId) {
  53089. if (this._currentLOD) {
  53090. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53091. }
  53092. return this;
  53093. };
  53094. /**
  53095. * Returns the current associated LOD AbstractMesh.
  53096. */
  53097. InstancedMesh.prototype.getLOD = function (camera) {
  53098. if (!camera) {
  53099. return this;
  53100. }
  53101. var boundingInfo = this.getBoundingInfo();
  53102. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53103. if (this._currentLOD === this.sourceMesh) {
  53104. return this;
  53105. }
  53106. return this._currentLOD;
  53107. };
  53108. InstancedMesh.prototype._syncSubMeshes = function () {
  53109. this.releaseSubMeshes();
  53110. if (this._sourceMesh.subMeshes) {
  53111. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53112. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53113. }
  53114. }
  53115. return this;
  53116. };
  53117. InstancedMesh.prototype._generatePointsArray = function () {
  53118. return this._sourceMesh._generatePointsArray();
  53119. };
  53120. /**
  53121. * Creates a new InstancedMesh from the current mesh.
  53122. * - name (string) : the cloned mesh name
  53123. * - newParent (optional Node) : the optional Node to parent the clone to.
  53124. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53125. *
  53126. * Returns the clone.
  53127. */
  53128. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53129. var result = this._sourceMesh.createInstance(name);
  53130. // Deep copy
  53131. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53132. // Bounding info
  53133. this.refreshBoundingInfo();
  53134. // Parent
  53135. if (newParent) {
  53136. result.parent = newParent;
  53137. }
  53138. if (!doNotCloneChildren) {
  53139. // Children
  53140. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53141. var mesh = this.getScene().meshes[index];
  53142. if (mesh.parent === this) {
  53143. mesh.clone(mesh.name, result);
  53144. }
  53145. }
  53146. }
  53147. result.computeWorldMatrix(true);
  53148. return result;
  53149. };
  53150. /**
  53151. * Disposes the InstancedMesh.
  53152. * Returns nothing.
  53153. */
  53154. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53155. // Remove from mesh
  53156. var index = this._sourceMesh.instances.indexOf(this);
  53157. this._sourceMesh.instances.splice(index, 1);
  53158. _super.prototype.dispose.call(this, doNotRecurse);
  53159. };
  53160. return InstancedMesh;
  53161. }(BABYLON.AbstractMesh));
  53162. BABYLON.InstancedMesh = InstancedMesh;
  53163. })(BABYLON || (BABYLON = {}));
  53164. //# sourceMappingURL=babylon.instancedMesh.js.map
  53165. var BABYLON;
  53166. (function (BABYLON) {
  53167. var LinesMesh = /** @class */ (function (_super) {
  53168. __extends(LinesMesh, _super);
  53169. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53170. if (scene === void 0) { scene = null; }
  53171. if (parent === void 0) { parent = null; }
  53172. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53173. _this.useVertexColor = useVertexColor;
  53174. _this.useVertexAlpha = useVertexAlpha;
  53175. _this.color = new BABYLON.Color3(1, 1, 1);
  53176. _this.alpha = 1;
  53177. if (source) {
  53178. _this.color = source.color.clone();
  53179. _this.alpha = source.alpha;
  53180. _this.useVertexColor = source.useVertexColor;
  53181. _this.useVertexAlpha = source.useVertexAlpha;
  53182. }
  53183. _this._intersectionThreshold = 0.1;
  53184. var defines = [];
  53185. var options = {
  53186. attributes: [BABYLON.VertexBuffer.PositionKind],
  53187. uniforms: ["world", "viewProjection"],
  53188. needAlphaBlending: true,
  53189. defines: defines
  53190. };
  53191. if (useVertexAlpha === false) {
  53192. options.needAlphaBlending = false;
  53193. }
  53194. if (!useVertexColor) {
  53195. options.uniforms.push("color");
  53196. }
  53197. else {
  53198. options.defines.push("#define VERTEXCOLOR");
  53199. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53200. }
  53201. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53202. return _this;
  53203. }
  53204. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53205. /**
  53206. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53207. * This margin is expressed in world space coordinates, so its value may vary.
  53208. * Default value is 0.1
  53209. * @returns the intersection Threshold value.
  53210. */
  53211. get: function () {
  53212. return this._intersectionThreshold;
  53213. },
  53214. /**
  53215. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53216. * This margin is expressed in world space coordinates, so its value may vary.
  53217. * @param value the new threshold to apply
  53218. */
  53219. set: function (value) {
  53220. if (this._intersectionThreshold === value) {
  53221. return;
  53222. }
  53223. this._intersectionThreshold = value;
  53224. if (this.geometry) {
  53225. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53226. }
  53227. },
  53228. enumerable: true,
  53229. configurable: true
  53230. });
  53231. /**
  53232. * Returns the string "LineMesh"
  53233. */
  53234. LinesMesh.prototype.getClassName = function () {
  53235. return "LinesMesh";
  53236. };
  53237. Object.defineProperty(LinesMesh.prototype, "material", {
  53238. get: function () {
  53239. return this._colorShader;
  53240. },
  53241. set: function (value) {
  53242. // Do nothing
  53243. },
  53244. enumerable: true,
  53245. configurable: true
  53246. });
  53247. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53248. get: function () {
  53249. return false;
  53250. },
  53251. enumerable: true,
  53252. configurable: true
  53253. });
  53254. LinesMesh.prototype.createInstance = function (name) {
  53255. throw new Error("LinesMeshes do not support createInstance.");
  53256. };
  53257. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53258. if (!this._geometry) {
  53259. return this;
  53260. }
  53261. // VBOs
  53262. this._geometry._bind(this._colorShader.getEffect());
  53263. // Color
  53264. if (!this.useVertexColor) {
  53265. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53266. }
  53267. return this;
  53268. };
  53269. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53270. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53271. return this;
  53272. }
  53273. var engine = this.getScene().getEngine();
  53274. // Draw order
  53275. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53276. return this;
  53277. };
  53278. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53279. this._colorShader.dispose();
  53280. _super.prototype.dispose.call(this, doNotRecurse);
  53281. };
  53282. /**
  53283. * Returns a new LineMesh object cloned from the current one.
  53284. */
  53285. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53286. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53287. };
  53288. return LinesMesh;
  53289. }(BABYLON.Mesh));
  53290. BABYLON.LinesMesh = LinesMesh;
  53291. })(BABYLON || (BABYLON = {}));
  53292. //# sourceMappingURL=babylon.linesMesh.js.map
  53293. var BABYLON;
  53294. (function (BABYLON) {
  53295. var MeshBuilder = /** @class */ (function () {
  53296. function MeshBuilder() {
  53297. }
  53298. MeshBuilder.updateSideOrientation = function (orientation) {
  53299. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53300. return BABYLON.Mesh.DOUBLESIDE;
  53301. }
  53302. if (orientation === undefined || orientation === null) {
  53303. return BABYLON.Mesh.FRONTSIDE;
  53304. }
  53305. return orientation;
  53306. };
  53307. /**
  53308. * Creates a box mesh.
  53309. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53310. * The parameter `size` sets the size (float) of each box side (default 1).
  53311. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53312. * 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).
  53313. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53314. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53315. * 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).
  53316. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53318. */
  53319. MeshBuilder.CreateBox = function (name, options, scene) {
  53320. if (scene === void 0) { scene = null; }
  53321. var box = new BABYLON.Mesh(name, scene);
  53322. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53323. box._originalBuilderSideOrientation = options.sideOrientation;
  53324. var vertexData = BABYLON.VertexData.CreateBox(options);
  53325. vertexData.applyToMesh(box, options.updatable);
  53326. return box;
  53327. };
  53328. /**
  53329. * Creates a sphere mesh.
  53330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53331. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53332. * 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`).
  53333. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53334. * 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
  53335. * 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).
  53336. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53337. * 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).
  53338. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53340. */
  53341. MeshBuilder.CreateSphere = function (name, options, scene) {
  53342. var sphere = new BABYLON.Mesh(name, scene);
  53343. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53344. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53345. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53346. vertexData.applyToMesh(sphere, options.updatable);
  53347. return sphere;
  53348. };
  53349. /**
  53350. * Creates a plane polygonal mesh. By default, this is a disc.
  53351. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53352. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53353. * 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.
  53354. * 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
  53355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53356. * 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).
  53357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53359. */
  53360. MeshBuilder.CreateDisc = function (name, options, scene) {
  53361. if (scene === void 0) { scene = null; }
  53362. var disc = new BABYLON.Mesh(name, scene);
  53363. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53364. disc._originalBuilderSideOrientation = options.sideOrientation;
  53365. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53366. vertexData.applyToMesh(disc, options.updatable);
  53367. return disc;
  53368. };
  53369. /**
  53370. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53371. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53372. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53373. * 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`).
  53374. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53375. * 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.
  53376. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53377. * 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).
  53378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53380. */
  53381. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53382. var sphere = new BABYLON.Mesh(name, scene);
  53383. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53384. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53385. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53386. vertexData.applyToMesh(sphere, options.updatable);
  53387. return sphere;
  53388. };
  53389. ;
  53390. /**
  53391. * Creates a ribbon mesh.
  53392. * 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.
  53393. *
  53394. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53395. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53396. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53397. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53398. * 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.
  53399. * 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.
  53400. * 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
  53401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53402. * 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).
  53403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53404. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53405. * 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.
  53406. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53407. * 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
  53408. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53409. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53411. */
  53412. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53413. if (scene === void 0) { scene = null; }
  53414. var pathArray = options.pathArray;
  53415. var closeArray = options.closeArray;
  53416. var closePath = options.closePath;
  53417. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53418. var instance = options.instance;
  53419. var updatable = options.updatable;
  53420. if (instance) {
  53421. // positionFunction : ribbon case
  53422. // only pathArray and sideOrientation parameters are taken into account for positions update
  53423. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53424. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53425. var positionFunction = function (positions) {
  53426. var minlg = pathArray[0].length;
  53427. var i = 0;
  53428. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53429. for (var si = 1; si <= ns; si++) {
  53430. for (var p = 0; p < pathArray.length; p++) {
  53431. var path = pathArray[p];
  53432. var l = path.length;
  53433. minlg = (minlg < l) ? minlg : l;
  53434. var j = 0;
  53435. while (j < minlg) {
  53436. positions[i] = path[j].x;
  53437. positions[i + 1] = path[j].y;
  53438. positions[i + 2] = path[j].z;
  53439. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53440. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53441. }
  53442. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53443. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53444. }
  53445. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53446. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53447. }
  53448. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53449. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53450. }
  53451. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53452. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53453. }
  53454. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53455. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53456. }
  53457. j++;
  53458. i += 3;
  53459. }
  53460. if (instance._closePath) {
  53461. positions[i] = path[0].x;
  53462. positions[i + 1] = path[0].y;
  53463. positions[i + 2] = path[0].z;
  53464. i += 3;
  53465. }
  53466. }
  53467. }
  53468. };
  53469. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53470. positionFunction(positions);
  53471. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53472. instance._boundingInfo.update(instance._worldMatrix);
  53473. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53474. if (options.colors) {
  53475. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53476. for (var c = 0; c < options.colors.length; c++) {
  53477. colors[c * 4] = options.colors[c].r;
  53478. colors[c * 4 + 1] = options.colors[c].g;
  53479. colors[c * 4 + 2] = options.colors[c].b;
  53480. colors[c * 4 + 3] = options.colors[c].a;
  53481. }
  53482. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53483. }
  53484. if (options.uvs) {
  53485. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53486. for (var i = 0; i < options.uvs.length; i++) {
  53487. uvs[i * 2] = options.uvs[i].x;
  53488. uvs[i * 2 + 1] = options.uvs[i].y;
  53489. }
  53490. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53491. }
  53492. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53493. var indices = instance.getIndices();
  53494. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53495. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53496. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53497. if (instance._closePath) {
  53498. var indexFirst = 0;
  53499. var indexLast = 0;
  53500. for (var p = 0; p < pathArray.length; p++) {
  53501. indexFirst = instance._idx[p] * 3;
  53502. if (p + 1 < pathArray.length) {
  53503. indexLast = (instance._idx[p + 1] - 1) * 3;
  53504. }
  53505. else {
  53506. indexLast = normals.length - 3;
  53507. }
  53508. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53509. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53510. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53511. normals[indexLast] = normals[indexFirst];
  53512. normals[indexLast + 1] = normals[indexFirst + 1];
  53513. normals[indexLast + 2] = normals[indexFirst + 2];
  53514. }
  53515. }
  53516. if (!(instance.areNormalsFrozen)) {
  53517. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  53518. }
  53519. }
  53520. return instance;
  53521. }
  53522. else {
  53523. var ribbon = new BABYLON.Mesh(name, scene);
  53524. ribbon._originalBuilderSideOrientation = sideOrientation;
  53525. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  53526. if (closePath) {
  53527. ribbon._idx = vertexData._idx;
  53528. }
  53529. ribbon._closePath = closePath;
  53530. ribbon._closeArray = closeArray;
  53531. vertexData.applyToMesh(ribbon, updatable);
  53532. return ribbon;
  53533. }
  53534. };
  53535. /**
  53536. * Creates a cylinder or a cone mesh.
  53537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  53538. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  53539. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  53540. * 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.
  53541. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  53542. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  53543. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  53544. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  53545. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  53546. * 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).
  53547. * 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
  53548. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  53549. * 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
  53550. * 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.
  53551. * If `enclose` is false, a ring surface is one element.
  53552. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  53553. * 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
  53554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53555. * 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).
  53556. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53558. */
  53559. MeshBuilder.CreateCylinder = function (name, options, scene) {
  53560. var cylinder = new BABYLON.Mesh(name, scene);
  53561. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53562. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  53563. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  53564. vertexData.applyToMesh(cylinder, options.updatable);
  53565. return cylinder;
  53566. };
  53567. /**
  53568. * Creates a torus mesh.
  53569. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  53570. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  53571. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  53572. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  53573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53574. * 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).
  53575. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53577. */
  53578. MeshBuilder.CreateTorus = function (name, options, scene) {
  53579. var torus = new BABYLON.Mesh(name, scene);
  53580. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53581. torus._originalBuilderSideOrientation = options.sideOrientation;
  53582. var vertexData = BABYLON.VertexData.CreateTorus(options);
  53583. vertexData.applyToMesh(torus, options.updatable);
  53584. return torus;
  53585. };
  53586. /**
  53587. * Creates a torus knot mesh.
  53588. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  53589. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  53590. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  53591. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  53592. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  53593. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53594. * 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).
  53595. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53597. */
  53598. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  53599. var torusKnot = new BABYLON.Mesh(name, scene);
  53600. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53601. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  53602. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  53603. vertexData.applyToMesh(torusKnot, options.updatable);
  53604. return torusKnot;
  53605. };
  53606. /**
  53607. * Creates a line system mesh.
  53608. * A line system is a pool of many lines gathered in a single mesh.
  53609. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  53610. * 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.
  53611. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  53612. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  53613. * 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
  53614. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  53615. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  53616. * 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
  53617. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  53618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53619. */
  53620. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  53621. var instance = options.instance;
  53622. var lines = options.lines;
  53623. var colors = options.colors;
  53624. if (instance) {
  53625. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53626. var vertexColor;
  53627. var lineColors;
  53628. if (colors) {
  53629. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53630. }
  53631. var i = 0;
  53632. var c = 0;
  53633. for (var l = 0; l < lines.length; l++) {
  53634. var points = lines[l];
  53635. for (var p = 0; p < points.length; p++) {
  53636. positions[i] = points[p].x;
  53637. positions[i + 1] = points[p].y;
  53638. positions[i + 2] = points[p].z;
  53639. if (colors && vertexColor) {
  53640. lineColors = colors[l];
  53641. vertexColor[c] = lineColors[p].r;
  53642. vertexColor[c + 1] = lineColors[p].g;
  53643. vertexColor[c + 2] = lineColors[p].b;
  53644. vertexColor[c + 3] = lineColors[p].a;
  53645. c += 4;
  53646. }
  53647. i += 3;
  53648. }
  53649. }
  53650. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53651. if (colors && vertexColor) {
  53652. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  53653. }
  53654. return instance;
  53655. }
  53656. // line system creation
  53657. var useVertexColor = (colors) ? true : false;
  53658. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  53659. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  53660. vertexData.applyToMesh(lineSystem, options.updatable);
  53661. return lineSystem;
  53662. };
  53663. /**
  53664. * Creates a line mesh.
  53665. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  53666. * 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.
  53667. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  53668. * The parameter `points` is an array successive Vector3.
  53669. * 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
  53670. * The optional parameter `colors` is an array of successive Color4, one per line point.
  53671. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  53672. * When updating an instance, remember that only point positions can change, not the number of points.
  53673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53674. */
  53675. MeshBuilder.CreateLines = function (name, options, scene) {
  53676. if (scene === void 0) { scene = null; }
  53677. var colors = (options.colors) ? [options.colors] : null;
  53678. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  53679. return lines;
  53680. };
  53681. /**
  53682. * Creates a dashed line mesh.
  53683. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  53684. * 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.
  53685. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  53686. * The parameter `points` is an array successive Vector3.
  53687. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  53688. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  53689. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  53690. * 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
  53691. * When updating an instance, remember that only point positions can change, not the number of points.
  53692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53693. */
  53694. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  53695. if (scene === void 0) { scene = null; }
  53696. var points = options.points;
  53697. var instance = options.instance;
  53698. var gapSize = options.gapSize || 1;
  53699. var dashSize = options.dashSize || 3;
  53700. if (instance) {
  53701. var positionFunction = function (positions) {
  53702. var curvect = BABYLON.Vector3.Zero();
  53703. var nbSeg = positions.length / 6;
  53704. var lg = 0;
  53705. var nb = 0;
  53706. var shft = 0;
  53707. var dashshft = 0;
  53708. var curshft = 0;
  53709. var p = 0;
  53710. var i = 0;
  53711. var j = 0;
  53712. for (i = 0; i < points.length - 1; i++) {
  53713. points[i + 1].subtractToRef(points[i], curvect);
  53714. lg += curvect.length();
  53715. }
  53716. shft = lg / nbSeg;
  53717. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  53718. for (i = 0; i < points.length - 1; i++) {
  53719. points[i + 1].subtractToRef(points[i], curvect);
  53720. nb = Math.floor(curvect.length() / shft);
  53721. curvect.normalize();
  53722. j = 0;
  53723. while (j < nb && p < positions.length) {
  53724. curshft = shft * j;
  53725. positions[p] = points[i].x + curshft * curvect.x;
  53726. positions[p + 1] = points[i].y + curshft * curvect.y;
  53727. positions[p + 2] = points[i].z + curshft * curvect.z;
  53728. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  53729. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  53730. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  53731. p += 6;
  53732. j++;
  53733. }
  53734. }
  53735. while (p < positions.length) {
  53736. positions[p] = points[i].x;
  53737. positions[p + 1] = points[i].y;
  53738. positions[p + 2] = points[i].z;
  53739. p += 3;
  53740. }
  53741. };
  53742. instance.updateMeshPositions(positionFunction, false);
  53743. return instance;
  53744. }
  53745. // dashed lines creation
  53746. var dashedLines = new BABYLON.LinesMesh(name, scene);
  53747. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  53748. vertexData.applyToMesh(dashedLines, options.updatable);
  53749. dashedLines.dashSize = dashSize;
  53750. dashedLines.gapSize = gapSize;
  53751. return dashedLines;
  53752. };
  53753. /**
  53754. * Creates an extruded shape mesh.
  53755. * 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.
  53756. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  53757. *
  53758. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  53759. * 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
  53760. * extruded along the Z axis.
  53761. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  53762. * 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.
  53763. * The parameter `scale` (float, default 1) is the value to scale the shape.
  53764. * 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
  53765. * 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
  53766. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  53767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53768. * 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).
  53769. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53770. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53772. */
  53773. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  53774. if (scene === void 0) { scene = null; }
  53775. var path = options.path;
  53776. var shape = options.shape;
  53777. var scale = options.scale || 1;
  53778. var rotation = options.rotation || 0;
  53779. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  53780. var updatable = options.updatable;
  53781. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53782. var instance = options.instance || null;
  53783. var invertUV = options.invertUV || false;
  53784. 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);
  53785. };
  53786. /**
  53787. * Creates an custom extruded shape mesh.
  53788. * 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.
  53789. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  53790. *
  53791. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  53792. * 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
  53793. * extruded along the Z axis.
  53794. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  53795. * 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
  53796. * and the distance of this point from the begining of the path :
  53797. * ```javascript
  53798. * var rotationFunction = function(i, distance) {
  53799. * // do things
  53800. * return rotationValue; }
  53801. * ```
  53802. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  53803. * 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
  53804. * and the distance of this point from the begining of the path :
  53805. * ```javascript
  53806. * var scaleFunction = function(i, distance) {
  53807. * // do things
  53808. * return scaleValue;}
  53809. * ```
  53810. * It must returns a float value that will be the scale value applied to the shape on each path point.
  53811. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  53812. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  53813. * 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
  53814. * 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
  53815. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  53816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53817. * 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).
  53818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53819. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53821. */
  53822. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  53823. var path = options.path;
  53824. var shape = options.shape;
  53825. var scaleFunction = options.scaleFunction || (function () { return 1; });
  53826. var rotationFunction = options.rotationFunction || (function () { return 0; });
  53827. var ribbonCloseArray = options.ribbonCloseArray || false;
  53828. var ribbonClosePath = options.ribbonClosePath || false;
  53829. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  53830. var updatable = options.updatable;
  53831. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53832. var instance = options.instance;
  53833. var invertUV = options.invertUV || false;
  53834. 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);
  53835. };
  53836. /**
  53837. * Creates lathe mesh.
  53838. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  53839. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  53840. *
  53841. * 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
  53842. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  53843. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  53844. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  53845. * 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.
  53846. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  53847. * 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
  53848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53849. * 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).
  53850. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53851. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53853. */
  53854. MeshBuilder.CreateLathe = function (name, options, scene) {
  53855. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  53856. var closed = (options.closed === undefined) ? true : options.closed;
  53857. var shape = options.shape;
  53858. var radius = options.radius || 1;
  53859. var tessellation = options.tessellation || 64;
  53860. var updatable = options.updatable;
  53861. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53862. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  53863. var pi2 = Math.PI * 2;
  53864. var paths = new Array();
  53865. var invertUV = options.invertUV || false;
  53866. var i = 0;
  53867. var p = 0;
  53868. var step = pi2 / tessellation * arc;
  53869. var rotated;
  53870. var path = new Array();
  53871. ;
  53872. for (i = 0; i <= tessellation; i++) {
  53873. var path = [];
  53874. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  53875. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  53876. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  53877. }
  53878. for (p = 0; p < shape.length; p++) {
  53879. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  53880. path.push(rotated);
  53881. }
  53882. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  53883. 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));
  53884. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  53885. }
  53886. paths.push(path);
  53887. }
  53888. // lathe ribbon
  53889. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  53890. return lathe;
  53891. };
  53892. /**
  53893. * Creates a plane mesh.
  53894. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  53895. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  53896. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  53897. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  53898. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53899. * 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).
  53900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53902. */
  53903. MeshBuilder.CreatePlane = function (name, options, scene) {
  53904. var plane = new BABYLON.Mesh(name, scene);
  53905. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53906. plane._originalBuilderSideOrientation = options.sideOrientation;
  53907. var vertexData = BABYLON.VertexData.CreatePlane(options);
  53908. vertexData.applyToMesh(plane, options.updatable);
  53909. if (options.sourcePlane) {
  53910. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  53911. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  53912. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  53913. plane.rotate(vectorProduct, product);
  53914. }
  53915. return plane;
  53916. };
  53917. /**
  53918. * Creates a ground mesh.
  53919. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  53920. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  53921. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  53922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53923. */
  53924. MeshBuilder.CreateGround = function (name, options, scene) {
  53925. var ground = new BABYLON.GroundMesh(name, scene);
  53926. ground._setReady(false);
  53927. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  53928. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  53929. ground._width = options.width || 1;
  53930. ground._height = options.height || 1;
  53931. ground._maxX = ground._width / 2;
  53932. ground._maxZ = ground._height / 2;
  53933. ground._minX = -ground._maxX;
  53934. ground._minZ = -ground._maxZ;
  53935. var vertexData = BABYLON.VertexData.CreateGround(options);
  53936. vertexData.applyToMesh(ground, options.updatable);
  53937. ground._setReady(true);
  53938. return ground;
  53939. };
  53940. /**
  53941. * Creates a tiled ground mesh.
  53942. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  53943. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  53944. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  53945. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  53946. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  53947. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  53948. * numbers of subdivisions on the ground width and height of each tile.
  53949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53950. */
  53951. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  53952. var tiledGround = new BABYLON.Mesh(name, scene);
  53953. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  53954. vertexData.applyToMesh(tiledGround, options.updatable);
  53955. return tiledGround;
  53956. };
  53957. /**
  53958. * Creates a ground mesh from a height map.
  53959. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  53960. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  53961. * The parameter `url` sets the URL of the height map image resource.
  53962. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  53963. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  53964. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  53965. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  53966. * 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.
  53967. * 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).
  53968. * This function is passed the newly built mesh :
  53969. * ```javascript
  53970. * function(mesh) { // do things
  53971. * return; }
  53972. * ```
  53973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53974. */
  53975. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  53976. var width = options.width || 10.0;
  53977. var height = options.height || 10.0;
  53978. var subdivisions = options.subdivisions || 1 | 0;
  53979. var minHeight = options.minHeight || 0.0;
  53980. var maxHeight = options.maxHeight || 1.0;
  53981. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  53982. var updatable = options.updatable;
  53983. var onReady = options.onReady;
  53984. var ground = new BABYLON.GroundMesh(name, scene);
  53985. ground._subdivisionsX = subdivisions;
  53986. ground._subdivisionsY = subdivisions;
  53987. ground._width = width;
  53988. ground._height = height;
  53989. ground._maxX = ground._width / 2.0;
  53990. ground._maxZ = ground._height / 2.0;
  53991. ground._minX = -ground._maxX;
  53992. ground._minZ = -ground._maxZ;
  53993. ground._setReady(false);
  53994. var onload = function (img) {
  53995. // Getting height map data
  53996. var canvas = document.createElement("canvas");
  53997. var context = canvas.getContext("2d");
  53998. if (!context) {
  53999. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54000. }
  54001. if (scene.isDisposed) {
  54002. return;
  54003. }
  54004. var bufferWidth = img.width;
  54005. var bufferHeight = img.height;
  54006. canvas.width = bufferWidth;
  54007. canvas.height = bufferHeight;
  54008. context.drawImage(img, 0, 0);
  54009. // Create VertexData from map data
  54010. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54011. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54012. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54013. width: width, height: height,
  54014. subdivisions: subdivisions,
  54015. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54016. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54017. });
  54018. vertexData.applyToMesh(ground, updatable);
  54019. ground._setReady(true);
  54020. //execute ready callback, if set
  54021. if (onReady) {
  54022. onReady(ground);
  54023. }
  54024. };
  54025. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54026. return ground;
  54027. };
  54028. /**
  54029. * Creates a polygon mesh.
  54030. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54031. * 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.
  54032. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54033. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54034. * 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).
  54035. * Remember you can only change the shape positions, not their number when updating a polygon.
  54036. */
  54037. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54038. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54039. var shape = options.shape;
  54040. var holes = options.holes || [];
  54041. var depth = options.depth || 0;
  54042. var contours = [];
  54043. var hole = [];
  54044. for (var i = 0; i < shape.length; i++) {
  54045. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54046. }
  54047. var epsilon = 0.00000001;
  54048. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54049. contours.pop();
  54050. }
  54051. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54052. for (var hNb = 0; hNb < holes.length; hNb++) {
  54053. hole = [];
  54054. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54055. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54056. }
  54057. polygonTriangulation.addHole(hole);
  54058. }
  54059. var polygon = polygonTriangulation.build(options.updatable, depth);
  54060. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54061. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54062. vertexData.applyToMesh(polygon, options.updatable);
  54063. return polygon;
  54064. };
  54065. ;
  54066. /**
  54067. * Creates an extruded polygon mesh, with depth in the Y direction.
  54068. * 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).
  54069. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54070. */
  54071. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54072. return MeshBuilder.CreatePolygon(name, options, scene);
  54073. };
  54074. ;
  54075. /**
  54076. * Creates a tube mesh.
  54077. * 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.
  54078. *
  54079. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54080. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54081. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54082. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54083. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54084. * 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.
  54085. * It must return a radius value (positive float) :
  54086. * ```javascript
  54087. * var radiusFunction = function(i, distance) {
  54088. * // do things
  54089. * return radius; }
  54090. * ```
  54091. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54092. * 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
  54093. * 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
  54094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54095. * 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).
  54096. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54097. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54099. */
  54100. MeshBuilder.CreateTube = function (name, options, scene) {
  54101. var path = options.path;
  54102. var instance = options.instance;
  54103. var radius = 1.0;
  54104. if (instance) {
  54105. radius = instance.radius;
  54106. }
  54107. if (options.radius !== undefined) {
  54108. radius = options.radius;
  54109. }
  54110. ;
  54111. var tessellation = options.tessellation || 64 | 0;
  54112. var radiusFunction = options.radiusFunction || null;
  54113. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54114. var invertUV = options.invertUV || false;
  54115. var updatable = options.updatable;
  54116. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54117. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54118. // tube geometry
  54119. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54120. var tangents = path3D.getTangents();
  54121. var normals = path3D.getNormals();
  54122. var distances = path3D.getDistances();
  54123. var pi2 = Math.PI * 2;
  54124. var step = pi2 / tessellation * arc;
  54125. var returnRadius = function () { return radius; };
  54126. var radiusFunctionFinal = radiusFunction || returnRadius;
  54127. var circlePath;
  54128. var rad;
  54129. var normal;
  54130. var rotated;
  54131. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54132. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54133. for (var i = 0; i < path.length; i++) {
  54134. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54135. circlePath = Array(); // current circle array
  54136. normal = normals[i]; // current normal
  54137. for (var t = 0; t < tessellation; t++) {
  54138. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54139. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54140. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54141. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54142. circlePath[t] = rotated;
  54143. }
  54144. circlePaths[index] = circlePath;
  54145. index++;
  54146. }
  54147. // cap
  54148. var capPath = function (nbPoints, pathIndex) {
  54149. var pointCap = Array();
  54150. for (var i = 0; i < nbPoints; i++) {
  54151. pointCap.push(path[pathIndex]);
  54152. }
  54153. return pointCap;
  54154. };
  54155. switch (cap) {
  54156. case BABYLON.Mesh.NO_CAP:
  54157. break;
  54158. case BABYLON.Mesh.CAP_START:
  54159. circlePaths[0] = capPath(tessellation, 0);
  54160. circlePaths[1] = circlePaths[2].slice(0);
  54161. break;
  54162. case BABYLON.Mesh.CAP_END:
  54163. circlePaths[index] = circlePaths[index - 1].slice(0);
  54164. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54165. break;
  54166. case BABYLON.Mesh.CAP_ALL:
  54167. circlePaths[0] = capPath(tessellation, 0);
  54168. circlePaths[1] = circlePaths[2].slice(0);
  54169. circlePaths[index] = circlePaths[index - 1].slice(0);
  54170. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54171. break;
  54172. default:
  54173. break;
  54174. }
  54175. return circlePaths;
  54176. };
  54177. var path3D;
  54178. var pathArray;
  54179. if (instance) {
  54180. var arc = options.arc || instance.arc;
  54181. path3D = (instance.path3D).update(path);
  54182. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54183. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54184. instance.path3D = path3D;
  54185. instance.pathArray = pathArray;
  54186. instance.arc = arc;
  54187. instance.radius = radius;
  54188. return instance;
  54189. }
  54190. // tube creation
  54191. path3D = new BABYLON.Path3D(path);
  54192. var newPathArray = new Array();
  54193. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54194. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54195. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54196. tube.pathArray = pathArray;
  54197. tube.path3D = path3D;
  54198. tube.tessellation = tessellation;
  54199. tube.cap = cap;
  54200. tube.arc = options.arc;
  54201. tube.radius = radius;
  54202. return tube;
  54203. };
  54204. /**
  54205. * Creates a polyhedron mesh.
  54206. *
  54207. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54208. * 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
  54209. * to choose the wanted type.
  54210. * The parameter `size` (positive float, default 1) sets the polygon size.
  54211. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54212. * 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`.
  54213. * 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
  54214. * 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)`).
  54215. * 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
  54216. * 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.
  54217. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54218. * 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).
  54219. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54220. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54221. */
  54222. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54223. var polyhedron = new BABYLON.Mesh(name, scene);
  54224. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54225. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54226. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54227. vertexData.applyToMesh(polyhedron, options.updatable);
  54228. return polyhedron;
  54229. };
  54230. /**
  54231. * Creates a decal mesh.
  54232. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54233. * 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.
  54234. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54235. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54236. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54237. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54238. */
  54239. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54240. var indices = sourceMesh.getIndices();
  54241. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54242. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54243. var position = options.position || BABYLON.Vector3.Zero();
  54244. var normal = options.normal || BABYLON.Vector3.Up();
  54245. var size = options.size || BABYLON.Vector3.One();
  54246. var angle = options.angle || 0;
  54247. // Getting correct rotation
  54248. if (!normal) {
  54249. var target = new BABYLON.Vector3(0, 0, 1);
  54250. var camera = sourceMesh.getScene().activeCamera;
  54251. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54252. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54253. }
  54254. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54255. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54256. var pitch = Math.atan2(normal.y, len);
  54257. // Matrix
  54258. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54259. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54260. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54261. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54262. var vertexData = new BABYLON.VertexData();
  54263. vertexData.indices = [];
  54264. vertexData.positions = [];
  54265. vertexData.normals = [];
  54266. vertexData.uvs = [];
  54267. var currentVertexDataIndex = 0;
  54268. var extractDecalVector3 = function (indexId) {
  54269. var result = new BABYLON.PositionNormalVertex();
  54270. if (!indices || !positions || !normals) {
  54271. return result;
  54272. }
  54273. var vertexId = indices[indexId];
  54274. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54275. // Send vector to decal local world
  54276. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54277. // Get normal
  54278. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54279. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54280. return result;
  54281. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54282. var clip = function (vertices, axis) {
  54283. if (vertices.length === 0) {
  54284. return vertices;
  54285. }
  54286. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54287. var clipVertices = function (v0, v1) {
  54288. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54289. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54290. };
  54291. var result = new Array();
  54292. for (var index = 0; index < vertices.length; index += 3) {
  54293. var v1Out;
  54294. var v2Out;
  54295. var v3Out;
  54296. var total = 0;
  54297. var nV1 = null;
  54298. var nV2 = null;
  54299. var nV3 = null;
  54300. var nV4 = null;
  54301. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54302. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54303. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54304. v1Out = d1 > 0;
  54305. v2Out = d2 > 0;
  54306. v3Out = d3 > 0;
  54307. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54308. switch (total) {
  54309. case 0:
  54310. result.push(vertices[index]);
  54311. result.push(vertices[index + 1]);
  54312. result.push(vertices[index + 2]);
  54313. break;
  54314. case 1:
  54315. if (v1Out) {
  54316. nV1 = vertices[index + 1];
  54317. nV2 = vertices[index + 2];
  54318. nV3 = clipVertices(vertices[index], nV1);
  54319. nV4 = clipVertices(vertices[index], nV2);
  54320. }
  54321. if (v2Out) {
  54322. nV1 = vertices[index];
  54323. nV2 = vertices[index + 2];
  54324. nV3 = clipVertices(vertices[index + 1], nV1);
  54325. nV4 = clipVertices(vertices[index + 1], nV2);
  54326. result.push(nV3);
  54327. result.push(nV2.clone());
  54328. result.push(nV1.clone());
  54329. result.push(nV2.clone());
  54330. result.push(nV3.clone());
  54331. result.push(nV4);
  54332. break;
  54333. }
  54334. if (v3Out) {
  54335. nV1 = vertices[index];
  54336. nV2 = vertices[index + 1];
  54337. nV3 = clipVertices(vertices[index + 2], nV1);
  54338. nV4 = clipVertices(vertices[index + 2], nV2);
  54339. }
  54340. if (nV1 && nV2 && nV3 && nV4) {
  54341. result.push(nV1.clone());
  54342. result.push(nV2.clone());
  54343. result.push(nV3);
  54344. result.push(nV4);
  54345. result.push(nV3.clone());
  54346. result.push(nV2.clone());
  54347. }
  54348. break;
  54349. case 2:
  54350. if (!v1Out) {
  54351. nV1 = vertices[index].clone();
  54352. nV2 = clipVertices(nV1, vertices[index + 1]);
  54353. nV3 = clipVertices(nV1, vertices[index + 2]);
  54354. result.push(nV1);
  54355. result.push(nV2);
  54356. result.push(nV3);
  54357. }
  54358. if (!v2Out) {
  54359. nV1 = vertices[index + 1].clone();
  54360. nV2 = clipVertices(nV1, vertices[index + 2]);
  54361. nV3 = clipVertices(nV1, vertices[index]);
  54362. result.push(nV1);
  54363. result.push(nV2);
  54364. result.push(nV3);
  54365. }
  54366. if (!v3Out) {
  54367. nV1 = vertices[index + 2].clone();
  54368. nV2 = clipVertices(nV1, vertices[index]);
  54369. nV3 = clipVertices(nV1, vertices[index + 1]);
  54370. result.push(nV1);
  54371. result.push(nV2);
  54372. result.push(nV3);
  54373. }
  54374. break;
  54375. case 3:
  54376. break;
  54377. }
  54378. }
  54379. return result;
  54380. };
  54381. for (var index = 0; index < indices.length; index += 3) {
  54382. var faceVertices = new Array();
  54383. faceVertices.push(extractDecalVector3(index));
  54384. faceVertices.push(extractDecalVector3(index + 1));
  54385. faceVertices.push(extractDecalVector3(index + 2));
  54386. // Clip
  54387. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54388. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54389. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54390. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54391. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54392. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54393. if (faceVertices.length === 0) {
  54394. continue;
  54395. }
  54396. // Add UVs and get back to world
  54397. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54398. var vertex = faceVertices[vIndex];
  54399. //TODO check for Int32Array | Uint32Array | Uint16Array
  54400. vertexData.indices.push(currentVertexDataIndex);
  54401. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54402. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54403. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54404. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54405. currentVertexDataIndex++;
  54406. }
  54407. }
  54408. // Return mesh
  54409. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54410. vertexData.applyToMesh(decal);
  54411. decal.position = position.clone();
  54412. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54413. return decal;
  54414. };
  54415. // Privates
  54416. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54417. // extrusion geometry
  54418. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54419. var tangents = path3D.getTangents();
  54420. var normals = path3D.getNormals();
  54421. var binormals = path3D.getBinormals();
  54422. var distances = path3D.getDistances();
  54423. var angle = 0;
  54424. var returnScale = function () { return scale !== null ? scale : 1; };
  54425. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54426. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54427. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54428. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54429. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54430. for (var i = 0; i < curve.length; i++) {
  54431. var shapePath = new Array();
  54432. var angleStep = rotate(i, distances[i]);
  54433. var scaleRatio = scl(i, distances[i]);
  54434. for (var p = 0; p < shape.length; p++) {
  54435. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54436. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54437. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54438. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54439. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54440. shapePath[p] = rotated;
  54441. }
  54442. shapePaths[index] = shapePath;
  54443. angle += angleStep;
  54444. index++;
  54445. }
  54446. // cap
  54447. var capPath = function (shapePath) {
  54448. var pointCap = Array();
  54449. var barycenter = BABYLON.Vector3.Zero();
  54450. var i;
  54451. for (i = 0; i < shapePath.length; i++) {
  54452. barycenter.addInPlace(shapePath[i]);
  54453. }
  54454. barycenter.scaleInPlace(1.0 / shapePath.length);
  54455. for (i = 0; i < shapePath.length; i++) {
  54456. pointCap.push(barycenter);
  54457. }
  54458. return pointCap;
  54459. };
  54460. switch (cap) {
  54461. case BABYLON.Mesh.NO_CAP:
  54462. break;
  54463. case BABYLON.Mesh.CAP_START:
  54464. shapePaths[0] = capPath(shapePaths[2]);
  54465. shapePaths[1] = shapePaths[2];
  54466. break;
  54467. case BABYLON.Mesh.CAP_END:
  54468. shapePaths[index] = shapePaths[index - 1];
  54469. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54470. break;
  54471. case BABYLON.Mesh.CAP_ALL:
  54472. shapePaths[0] = capPath(shapePaths[2]);
  54473. shapePaths[1] = shapePaths[2];
  54474. shapePaths[index] = shapePaths[index - 1];
  54475. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54476. break;
  54477. default:
  54478. break;
  54479. }
  54480. return shapePaths;
  54481. };
  54482. var path3D;
  54483. var pathArray;
  54484. if (instance) {
  54485. path3D = (instance.path3D).update(curve);
  54486. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54487. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54488. return instance;
  54489. }
  54490. // extruded shape creation
  54491. path3D = new BABYLON.Path3D(curve);
  54492. var newShapePaths = new Array();
  54493. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54494. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54495. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54496. extrudedGeneric.pathArray = pathArray;
  54497. extrudedGeneric.path3D = path3D;
  54498. extrudedGeneric.cap = cap;
  54499. return extrudedGeneric;
  54500. };
  54501. return MeshBuilder;
  54502. }());
  54503. BABYLON.MeshBuilder = MeshBuilder;
  54504. })(BABYLON || (BABYLON = {}));
  54505. //# sourceMappingURL=babylon.meshBuilder.js.map
  54506. var BABYLON;
  54507. (function (BABYLON) {
  54508. var AudioEngine = /** @class */ (function () {
  54509. function AudioEngine() {
  54510. this._audioContext = null;
  54511. this._audioContextInitialized = false;
  54512. this.canUseWebAudio = false;
  54513. this.WarnedWebAudioUnsupported = false;
  54514. this.unlocked = false;
  54515. this.isMP3supported = false;
  54516. this.isOGGsupported = false;
  54517. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  54518. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  54519. this.canUseWebAudio = true;
  54520. }
  54521. var audioElem = document.createElement('audio');
  54522. try {
  54523. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  54524. this.isMP3supported = true;
  54525. }
  54526. }
  54527. catch (e) {
  54528. // protect error during capability check.
  54529. }
  54530. try {
  54531. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  54532. this.isOGGsupported = true;
  54533. }
  54534. }
  54535. catch (e) {
  54536. // protect error during capability check.
  54537. }
  54538. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  54539. this._unlockiOSaudio();
  54540. }
  54541. else {
  54542. this.unlocked = true;
  54543. }
  54544. }
  54545. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  54546. get: function () {
  54547. if (!this._audioContextInitialized) {
  54548. this._initializeAudioContext();
  54549. }
  54550. return this._audioContext;
  54551. },
  54552. enumerable: true,
  54553. configurable: true
  54554. });
  54555. AudioEngine.prototype._unlockiOSaudio = function () {
  54556. var _this = this;
  54557. var unlockaudio = function () {
  54558. if (!_this.audioContext) {
  54559. return;
  54560. }
  54561. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  54562. var source = _this.audioContext.createBufferSource();
  54563. source.buffer = buffer;
  54564. source.connect(_this.audioContext.destination);
  54565. source.start(0);
  54566. setTimeout(function () {
  54567. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  54568. _this.unlocked = true;
  54569. window.removeEventListener('touchend', unlockaudio, false);
  54570. if (_this.onAudioUnlocked) {
  54571. _this.onAudioUnlocked();
  54572. }
  54573. }
  54574. }, 0);
  54575. };
  54576. window.addEventListener('touchend', unlockaudio, false);
  54577. };
  54578. AudioEngine.prototype._initializeAudioContext = function () {
  54579. try {
  54580. if (this.canUseWebAudio) {
  54581. this._audioContext = new AudioContext();
  54582. // create a global volume gain node
  54583. this.masterGain = this._audioContext.createGain();
  54584. this.masterGain.gain.value = 1;
  54585. this.masterGain.connect(this._audioContext.destination);
  54586. this._audioContextInitialized = true;
  54587. }
  54588. }
  54589. catch (e) {
  54590. this.canUseWebAudio = false;
  54591. BABYLON.Tools.Error("Web Audio: " + e.message);
  54592. }
  54593. };
  54594. AudioEngine.prototype.dispose = function () {
  54595. if (this.canUseWebAudio && this._audioContextInitialized) {
  54596. if (this._connectedAnalyser && this._audioContext) {
  54597. this._connectedAnalyser.stopDebugCanvas();
  54598. this._connectedAnalyser.dispose();
  54599. this.masterGain.disconnect();
  54600. this.masterGain.connect(this._audioContext.destination);
  54601. this._connectedAnalyser = null;
  54602. }
  54603. this.masterGain.gain.value = 1;
  54604. }
  54605. this.WarnedWebAudioUnsupported = false;
  54606. };
  54607. AudioEngine.prototype.getGlobalVolume = function () {
  54608. if (this.canUseWebAudio && this._audioContextInitialized) {
  54609. return this.masterGain.gain.value;
  54610. }
  54611. else {
  54612. return -1;
  54613. }
  54614. };
  54615. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  54616. if (this.canUseWebAudio && this._audioContextInitialized) {
  54617. this.masterGain.gain.value = newVolume;
  54618. }
  54619. };
  54620. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  54621. if (this._connectedAnalyser) {
  54622. this._connectedAnalyser.stopDebugCanvas();
  54623. }
  54624. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  54625. this._connectedAnalyser = analyser;
  54626. this.masterGain.disconnect();
  54627. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  54628. }
  54629. };
  54630. return AudioEngine;
  54631. }());
  54632. BABYLON.AudioEngine = AudioEngine;
  54633. })(BABYLON || (BABYLON = {}));
  54634. //# sourceMappingURL=babylon.audioEngine.js.map
  54635. var BABYLON;
  54636. (function (BABYLON) {
  54637. var Sound = /** @class */ (function () {
  54638. /**
  54639. * Create a sound and attach it to a scene
  54640. * @param name Name of your sound
  54641. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  54642. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  54643. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  54644. */
  54645. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  54646. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  54647. var _this = this;
  54648. this.autoplay = false;
  54649. this.loop = false;
  54650. this.useCustomAttenuation = false;
  54651. this.spatialSound = false;
  54652. this.refDistance = 1;
  54653. this.rolloffFactor = 1;
  54654. this.maxDistance = 100;
  54655. this.distanceModel = "linear";
  54656. this._panningModel = "equalpower";
  54657. this._playbackRate = 1;
  54658. this._streaming = false;
  54659. this._startTime = 0;
  54660. this._startOffset = 0;
  54661. this._position = BABYLON.Vector3.Zero();
  54662. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  54663. this._volume = 1;
  54664. this._isReadyToPlay = false;
  54665. this.isPlaying = false;
  54666. this.isPaused = false;
  54667. this._isDirectional = false;
  54668. // Used if you'd like to create a directional sound.
  54669. // If not set, the sound will be omnidirectional
  54670. this._coneInnerAngle = 360;
  54671. this._coneOuterAngle = 360;
  54672. this._coneOuterGain = 0;
  54673. this._isOutputConnected = false;
  54674. this._urlType = "Unknown";
  54675. this.name = name;
  54676. this._scene = scene;
  54677. this._readyToPlayCallback = readyToPlayCallback;
  54678. // Default custom attenuation function is a linear attenuation
  54679. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  54680. if (currentDistance < maxDistance) {
  54681. return currentVolume * (1 - currentDistance / maxDistance);
  54682. }
  54683. else {
  54684. return 0;
  54685. }
  54686. };
  54687. if (options) {
  54688. this.autoplay = options.autoplay || false;
  54689. this.loop = options.loop || false;
  54690. // if volume === 0, we need another way to check this option
  54691. if (options.volume !== undefined) {
  54692. this._volume = options.volume;
  54693. }
  54694. this.spatialSound = options.spatialSound || false;
  54695. this.maxDistance = options.maxDistance || 100;
  54696. this.useCustomAttenuation = options.useCustomAttenuation || false;
  54697. this.rolloffFactor = options.rolloffFactor || 1;
  54698. this.refDistance = options.refDistance || 1;
  54699. this.distanceModel = options.distanceModel || "linear";
  54700. this._playbackRate = options.playbackRate || 1;
  54701. this._streaming = options.streaming || false;
  54702. }
  54703. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54704. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  54705. this._soundGain.gain.value = this._volume;
  54706. this._inputAudioNode = this._soundGain;
  54707. this._ouputAudioNode = this._soundGain;
  54708. if (this.spatialSound) {
  54709. this._createSpatialParameters();
  54710. }
  54711. this._scene.mainSoundTrack.AddSound(this);
  54712. var validParameter = true;
  54713. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  54714. if (urlOrArrayBuffer) {
  54715. if (typeof (urlOrArrayBuffer) === "string")
  54716. this._urlType = "String";
  54717. if (Array.isArray(urlOrArrayBuffer))
  54718. this._urlType = "Array";
  54719. if (urlOrArrayBuffer instanceof ArrayBuffer)
  54720. this._urlType = "ArrayBuffer";
  54721. var urls = [];
  54722. var codecSupportedFound = false;
  54723. switch (this._urlType) {
  54724. case "ArrayBuffer":
  54725. if (urlOrArrayBuffer.byteLength > 0) {
  54726. codecSupportedFound = true;
  54727. this._soundLoaded(urlOrArrayBuffer);
  54728. }
  54729. break;
  54730. case "String":
  54731. urls.push(urlOrArrayBuffer);
  54732. case "Array":
  54733. if (urls.length === 0)
  54734. urls = urlOrArrayBuffer;
  54735. // If we found a supported format, we load it immediately and stop the loop
  54736. for (var i = 0; i < urls.length; i++) {
  54737. var url = urls[i];
  54738. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  54739. codecSupportedFound = true;
  54740. }
  54741. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  54742. codecSupportedFound = true;
  54743. }
  54744. if (url.indexOf(".wav", url.length - 4) !== -1) {
  54745. codecSupportedFound = true;
  54746. }
  54747. if (url.indexOf("blob:") !== -1) {
  54748. codecSupportedFound = true;
  54749. }
  54750. if (codecSupportedFound) {
  54751. // Loading sound using XHR2
  54752. if (!this._streaming) {
  54753. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  54754. }
  54755. else {
  54756. this._htmlAudioElement = new Audio(url);
  54757. this._htmlAudioElement.controls = false;
  54758. this._htmlAudioElement.loop = this.loop;
  54759. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  54760. this._htmlAudioElement.preload = "auto";
  54761. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  54762. _this._isReadyToPlay = true;
  54763. if (_this.autoplay) {
  54764. _this.play();
  54765. }
  54766. if (_this._readyToPlayCallback) {
  54767. _this._readyToPlayCallback();
  54768. }
  54769. });
  54770. document.body.appendChild(this._htmlAudioElement);
  54771. }
  54772. break;
  54773. }
  54774. }
  54775. break;
  54776. default:
  54777. validParameter = false;
  54778. break;
  54779. }
  54780. if (!validParameter) {
  54781. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  54782. }
  54783. else {
  54784. if (!codecSupportedFound) {
  54785. this._isReadyToPlay = true;
  54786. // Simulating a ready to play event to avoid breaking code path
  54787. if (this._readyToPlayCallback) {
  54788. window.setTimeout(function () {
  54789. if (_this._readyToPlayCallback) {
  54790. _this._readyToPlayCallback();
  54791. }
  54792. }, 1000);
  54793. }
  54794. }
  54795. }
  54796. }
  54797. }
  54798. else {
  54799. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  54800. this._scene.mainSoundTrack.AddSound(this);
  54801. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  54802. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  54803. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  54804. }
  54805. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  54806. if (this._readyToPlayCallback) {
  54807. window.setTimeout(function () {
  54808. if (_this._readyToPlayCallback) {
  54809. _this._readyToPlayCallback();
  54810. }
  54811. }, 1000);
  54812. }
  54813. }
  54814. }
  54815. Sound.prototype.dispose = function () {
  54816. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  54817. if (this.isPlaying) {
  54818. this.stop();
  54819. }
  54820. this._isReadyToPlay = false;
  54821. if (this.soundTrackId === -1) {
  54822. this._scene.mainSoundTrack.RemoveSound(this);
  54823. }
  54824. else {
  54825. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  54826. }
  54827. if (this._soundGain) {
  54828. this._soundGain.disconnect();
  54829. this._soundGain = null;
  54830. }
  54831. if (this._soundPanner) {
  54832. this._soundPanner.disconnect();
  54833. this._soundPanner = null;
  54834. }
  54835. if (this._soundSource) {
  54836. this._soundSource.disconnect();
  54837. this._soundSource = null;
  54838. }
  54839. this._audioBuffer = null;
  54840. if (this._htmlAudioElement) {
  54841. this._htmlAudioElement.pause();
  54842. this._htmlAudioElement.src = "";
  54843. document.body.removeChild(this._htmlAudioElement);
  54844. }
  54845. if (this._connectedMesh && this._registerFunc) {
  54846. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  54847. this._connectedMesh = null;
  54848. }
  54849. }
  54850. };
  54851. Sound.prototype.isReady = function () {
  54852. return this._isReadyToPlay;
  54853. };
  54854. Sound.prototype._soundLoaded = function (audioData) {
  54855. var _this = this;
  54856. if (!BABYLON.Engine.audioEngine.audioContext) {
  54857. return;
  54858. }
  54859. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  54860. _this._audioBuffer = buffer;
  54861. _this._isReadyToPlay = true;
  54862. if (_this.autoplay) {
  54863. _this.play();
  54864. }
  54865. if (_this._readyToPlayCallback) {
  54866. _this._readyToPlayCallback();
  54867. }
  54868. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  54869. };
  54870. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  54871. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54872. this._audioBuffer = audioBuffer;
  54873. this._isReadyToPlay = true;
  54874. }
  54875. };
  54876. Sound.prototype.updateOptions = function (options) {
  54877. if (options) {
  54878. this.loop = options.loop || this.loop;
  54879. this.maxDistance = options.maxDistance || this.maxDistance;
  54880. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  54881. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  54882. this.refDistance = options.refDistance || this.refDistance;
  54883. this.distanceModel = options.distanceModel || this.distanceModel;
  54884. this._playbackRate = options.playbackRate || this._playbackRate;
  54885. this._updateSpatialParameters();
  54886. if (this.isPlaying) {
  54887. if (this._streaming) {
  54888. this._htmlAudioElement.playbackRate = this._playbackRate;
  54889. }
  54890. else {
  54891. if (this._soundSource) {
  54892. this._soundSource.playbackRate.value = this._playbackRate;
  54893. }
  54894. }
  54895. }
  54896. }
  54897. };
  54898. Sound.prototype._createSpatialParameters = function () {
  54899. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54900. if (this._scene.headphone) {
  54901. this._panningModel = "HRTF";
  54902. }
  54903. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  54904. this._updateSpatialParameters();
  54905. this._soundPanner.connect(this._ouputAudioNode);
  54906. this._inputAudioNode = this._soundPanner;
  54907. }
  54908. };
  54909. Sound.prototype._updateSpatialParameters = function () {
  54910. if (this.spatialSound && this._soundPanner) {
  54911. if (this.useCustomAttenuation) {
  54912. // Tricks to disable in a way embedded Web Audio attenuation
  54913. this._soundPanner.distanceModel = "linear";
  54914. this._soundPanner.maxDistance = Number.MAX_VALUE;
  54915. this._soundPanner.refDistance = 1;
  54916. this._soundPanner.rolloffFactor = 1;
  54917. this._soundPanner.panningModel = this._panningModel;
  54918. }
  54919. else {
  54920. this._soundPanner.distanceModel = this.distanceModel;
  54921. this._soundPanner.maxDistance = this.maxDistance;
  54922. this._soundPanner.refDistance = this.refDistance;
  54923. this._soundPanner.rolloffFactor = this.rolloffFactor;
  54924. this._soundPanner.panningModel = this._panningModel;
  54925. }
  54926. }
  54927. };
  54928. Sound.prototype.switchPanningModelToHRTF = function () {
  54929. this._panningModel = "HRTF";
  54930. this._switchPanningModel();
  54931. };
  54932. Sound.prototype.switchPanningModelToEqualPower = function () {
  54933. this._panningModel = "equalpower";
  54934. this._switchPanningModel();
  54935. };
  54936. Sound.prototype._switchPanningModel = function () {
  54937. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  54938. this._soundPanner.panningModel = this._panningModel;
  54939. }
  54940. };
  54941. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  54942. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54943. if (this._isOutputConnected) {
  54944. this._ouputAudioNode.disconnect();
  54945. }
  54946. this._ouputAudioNode.connect(soundTrackAudioNode);
  54947. this._isOutputConnected = true;
  54948. }
  54949. };
  54950. /**
  54951. * Transform this sound into a directional source
  54952. * @param coneInnerAngle Size of the inner cone in degree
  54953. * @param coneOuterAngle Size of the outer cone in degree
  54954. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  54955. */
  54956. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  54957. if (coneOuterAngle < coneInnerAngle) {
  54958. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  54959. return;
  54960. }
  54961. this._coneInnerAngle = coneInnerAngle;
  54962. this._coneOuterAngle = coneOuterAngle;
  54963. this._coneOuterGain = coneOuterGain;
  54964. this._isDirectional = true;
  54965. if (this.isPlaying && this.loop) {
  54966. this.stop();
  54967. this.play();
  54968. }
  54969. };
  54970. Sound.prototype.setPosition = function (newPosition) {
  54971. this._position = newPosition;
  54972. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  54973. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  54974. }
  54975. };
  54976. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  54977. this._localDirection = newLocalDirection;
  54978. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  54979. this._updateDirection();
  54980. }
  54981. };
  54982. Sound.prototype._updateDirection = function () {
  54983. if (!this._connectedMesh || !this._soundPanner) {
  54984. return;
  54985. }
  54986. var mat = this._connectedMesh.getWorldMatrix();
  54987. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  54988. direction.normalize();
  54989. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  54990. };
  54991. Sound.prototype.updateDistanceFromListener = function () {
  54992. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  54993. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  54994. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  54995. }
  54996. };
  54997. Sound.prototype.setAttenuationFunction = function (callback) {
  54998. this._customAttenuationFunction = callback;
  54999. };
  55000. /**
  55001. * Play the sound
  55002. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55003. * @param offset (optional) Start the sound setting it at a specific time
  55004. */
  55005. Sound.prototype.play = function (time, offset) {
  55006. var _this = this;
  55007. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55008. try {
  55009. if (this._startOffset < 0) {
  55010. time = -this._startOffset;
  55011. this._startOffset = 0;
  55012. }
  55013. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55014. if (!this._soundSource || !this._streamingSource) {
  55015. if (this.spatialSound && this._soundPanner) {
  55016. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55017. if (this._isDirectional) {
  55018. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55019. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55020. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55021. if (this._connectedMesh) {
  55022. this._updateDirection();
  55023. }
  55024. else {
  55025. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55026. }
  55027. }
  55028. }
  55029. }
  55030. if (this._streaming) {
  55031. if (!this._streamingSource) {
  55032. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55033. this._htmlAudioElement.onended = function () { _this._onended(); };
  55034. this._htmlAudioElement.playbackRate = this._playbackRate;
  55035. }
  55036. this._streamingSource.disconnect();
  55037. this._streamingSource.connect(this._inputAudioNode);
  55038. this._htmlAudioElement.play();
  55039. }
  55040. else {
  55041. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55042. this._soundSource.buffer = this._audioBuffer;
  55043. this._soundSource.connect(this._inputAudioNode);
  55044. this._soundSource.loop = this.loop;
  55045. this._soundSource.playbackRate.value = this._playbackRate;
  55046. this._soundSource.onended = function () { _this._onended(); };
  55047. if (this._soundSource.buffer) {
  55048. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55049. }
  55050. }
  55051. this._startTime = startTime;
  55052. this.isPlaying = true;
  55053. this.isPaused = false;
  55054. }
  55055. catch (ex) {
  55056. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55057. }
  55058. }
  55059. };
  55060. Sound.prototype._onended = function () {
  55061. this.isPlaying = false;
  55062. if (this.onended) {
  55063. this.onended();
  55064. }
  55065. };
  55066. /**
  55067. * Stop the sound
  55068. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55069. */
  55070. Sound.prototype.stop = function (time) {
  55071. if (this.isPlaying) {
  55072. if (this._streaming) {
  55073. this._htmlAudioElement.pause();
  55074. // Test needed for Firefox or it will generate an Invalid State Error
  55075. if (this._htmlAudioElement.currentTime > 0) {
  55076. this._htmlAudioElement.currentTime = 0;
  55077. }
  55078. }
  55079. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55080. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55081. this._soundSource.stop(stopTime);
  55082. this._soundSource.onended = function () { };
  55083. if (!this.isPaused) {
  55084. this._startOffset = 0;
  55085. }
  55086. }
  55087. this.isPlaying = false;
  55088. }
  55089. };
  55090. Sound.prototype.pause = function () {
  55091. if (this.isPlaying) {
  55092. this.isPaused = true;
  55093. if (this._streaming) {
  55094. this._htmlAudioElement.pause();
  55095. }
  55096. else if (BABYLON.Engine.audioEngine.audioContext) {
  55097. this.stop(0);
  55098. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55099. }
  55100. }
  55101. };
  55102. Sound.prototype.setVolume = function (newVolume, time) {
  55103. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55104. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55105. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55106. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55107. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55108. }
  55109. else {
  55110. this._soundGain.gain.value = newVolume;
  55111. }
  55112. }
  55113. this._volume = newVolume;
  55114. };
  55115. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55116. this._playbackRate = newPlaybackRate;
  55117. if (this.isPlaying) {
  55118. if (this._streaming) {
  55119. this._htmlAudioElement.playbackRate = this._playbackRate;
  55120. }
  55121. else if (this._soundSource) {
  55122. this._soundSource.playbackRate.value = this._playbackRate;
  55123. }
  55124. }
  55125. };
  55126. Sound.prototype.getVolume = function () {
  55127. return this._volume;
  55128. };
  55129. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55130. var _this = this;
  55131. if (this._connectedMesh && this._registerFunc) {
  55132. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55133. this._registerFunc = null;
  55134. }
  55135. this._connectedMesh = meshToConnectTo;
  55136. if (!this.spatialSound) {
  55137. this.spatialSound = true;
  55138. this._createSpatialParameters();
  55139. if (this.isPlaying && this.loop) {
  55140. this.stop();
  55141. this.play();
  55142. }
  55143. }
  55144. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55145. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55146. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55147. };
  55148. Sound.prototype.detachFromMesh = function () {
  55149. if (this._connectedMesh && this._registerFunc) {
  55150. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55151. this._registerFunc = null;
  55152. this._connectedMesh = null;
  55153. }
  55154. };
  55155. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55156. if (!node.getBoundingInfo) {
  55157. return;
  55158. }
  55159. var mesh = node;
  55160. var boundingInfo = mesh.getBoundingInfo();
  55161. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55162. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55163. this._updateDirection();
  55164. }
  55165. };
  55166. Sound.prototype.clone = function () {
  55167. var _this = this;
  55168. if (!this._streaming) {
  55169. var setBufferAndRun = function () {
  55170. if (_this._isReadyToPlay) {
  55171. clonedSound._audioBuffer = _this.getAudioBuffer();
  55172. clonedSound._isReadyToPlay = true;
  55173. if (clonedSound.autoplay) {
  55174. clonedSound.play();
  55175. }
  55176. }
  55177. else {
  55178. window.setTimeout(setBufferAndRun, 300);
  55179. }
  55180. };
  55181. var currentOptions = {
  55182. autoplay: this.autoplay, loop: this.loop,
  55183. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55184. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55185. refDistance: this.refDistance, distanceModel: this.distanceModel
  55186. };
  55187. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55188. if (this.useCustomAttenuation) {
  55189. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55190. }
  55191. clonedSound.setPosition(this._position);
  55192. clonedSound.setPlaybackRate(this._playbackRate);
  55193. setBufferAndRun();
  55194. return clonedSound;
  55195. }
  55196. else {
  55197. return null;
  55198. }
  55199. };
  55200. Sound.prototype.getAudioBuffer = function () {
  55201. return this._audioBuffer;
  55202. };
  55203. Sound.prototype.serialize = function () {
  55204. var serializationObject = {
  55205. name: this.name,
  55206. url: this.name,
  55207. autoplay: this.autoplay,
  55208. loop: this.loop,
  55209. volume: this._volume,
  55210. spatialSound: this.spatialSound,
  55211. maxDistance: this.maxDistance,
  55212. rolloffFactor: this.rolloffFactor,
  55213. refDistance: this.refDistance,
  55214. distanceModel: this.distanceModel,
  55215. playbackRate: this._playbackRate,
  55216. panningModel: this._panningModel,
  55217. soundTrackId: this.soundTrackId
  55218. };
  55219. if (this.spatialSound) {
  55220. if (this._connectedMesh)
  55221. serializationObject.connectedMeshId = this._connectedMesh.id;
  55222. serializationObject.position = this._position.asArray();
  55223. serializationObject.refDistance = this.refDistance;
  55224. serializationObject.distanceModel = this.distanceModel;
  55225. serializationObject.isDirectional = this._isDirectional;
  55226. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55227. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55228. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55229. serializationObject.coneOuterGain = this._coneOuterGain;
  55230. }
  55231. return serializationObject;
  55232. };
  55233. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55234. var soundName = parsedSound.name;
  55235. var soundUrl;
  55236. if (parsedSound.url) {
  55237. soundUrl = rootUrl + parsedSound.url;
  55238. }
  55239. else {
  55240. soundUrl = rootUrl + soundName;
  55241. }
  55242. var options = {
  55243. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55244. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55245. rolloffFactor: parsedSound.rolloffFactor,
  55246. refDistance: parsedSound.refDistance,
  55247. distanceModel: parsedSound.distanceModel,
  55248. playbackRate: parsedSound.playbackRate
  55249. };
  55250. var newSound;
  55251. if (!sourceSound) {
  55252. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55253. scene._addPendingData(newSound);
  55254. }
  55255. else {
  55256. var setBufferAndRun = function () {
  55257. if (sourceSound._isReadyToPlay) {
  55258. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55259. newSound._isReadyToPlay = true;
  55260. if (newSound.autoplay) {
  55261. newSound.play();
  55262. }
  55263. }
  55264. else {
  55265. window.setTimeout(setBufferAndRun, 300);
  55266. }
  55267. };
  55268. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55269. setBufferAndRun();
  55270. }
  55271. if (parsedSound.position) {
  55272. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55273. newSound.setPosition(soundPosition);
  55274. }
  55275. if (parsedSound.isDirectional) {
  55276. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55277. if (parsedSound.localDirectionToMesh) {
  55278. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55279. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55280. }
  55281. }
  55282. if (parsedSound.connectedMeshId) {
  55283. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55284. if (connectedMesh) {
  55285. newSound.attachToMesh(connectedMesh);
  55286. }
  55287. }
  55288. return newSound;
  55289. };
  55290. return Sound;
  55291. }());
  55292. BABYLON.Sound = Sound;
  55293. })(BABYLON || (BABYLON = {}));
  55294. //# sourceMappingURL=babylon.sound.js.map
  55295. var BABYLON;
  55296. (function (BABYLON) {
  55297. var SoundTrack = /** @class */ (function () {
  55298. function SoundTrack(scene, options) {
  55299. this.id = -1;
  55300. this._isMainTrack = false;
  55301. this._isInitialized = false;
  55302. this._scene = scene;
  55303. this.soundCollection = new Array();
  55304. this._options = options;
  55305. if (!this._isMainTrack) {
  55306. this._scene.soundTracks.push(this);
  55307. this.id = this._scene.soundTracks.length - 1;
  55308. }
  55309. }
  55310. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55311. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55312. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55313. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55314. if (this._options) {
  55315. if (this._options.volume) {
  55316. this._outputAudioNode.gain.value = this._options.volume;
  55317. }
  55318. if (this._options.mainTrack) {
  55319. this._isMainTrack = this._options.mainTrack;
  55320. }
  55321. }
  55322. this._isInitialized = true;
  55323. }
  55324. };
  55325. SoundTrack.prototype.dispose = function () {
  55326. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55327. if (this._connectedAnalyser) {
  55328. this._connectedAnalyser.stopDebugCanvas();
  55329. }
  55330. while (this.soundCollection.length) {
  55331. this.soundCollection[0].dispose();
  55332. }
  55333. if (this._outputAudioNode) {
  55334. this._outputAudioNode.disconnect();
  55335. }
  55336. this._outputAudioNode = null;
  55337. }
  55338. };
  55339. SoundTrack.prototype.AddSound = function (sound) {
  55340. if (!this._isInitialized) {
  55341. this._initializeSoundTrackAudioGraph();
  55342. }
  55343. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55344. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55345. }
  55346. if (sound.soundTrackId) {
  55347. if (sound.soundTrackId === -1) {
  55348. this._scene.mainSoundTrack.RemoveSound(sound);
  55349. }
  55350. else {
  55351. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55352. }
  55353. }
  55354. this.soundCollection.push(sound);
  55355. sound.soundTrackId = this.id;
  55356. };
  55357. SoundTrack.prototype.RemoveSound = function (sound) {
  55358. var index = this.soundCollection.indexOf(sound);
  55359. if (index !== -1) {
  55360. this.soundCollection.splice(index, 1);
  55361. }
  55362. };
  55363. SoundTrack.prototype.setVolume = function (newVolume) {
  55364. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55365. this._outputAudioNode.gain.value = newVolume;
  55366. }
  55367. };
  55368. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55369. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55370. for (var i = 0; i < this.soundCollection.length; i++) {
  55371. this.soundCollection[i].switchPanningModelToHRTF();
  55372. }
  55373. }
  55374. };
  55375. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55376. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55377. for (var i = 0; i < this.soundCollection.length; i++) {
  55378. this.soundCollection[i].switchPanningModelToEqualPower();
  55379. }
  55380. }
  55381. };
  55382. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55383. if (this._connectedAnalyser) {
  55384. this._connectedAnalyser.stopDebugCanvas();
  55385. }
  55386. this._connectedAnalyser = analyser;
  55387. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55388. this._outputAudioNode.disconnect();
  55389. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55390. }
  55391. };
  55392. return SoundTrack;
  55393. }());
  55394. BABYLON.SoundTrack = SoundTrack;
  55395. })(BABYLON || (BABYLON = {}));
  55396. //# sourceMappingURL=babylon.soundtrack.js.map
  55397. var BABYLON;
  55398. (function (BABYLON) {
  55399. var Analyser = /** @class */ (function () {
  55400. function Analyser(scene) {
  55401. this.SMOOTHING = 0.75;
  55402. this.FFT_SIZE = 512;
  55403. this.BARGRAPHAMPLITUDE = 256;
  55404. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55405. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55406. this._scene = scene;
  55407. this._audioEngine = BABYLON.Engine.audioEngine;
  55408. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55409. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55410. this._webAudioAnalyser.minDecibels = -140;
  55411. this._webAudioAnalyser.maxDecibels = 0;
  55412. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55413. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55414. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55415. }
  55416. }
  55417. Analyser.prototype.getFrequencyBinCount = function () {
  55418. if (this._audioEngine.canUseWebAudio) {
  55419. return this._webAudioAnalyser.frequencyBinCount;
  55420. }
  55421. else {
  55422. return 0;
  55423. }
  55424. };
  55425. Analyser.prototype.getByteFrequencyData = function () {
  55426. if (this._audioEngine.canUseWebAudio) {
  55427. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55428. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55429. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55430. }
  55431. return this._byteFreqs;
  55432. };
  55433. Analyser.prototype.getByteTimeDomainData = function () {
  55434. if (this._audioEngine.canUseWebAudio) {
  55435. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55436. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55437. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55438. }
  55439. return this._byteTime;
  55440. };
  55441. Analyser.prototype.getFloatFrequencyData = function () {
  55442. if (this._audioEngine.canUseWebAudio) {
  55443. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55444. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55445. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55446. }
  55447. return this._floatFreqs;
  55448. };
  55449. Analyser.prototype.drawDebugCanvas = function () {
  55450. var _this = this;
  55451. if (this._audioEngine.canUseWebAudio) {
  55452. if (!this._debugCanvas) {
  55453. this._debugCanvas = document.createElement("canvas");
  55454. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55455. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55456. this._debugCanvas.style.position = "absolute";
  55457. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55458. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55459. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55460. document.body.appendChild(this._debugCanvas);
  55461. this._registerFunc = function () {
  55462. _this.drawDebugCanvas();
  55463. };
  55464. this._scene.registerBeforeRender(this._registerFunc);
  55465. }
  55466. if (this._registerFunc && this._debugCanvasContext) {
  55467. var workingArray = this.getByteFrequencyData();
  55468. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55469. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55470. // Draw the frequency domain chart.
  55471. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55472. var value = workingArray[i];
  55473. var percent = value / this.BARGRAPHAMPLITUDE;
  55474. var height = this.DEBUGCANVASSIZE.height * percent;
  55475. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55476. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55477. var hue = i / this.getFrequencyBinCount() * 360;
  55478. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55479. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55480. }
  55481. }
  55482. }
  55483. };
  55484. Analyser.prototype.stopDebugCanvas = function () {
  55485. if (this._debugCanvas) {
  55486. if (this._registerFunc) {
  55487. this._scene.unregisterBeforeRender(this._registerFunc);
  55488. this._registerFunc = null;
  55489. }
  55490. document.body.removeChild(this._debugCanvas);
  55491. this._debugCanvas = null;
  55492. this._debugCanvasContext = null;
  55493. }
  55494. };
  55495. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55496. if (this._audioEngine.canUseWebAudio) {
  55497. inputAudioNode.connect(this._webAudioAnalyser);
  55498. this._webAudioAnalyser.connect(outputAudioNode);
  55499. }
  55500. };
  55501. Analyser.prototype.dispose = function () {
  55502. if (this._audioEngine.canUseWebAudio) {
  55503. this._webAudioAnalyser.disconnect();
  55504. }
  55505. };
  55506. return Analyser;
  55507. }());
  55508. BABYLON.Analyser = Analyser;
  55509. })(BABYLON || (BABYLON = {}));
  55510. //# sourceMappingURL=babylon.analyser.js.map
  55511. var BABYLON;
  55512. (function (BABYLON) {
  55513. var CubeTexture = /** @class */ (function (_super) {
  55514. __extends(CubeTexture, _super);
  55515. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55516. if (extensions === void 0) { extensions = null; }
  55517. if (noMipmap === void 0) { noMipmap = false; }
  55518. if (files === void 0) { files = null; }
  55519. if (onLoad === void 0) { onLoad = null; }
  55520. if (onError === void 0) { onError = null; }
  55521. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55522. if (prefiltered === void 0) { prefiltered = false; }
  55523. if (forcedExtension === void 0) { forcedExtension = null; }
  55524. var _this = _super.call(this, scene) || this;
  55525. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55526. _this.name = rootUrl;
  55527. _this.url = rootUrl;
  55528. _this._noMipmap = noMipmap;
  55529. _this.hasAlpha = false;
  55530. _this._format = format;
  55531. _this._prefiltered = prefiltered;
  55532. _this.isCube = true;
  55533. _this._textureMatrix = BABYLON.Matrix.Identity();
  55534. if (prefiltered) {
  55535. _this.gammaSpace = false;
  55536. }
  55537. if (!rootUrl && !files) {
  55538. return _this;
  55539. }
  55540. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  55541. var lastDot = rootUrl.lastIndexOf(".");
  55542. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  55543. var isDDS = (extension === ".dds");
  55544. if (!files) {
  55545. if (!isDDS && !extensions) {
  55546. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  55547. }
  55548. files = [];
  55549. if (extensions) {
  55550. for (var index = 0; index < extensions.length; index++) {
  55551. files.push(rootUrl + extensions[index]);
  55552. }
  55553. }
  55554. }
  55555. _this._files = files;
  55556. if (!_this._texture) {
  55557. if (!scene.useDelayedTextureLoading) {
  55558. if (prefiltered) {
  55559. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  55560. }
  55561. else {
  55562. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  55563. }
  55564. }
  55565. else {
  55566. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55567. }
  55568. }
  55569. else if (onLoad) {
  55570. if (_this._texture.isReady) {
  55571. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  55572. }
  55573. else {
  55574. _this._texture.onLoadedObservable.add(onLoad);
  55575. }
  55576. }
  55577. return _this;
  55578. }
  55579. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  55580. return new CubeTexture("", scene, null, noMipmap, files);
  55581. };
  55582. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  55583. if (forcedExtension === void 0) { forcedExtension = null; }
  55584. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  55585. };
  55586. // Methods
  55587. CubeTexture.prototype.delayLoad = function () {
  55588. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55589. return;
  55590. }
  55591. var scene = this.getScene();
  55592. if (!scene) {
  55593. return;
  55594. }
  55595. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55596. this._texture = this._getFromCache(this.url, this._noMipmap);
  55597. if (!this._texture) {
  55598. if (this._prefiltered) {
  55599. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  55600. }
  55601. else {
  55602. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  55603. }
  55604. }
  55605. };
  55606. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  55607. return this._textureMatrix;
  55608. };
  55609. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  55610. this._textureMatrix = value;
  55611. };
  55612. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55613. var texture = BABYLON.SerializationHelper.Parse(function () {
  55614. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  55615. }, parsedTexture, scene);
  55616. // Animations
  55617. if (parsedTexture.animations) {
  55618. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  55619. var parsedAnimation = parsedTexture.animations[animationIndex];
  55620. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55621. }
  55622. }
  55623. return texture;
  55624. };
  55625. CubeTexture.prototype.clone = function () {
  55626. var _this = this;
  55627. return BABYLON.SerializationHelper.Clone(function () {
  55628. var scene = _this.getScene();
  55629. if (!scene) {
  55630. return _this;
  55631. }
  55632. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  55633. }, this);
  55634. };
  55635. return CubeTexture;
  55636. }(BABYLON.BaseTexture));
  55637. BABYLON.CubeTexture = CubeTexture;
  55638. })(BABYLON || (BABYLON = {}));
  55639. //# sourceMappingURL=babylon.cubeTexture.js.map
  55640. var BABYLON;
  55641. (function (BABYLON) {
  55642. var RenderTargetTexture = /** @class */ (function (_super) {
  55643. __extends(RenderTargetTexture, _super);
  55644. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  55645. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  55646. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55647. if (isCube === void 0) { isCube = false; }
  55648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55649. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55650. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  55651. if (isMulti === void 0) { isMulti = false; }
  55652. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55653. _this.isCube = isCube;
  55654. /**
  55655. * Use this list to define the list of mesh you want to render.
  55656. */
  55657. _this.renderList = new Array();
  55658. _this.renderParticles = true;
  55659. _this.renderSprites = false;
  55660. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  55661. _this.ignoreCameraViewport = false;
  55662. // Events
  55663. /**
  55664. * An event triggered when the texture is unbind.
  55665. * @type {BABYLON.Observable}
  55666. */
  55667. _this.onBeforeBindObservable = new BABYLON.Observable();
  55668. /**
  55669. * An event triggered when the texture is unbind.
  55670. * @type {BABYLON.Observable}
  55671. */
  55672. _this.onAfterUnbindObservable = new BABYLON.Observable();
  55673. /**
  55674. * An event triggered before rendering the texture
  55675. * @type {BABYLON.Observable}
  55676. */
  55677. _this.onBeforeRenderObservable = new BABYLON.Observable();
  55678. /**
  55679. * An event triggered after rendering the texture
  55680. * @type {BABYLON.Observable}
  55681. */
  55682. _this.onAfterRenderObservable = new BABYLON.Observable();
  55683. /**
  55684. * An event triggered after the texture clear
  55685. * @type {BABYLON.Observable}
  55686. */
  55687. _this.onClearObservable = new BABYLON.Observable();
  55688. _this._currentRefreshId = -1;
  55689. _this._refreshRate = 1;
  55690. _this._samples = 1;
  55691. scene = _this.getScene();
  55692. if (!scene) {
  55693. return _this;
  55694. }
  55695. _this._engine = scene.getEngine();
  55696. _this.name = name;
  55697. _this.isRenderTarget = true;
  55698. _this._initialSizeParameter = size;
  55699. _this._processSizeParameter(size);
  55700. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  55701. });
  55702. _this._generateMipMaps = generateMipMaps ? true : false;
  55703. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  55704. // Rendering groups
  55705. _this._renderingManager = new BABYLON.RenderingManager(scene);
  55706. if (isMulti) {
  55707. return _this;
  55708. }
  55709. _this._renderTargetOptions = {
  55710. generateMipMaps: generateMipMaps,
  55711. type: type,
  55712. samplingMode: samplingMode,
  55713. generateDepthBuffer: generateDepthBuffer,
  55714. generateStencilBuffer: generateStencilBuffer
  55715. };
  55716. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  55717. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55718. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55719. }
  55720. if (isCube) {
  55721. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  55722. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  55723. _this._textureMatrix = BABYLON.Matrix.Identity();
  55724. }
  55725. else {
  55726. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  55727. }
  55728. return _this;
  55729. }
  55730. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  55731. get: function () {
  55732. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  55733. },
  55734. enumerable: true,
  55735. configurable: true
  55736. });
  55737. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  55738. get: function () {
  55739. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  55740. },
  55741. enumerable: true,
  55742. configurable: true
  55743. });
  55744. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  55745. get: function () {
  55746. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  55747. },
  55748. enumerable: true,
  55749. configurable: true
  55750. });
  55751. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  55752. set: function (callback) {
  55753. if (this._onAfterUnbindObserver) {
  55754. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  55755. }
  55756. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  55757. },
  55758. enumerable: true,
  55759. configurable: true
  55760. });
  55761. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  55762. set: function (callback) {
  55763. if (this._onBeforeRenderObserver) {
  55764. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55765. }
  55766. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55767. },
  55768. enumerable: true,
  55769. configurable: true
  55770. });
  55771. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  55772. set: function (callback) {
  55773. if (this._onAfterRenderObserver) {
  55774. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55775. }
  55776. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55777. },
  55778. enumerable: true,
  55779. configurable: true
  55780. });
  55781. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  55782. set: function (callback) {
  55783. if (this._onClearObserver) {
  55784. this.onClearObservable.remove(this._onClearObserver);
  55785. }
  55786. this._onClearObserver = this.onClearObservable.add(callback);
  55787. },
  55788. enumerable: true,
  55789. configurable: true
  55790. });
  55791. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  55792. get: function () {
  55793. return this._renderTargetOptions;
  55794. },
  55795. enumerable: true,
  55796. configurable: true
  55797. });
  55798. RenderTargetTexture.prototype._onRatioRescale = function () {
  55799. if (this._sizeRatio) {
  55800. this.resize(this._initialSizeParameter);
  55801. }
  55802. };
  55803. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  55804. if (size.ratio) {
  55805. this._sizeRatio = size.ratio;
  55806. this._size = {
  55807. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  55808. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  55809. };
  55810. }
  55811. else {
  55812. this._size = size;
  55813. }
  55814. };
  55815. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  55816. get: function () {
  55817. return this._samples;
  55818. },
  55819. set: function (value) {
  55820. if (this._samples === value) {
  55821. return;
  55822. }
  55823. var scene = this.getScene();
  55824. if (!scene) {
  55825. return;
  55826. }
  55827. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  55828. },
  55829. enumerable: true,
  55830. configurable: true
  55831. });
  55832. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  55833. this._currentRefreshId = -1;
  55834. };
  55835. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  55836. get: function () {
  55837. return this._refreshRate;
  55838. },
  55839. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55840. set: function (value) {
  55841. this._refreshRate = value;
  55842. this.resetRefreshCounter();
  55843. },
  55844. enumerable: true,
  55845. configurable: true
  55846. });
  55847. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  55848. if (!this._postProcessManager) {
  55849. var scene = this.getScene();
  55850. if (!scene) {
  55851. return;
  55852. }
  55853. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  55854. this._postProcesses = new Array();
  55855. }
  55856. this._postProcesses.push(postProcess);
  55857. this._postProcesses[0].autoClear = false;
  55858. };
  55859. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  55860. if (!this._postProcesses) {
  55861. return;
  55862. }
  55863. if (dispose) {
  55864. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  55865. var postProcess = _a[_i];
  55866. postProcess.dispose();
  55867. }
  55868. }
  55869. this._postProcesses = [];
  55870. };
  55871. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  55872. if (!this._postProcesses) {
  55873. return;
  55874. }
  55875. var index = this._postProcesses.indexOf(postProcess);
  55876. if (index === -1) {
  55877. return;
  55878. }
  55879. this._postProcesses.splice(index, 1);
  55880. if (this._postProcesses.length > 0) {
  55881. this._postProcesses[0].autoClear = false;
  55882. }
  55883. };
  55884. RenderTargetTexture.prototype._shouldRender = function () {
  55885. if (this._currentRefreshId === -1) {
  55886. this._currentRefreshId = 1;
  55887. return true;
  55888. }
  55889. if (this.refreshRate === this._currentRefreshId) {
  55890. this._currentRefreshId = 1;
  55891. return true;
  55892. }
  55893. this._currentRefreshId++;
  55894. return false;
  55895. };
  55896. RenderTargetTexture.prototype.getRenderSize = function () {
  55897. if (this._size.width) {
  55898. return this._size.width;
  55899. }
  55900. return this._size;
  55901. };
  55902. RenderTargetTexture.prototype.getRenderWidth = function () {
  55903. if (this._size.width) {
  55904. return this._size.width;
  55905. }
  55906. return this._size;
  55907. };
  55908. RenderTargetTexture.prototype.getRenderHeight = function () {
  55909. if (this._size.width) {
  55910. return this._size.height;
  55911. }
  55912. return this._size;
  55913. };
  55914. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  55915. get: function () {
  55916. return true;
  55917. },
  55918. enumerable: true,
  55919. configurable: true
  55920. });
  55921. RenderTargetTexture.prototype.scale = function (ratio) {
  55922. var newSize = this.getRenderSize() * ratio;
  55923. this.resize(newSize);
  55924. };
  55925. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  55926. if (this.isCube) {
  55927. return this._textureMatrix;
  55928. }
  55929. return _super.prototype.getReflectionTextureMatrix.call(this);
  55930. };
  55931. RenderTargetTexture.prototype.resize = function (size) {
  55932. this.releaseInternalTexture();
  55933. var scene = this.getScene();
  55934. if (!scene) {
  55935. return;
  55936. }
  55937. this._processSizeParameter(size);
  55938. if (this.isCube) {
  55939. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  55940. }
  55941. else {
  55942. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  55943. }
  55944. };
  55945. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  55946. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  55947. if (dumpForDebug === void 0) { dumpForDebug = false; }
  55948. var scene = this.getScene();
  55949. if (!scene) {
  55950. return;
  55951. }
  55952. var engine = scene.getEngine();
  55953. if (this.useCameraPostProcesses !== undefined) {
  55954. useCameraPostProcess = this.useCameraPostProcesses;
  55955. }
  55956. if (this._waitingRenderList) {
  55957. this.renderList = [];
  55958. for (var index = 0; index < this._waitingRenderList.length; index++) {
  55959. var id = this._waitingRenderList[index];
  55960. var mesh_1 = scene.getMeshByID(id);
  55961. if (mesh_1) {
  55962. this.renderList.push(mesh_1);
  55963. }
  55964. }
  55965. delete this._waitingRenderList;
  55966. }
  55967. // Is predicate defined?
  55968. if (this.renderListPredicate) {
  55969. if (this.renderList) {
  55970. this.renderList.splice(0); // Clear previous renderList
  55971. }
  55972. else {
  55973. this.renderList = [];
  55974. }
  55975. var scene = this.getScene();
  55976. if (!scene) {
  55977. return;
  55978. }
  55979. var sceneMeshes = scene.meshes;
  55980. for (var index = 0; index < sceneMeshes.length; index++) {
  55981. var mesh = sceneMeshes[index];
  55982. if (this.renderListPredicate(mesh)) {
  55983. this.renderList.push(mesh);
  55984. }
  55985. }
  55986. }
  55987. this.onBeforeBindObservable.notifyObservers(this);
  55988. // Set custom projection.
  55989. // Needs to be before binding to prevent changing the aspect ratio.
  55990. var camera;
  55991. if (this.activeCamera) {
  55992. camera = this.activeCamera;
  55993. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  55994. if (this.activeCamera !== scene.activeCamera) {
  55995. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  55996. }
  55997. }
  55998. else {
  55999. camera = scene.activeCamera;
  56000. if (camera) {
  56001. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56002. }
  56003. }
  56004. // Prepare renderingManager
  56005. this._renderingManager.reset();
  56006. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56007. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56008. var sceneRenderId = scene.getRenderId();
  56009. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56010. var mesh = currentRenderList[meshIndex];
  56011. if (mesh) {
  56012. if (!mesh.isReady()) {
  56013. // Reset _currentRefreshId
  56014. this.resetRefreshCounter();
  56015. continue;
  56016. }
  56017. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56018. var isMasked = void 0;
  56019. if (!this.renderList && camera) {
  56020. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56021. }
  56022. else {
  56023. isMasked = false;
  56024. }
  56025. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56026. mesh._activate(sceneRenderId);
  56027. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56028. var subMesh = mesh.subMeshes[subIndex];
  56029. scene._activeIndices.addCount(subMesh.indexCount, false);
  56030. this._renderingManager.dispatch(subMesh, mesh);
  56031. }
  56032. }
  56033. }
  56034. }
  56035. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56036. var particleSystem = scene.particleSystems[particleIndex];
  56037. var emitter = particleSystem.emitter;
  56038. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56039. continue;
  56040. }
  56041. if (currentRenderList.indexOf(emitter) >= 0) {
  56042. this._renderingManager.dispatchParticles(particleSystem);
  56043. }
  56044. }
  56045. if (this.isCube) {
  56046. for (var face = 0; face < 6; face++) {
  56047. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56048. scene.incrementRenderId();
  56049. scene.resetCachedMaterial();
  56050. }
  56051. }
  56052. else {
  56053. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56054. }
  56055. this.onAfterUnbindObservable.notifyObservers(this);
  56056. if (scene.activeCamera) {
  56057. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56058. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56059. }
  56060. engine.setViewport(scene.activeCamera.viewport);
  56061. }
  56062. scene.resetCachedMaterial();
  56063. };
  56064. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56065. var minimum = 128;
  56066. var x = renderDimension * scale;
  56067. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56068. // Ensure we don't exceed the render dimension (while staying POT)
  56069. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56070. };
  56071. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56072. var _this = this;
  56073. if (!this._texture) {
  56074. return;
  56075. }
  56076. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56077. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56078. });
  56079. };
  56080. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56081. var scene = this.getScene();
  56082. if (!scene) {
  56083. return;
  56084. }
  56085. var engine = scene.getEngine();
  56086. if (!this._texture) {
  56087. return;
  56088. }
  56089. // Bind
  56090. if (this._postProcessManager) {
  56091. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56092. }
  56093. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56094. if (this._texture) {
  56095. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56096. }
  56097. }
  56098. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56099. // Clear
  56100. if (this.onClearObservable.hasObservers()) {
  56101. this.onClearObservable.notifyObservers(engine);
  56102. }
  56103. else {
  56104. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56105. }
  56106. if (!this._doNotChangeAspectRatio) {
  56107. scene.updateTransformMatrix(true);
  56108. }
  56109. // Render
  56110. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56111. if (this._postProcessManager) {
  56112. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56113. }
  56114. else if (useCameraPostProcess) {
  56115. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56116. }
  56117. if (!this._doNotChangeAspectRatio) {
  56118. scene.updateTransformMatrix(true);
  56119. }
  56120. // Dump ?
  56121. if (dumpForDebug) {
  56122. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56123. }
  56124. // Unbind
  56125. if (!this.isCube || faceIndex === 5) {
  56126. if (this.isCube) {
  56127. if (faceIndex === 5) {
  56128. engine.generateMipMapsForCubemap(this._texture);
  56129. }
  56130. }
  56131. this.unbindFrameBuffer(engine, faceIndex);
  56132. }
  56133. else {
  56134. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56135. }
  56136. };
  56137. /**
  56138. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56139. * This allowed control for front to back rendering or reversly depending of the special needs.
  56140. *
  56141. * @param renderingGroupId The rendering group id corresponding to its index
  56142. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56143. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56144. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56145. */
  56146. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56147. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56148. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56149. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56150. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56151. };
  56152. /**
  56153. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56154. *
  56155. * @param renderingGroupId The rendering group id corresponding to its index
  56156. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56157. */
  56158. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56159. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56160. };
  56161. RenderTargetTexture.prototype.clone = function () {
  56162. var textureSize = this.getSize();
  56163. 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);
  56164. // Base texture
  56165. newTexture.hasAlpha = this.hasAlpha;
  56166. newTexture.level = this.level;
  56167. // RenderTarget Texture
  56168. newTexture.coordinatesMode = this.coordinatesMode;
  56169. if (this.renderList) {
  56170. newTexture.renderList = this.renderList.slice(0);
  56171. }
  56172. return newTexture;
  56173. };
  56174. RenderTargetTexture.prototype.serialize = function () {
  56175. if (!this.name) {
  56176. return null;
  56177. }
  56178. var serializationObject = _super.prototype.serialize.call(this);
  56179. serializationObject.renderTargetSize = this.getRenderSize();
  56180. serializationObject.renderList = [];
  56181. if (this.renderList) {
  56182. for (var index = 0; index < this.renderList.length; index++) {
  56183. serializationObject.renderList.push(this.renderList[index].id);
  56184. }
  56185. }
  56186. return serializationObject;
  56187. };
  56188. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56189. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56190. var objBuffer = this.getInternalTexture();
  56191. var scene = this.getScene();
  56192. if (objBuffer && scene) {
  56193. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56194. }
  56195. };
  56196. RenderTargetTexture.prototype.dispose = function () {
  56197. if (this._postProcessManager) {
  56198. this._postProcessManager.dispose();
  56199. this._postProcessManager = null;
  56200. }
  56201. this.clearPostProcesses(true);
  56202. if (this._resizeObserver) {
  56203. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56204. this._resizeObserver = null;
  56205. }
  56206. this.renderList = null;
  56207. // Remove from custom render targets
  56208. var scene = this.getScene();
  56209. if (!scene) {
  56210. return;
  56211. }
  56212. var index = scene.customRenderTargets.indexOf(this);
  56213. if (index >= 0) {
  56214. scene.customRenderTargets.splice(index, 1);
  56215. }
  56216. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56217. var camera = _a[_i];
  56218. index = camera.customRenderTargets.indexOf(this);
  56219. if (index >= 0) {
  56220. camera.customRenderTargets.splice(index, 1);
  56221. }
  56222. }
  56223. _super.prototype.dispose.call(this);
  56224. };
  56225. RenderTargetTexture.prototype._rebuild = function () {
  56226. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56227. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56228. }
  56229. if (this._postProcessManager) {
  56230. this._postProcessManager._rebuild();
  56231. }
  56232. };
  56233. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56234. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56235. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56236. return RenderTargetTexture;
  56237. }(BABYLON.Texture));
  56238. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56239. })(BABYLON || (BABYLON = {}));
  56240. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56241. var BABYLON;
  56242. (function (BABYLON) {
  56243. ;
  56244. var MultiRenderTarget = /** @class */ (function (_super) {
  56245. __extends(MultiRenderTarget, _super);
  56246. function MultiRenderTarget(name, size, count, scene, options) {
  56247. var _this = this;
  56248. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56249. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56250. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56251. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56252. _this._engine = scene.getEngine();
  56253. if (!_this.isSupported) {
  56254. _this.dispose();
  56255. return;
  56256. }
  56257. var types = [];
  56258. var samplingModes = [];
  56259. for (var i = 0; i < count; i++) {
  56260. if (options && options.types && options.types[i] !== undefined) {
  56261. types.push(options.types[i]);
  56262. }
  56263. else {
  56264. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56265. }
  56266. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56267. samplingModes.push(options.samplingModes[i]);
  56268. }
  56269. else {
  56270. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56271. }
  56272. }
  56273. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56274. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56275. _this._size = size;
  56276. _this._multiRenderTargetOptions = {
  56277. samplingModes: samplingModes,
  56278. generateMipMaps: generateMipMaps,
  56279. generateDepthBuffer: generateDepthBuffer,
  56280. generateStencilBuffer: generateStencilBuffer,
  56281. generateDepthTexture: generateDepthTexture,
  56282. types: types,
  56283. textureCount: count
  56284. };
  56285. _this._createInternalTextures();
  56286. _this._createTextures();
  56287. return _this;
  56288. }
  56289. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56290. get: function () {
  56291. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56292. },
  56293. enumerable: true,
  56294. configurable: true
  56295. });
  56296. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56297. get: function () {
  56298. return this._textures;
  56299. },
  56300. enumerable: true,
  56301. configurable: true
  56302. });
  56303. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56304. get: function () {
  56305. return this._textures[this._textures.length - 1];
  56306. },
  56307. enumerable: true,
  56308. configurable: true
  56309. });
  56310. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56311. set: function (wrap) {
  56312. if (this._textures) {
  56313. for (var i = 0; i < this._textures.length; i++) {
  56314. this._textures[i].wrapU = wrap;
  56315. }
  56316. }
  56317. },
  56318. enumerable: true,
  56319. configurable: true
  56320. });
  56321. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56322. set: function (wrap) {
  56323. if (this._textures) {
  56324. for (var i = 0; i < this._textures.length; i++) {
  56325. this._textures[i].wrapV = wrap;
  56326. }
  56327. }
  56328. },
  56329. enumerable: true,
  56330. configurable: true
  56331. });
  56332. MultiRenderTarget.prototype._rebuild = function () {
  56333. this.releaseInternalTextures();
  56334. this._createInternalTextures();
  56335. for (var i = 0; i < this._internalTextures.length; i++) {
  56336. var texture = this._textures[i];
  56337. texture._texture = this._internalTextures[i];
  56338. }
  56339. // Keeps references to frame buffer and stencil/depth buffer
  56340. this._texture = this._internalTextures[0];
  56341. };
  56342. MultiRenderTarget.prototype._createInternalTextures = function () {
  56343. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56344. };
  56345. MultiRenderTarget.prototype._createTextures = function () {
  56346. this._textures = [];
  56347. for (var i = 0; i < this._internalTextures.length; i++) {
  56348. var texture = new BABYLON.Texture(null, this.getScene());
  56349. texture._texture = this._internalTextures[i];
  56350. this._textures.push(texture);
  56351. }
  56352. // Keeps references to frame buffer and stencil/depth buffer
  56353. this._texture = this._internalTextures[0];
  56354. };
  56355. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56356. get: function () {
  56357. return this._samples;
  56358. },
  56359. set: function (value) {
  56360. if (this._samples === value) {
  56361. return;
  56362. }
  56363. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56364. },
  56365. enumerable: true,
  56366. configurable: true
  56367. });
  56368. MultiRenderTarget.prototype.resize = function (size) {
  56369. this.releaseInternalTextures();
  56370. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56371. this._createInternalTextures();
  56372. };
  56373. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56374. var _this = this;
  56375. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56376. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56377. });
  56378. };
  56379. MultiRenderTarget.prototype.dispose = function () {
  56380. this.releaseInternalTextures();
  56381. _super.prototype.dispose.call(this);
  56382. };
  56383. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56384. if (!this._internalTextures) {
  56385. return;
  56386. }
  56387. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56388. if (this._internalTextures[i] !== undefined) {
  56389. this._internalTextures[i].dispose();
  56390. this._internalTextures.splice(i, 1);
  56391. }
  56392. }
  56393. };
  56394. return MultiRenderTarget;
  56395. }(BABYLON.RenderTargetTexture));
  56396. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56397. })(BABYLON || (BABYLON = {}));
  56398. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56399. var BABYLON;
  56400. (function (BABYLON) {
  56401. var MirrorTexture = /** @class */ (function (_super) {
  56402. __extends(MirrorTexture, _super);
  56403. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56404. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56406. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56407. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56408. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56409. _this._transformMatrix = BABYLON.Matrix.Zero();
  56410. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56411. _this._adaptiveBlurKernel = 0;
  56412. _this._blurKernelX = 0;
  56413. _this._blurKernelY = 0;
  56414. _this._blurRatio = 1.0;
  56415. _this.ignoreCameraViewport = true;
  56416. _this.onBeforeRenderObservable.add(function () {
  56417. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56418. _this._savedViewMatrix = scene.getViewMatrix();
  56419. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56420. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56421. scene.clipPlane = _this.mirrorPlane;
  56422. scene.getEngine().cullBackFaces = false;
  56423. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56424. });
  56425. _this.onAfterRenderObservable.add(function () {
  56426. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56427. scene.getEngine().cullBackFaces = true;
  56428. scene._mirroredCameraPosition = null;
  56429. delete scene.clipPlane;
  56430. });
  56431. return _this;
  56432. }
  56433. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56434. get: function () {
  56435. return this._blurRatio;
  56436. },
  56437. set: function (value) {
  56438. if (this._blurRatio === value) {
  56439. return;
  56440. }
  56441. this._blurRatio = value;
  56442. this._preparePostProcesses();
  56443. },
  56444. enumerable: true,
  56445. configurable: true
  56446. });
  56447. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56448. set: function (value) {
  56449. this._adaptiveBlurKernel = value;
  56450. this._autoComputeBlurKernel();
  56451. },
  56452. enumerable: true,
  56453. configurable: true
  56454. });
  56455. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56456. set: function (value) {
  56457. this.blurKernelX = value;
  56458. this.blurKernelY = value;
  56459. },
  56460. enumerable: true,
  56461. configurable: true
  56462. });
  56463. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  56464. get: function () {
  56465. return this._blurKernelX;
  56466. },
  56467. set: function (value) {
  56468. if (this._blurKernelX === value) {
  56469. return;
  56470. }
  56471. this._blurKernelX = value;
  56472. this._preparePostProcesses();
  56473. },
  56474. enumerable: true,
  56475. configurable: true
  56476. });
  56477. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  56478. get: function () {
  56479. return this._blurKernelY;
  56480. },
  56481. set: function (value) {
  56482. if (this._blurKernelY === value) {
  56483. return;
  56484. }
  56485. this._blurKernelY = value;
  56486. this._preparePostProcesses();
  56487. },
  56488. enumerable: true,
  56489. configurable: true
  56490. });
  56491. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  56492. var engine = this.getScene().getEngine();
  56493. var dw = this.getRenderWidth() / engine.getRenderWidth();
  56494. var dh = this.getRenderHeight() / engine.getRenderHeight();
  56495. this.blurKernelX = this._adaptiveBlurKernel * dw;
  56496. this.blurKernelY = this._adaptiveBlurKernel * dh;
  56497. };
  56498. MirrorTexture.prototype._onRatioRescale = function () {
  56499. if (this._sizeRatio) {
  56500. this.resize(this._initialSizeParameter);
  56501. if (!this._adaptiveBlurKernel) {
  56502. this._preparePostProcesses();
  56503. }
  56504. }
  56505. if (this._adaptiveBlurKernel) {
  56506. this._autoComputeBlurKernel();
  56507. }
  56508. };
  56509. MirrorTexture.prototype._preparePostProcesses = function () {
  56510. this.clearPostProcesses(true);
  56511. if (this._blurKernelX && this._blurKernelY) {
  56512. var engine = this.getScene().getEngine();
  56513. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56514. 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);
  56515. this._blurX.autoClear = false;
  56516. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  56517. this._blurX.inputTexture = this._texture;
  56518. }
  56519. else {
  56520. this._blurX.alwaysForcePOT = true;
  56521. }
  56522. 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);
  56523. this._blurY.autoClear = false;
  56524. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  56525. this.addPostProcess(this._blurX);
  56526. this.addPostProcess(this._blurY);
  56527. }
  56528. else {
  56529. if (this._blurY) {
  56530. this.removePostProcess(this._blurY);
  56531. this._blurY.dispose();
  56532. this._blurY = null;
  56533. }
  56534. if (this._blurX) {
  56535. this.removePostProcess(this._blurX);
  56536. this._blurX.dispose();
  56537. this._blurX = null;
  56538. }
  56539. }
  56540. };
  56541. MirrorTexture.prototype.clone = function () {
  56542. var scene = this.getScene();
  56543. if (!scene) {
  56544. return this;
  56545. }
  56546. var textureSize = this.getSize();
  56547. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  56548. // Base texture
  56549. newTexture.hasAlpha = this.hasAlpha;
  56550. newTexture.level = this.level;
  56551. // Mirror Texture
  56552. newTexture.mirrorPlane = this.mirrorPlane.clone();
  56553. if (this.renderList) {
  56554. newTexture.renderList = this.renderList.slice(0);
  56555. }
  56556. return newTexture;
  56557. };
  56558. MirrorTexture.prototype.serialize = function () {
  56559. if (!this.name) {
  56560. return null;
  56561. }
  56562. var serializationObject = _super.prototype.serialize.call(this);
  56563. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  56564. return serializationObject;
  56565. };
  56566. return MirrorTexture;
  56567. }(BABYLON.RenderTargetTexture));
  56568. BABYLON.MirrorTexture = MirrorTexture;
  56569. })(BABYLON || (BABYLON = {}));
  56570. //# sourceMappingURL=babylon.mirrorTexture.js.map
  56571. var BABYLON;
  56572. (function (BABYLON) {
  56573. /**
  56574. * Creates a refraction texture used by refraction channel of the standard material.
  56575. * @param name the texture name
  56576. * @param size size of the underlying texture
  56577. * @param scene root scene
  56578. */
  56579. var RefractionTexture = /** @class */ (function (_super) {
  56580. __extends(RefractionTexture, _super);
  56581. function RefractionTexture(name, size, scene, generateMipMaps) {
  56582. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  56583. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  56584. _this.depth = 2.0;
  56585. _this.onBeforeRenderObservable.add(function () {
  56586. scene.clipPlane = _this.refractionPlane;
  56587. });
  56588. _this.onAfterRenderObservable.add(function () {
  56589. delete scene.clipPlane;
  56590. });
  56591. return _this;
  56592. }
  56593. RefractionTexture.prototype.clone = function () {
  56594. var scene = this.getScene();
  56595. if (!scene) {
  56596. return this;
  56597. }
  56598. var textureSize = this.getSize();
  56599. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  56600. // Base texture
  56601. newTexture.hasAlpha = this.hasAlpha;
  56602. newTexture.level = this.level;
  56603. // Refraction Texture
  56604. newTexture.refractionPlane = this.refractionPlane.clone();
  56605. if (this.renderList) {
  56606. newTexture.renderList = this.renderList.slice(0);
  56607. }
  56608. newTexture.depth = this.depth;
  56609. return newTexture;
  56610. };
  56611. RefractionTexture.prototype.serialize = function () {
  56612. if (!this.name) {
  56613. return null;
  56614. }
  56615. var serializationObject = _super.prototype.serialize.call(this);
  56616. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  56617. serializationObject.depth = this.depth;
  56618. return serializationObject;
  56619. };
  56620. return RefractionTexture;
  56621. }(BABYLON.RenderTargetTexture));
  56622. BABYLON.RefractionTexture = RefractionTexture;
  56623. })(BABYLON || (BABYLON = {}));
  56624. //# sourceMappingURL=babylon.refractionTexture.js.map
  56625. var BABYLON;
  56626. (function (BABYLON) {
  56627. var DynamicTexture = /** @class */ (function (_super) {
  56628. __extends(DynamicTexture, _super);
  56629. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  56630. if (scene === void 0) { scene = null; }
  56631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56632. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56633. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  56634. _this.name = name;
  56635. _this._engine = _this.getScene().getEngine();
  56636. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56637. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56638. _this._generateMipMaps = generateMipMaps;
  56639. if (options.getContext) {
  56640. _this._canvas = options;
  56641. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  56642. }
  56643. else {
  56644. _this._canvas = document.createElement("canvas");
  56645. if (options.width) {
  56646. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  56647. }
  56648. else {
  56649. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  56650. }
  56651. }
  56652. var textureSize = _this.getSize();
  56653. _this._canvas.width = textureSize.width;
  56654. _this._canvas.height = textureSize.height;
  56655. _this._context = _this._canvas.getContext("2d");
  56656. return _this;
  56657. }
  56658. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  56659. get: function () {
  56660. return true;
  56661. },
  56662. enumerable: true,
  56663. configurable: true
  56664. });
  56665. DynamicTexture.prototype._recreate = function (textureSize) {
  56666. this._canvas.width = textureSize.width;
  56667. this._canvas.height = textureSize.height;
  56668. this.releaseInternalTexture();
  56669. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  56670. };
  56671. DynamicTexture.prototype.scale = function (ratio) {
  56672. var textureSize = this.getSize();
  56673. textureSize.width *= ratio;
  56674. textureSize.height *= ratio;
  56675. this._recreate(textureSize);
  56676. };
  56677. DynamicTexture.prototype.scaleTo = function (width, height) {
  56678. var textureSize = this.getSize();
  56679. textureSize.width = width;
  56680. textureSize.height = height;
  56681. this._recreate(textureSize);
  56682. };
  56683. DynamicTexture.prototype.getContext = function () {
  56684. return this._context;
  56685. };
  56686. DynamicTexture.prototype.clear = function () {
  56687. var size = this.getSize();
  56688. this._context.fillRect(0, 0, size.width, size.height);
  56689. };
  56690. DynamicTexture.prototype.update = function (invertY) {
  56691. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  56692. };
  56693. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  56694. if (update === void 0) { update = true; }
  56695. var size = this.getSize();
  56696. if (clearColor) {
  56697. this._context.fillStyle = clearColor;
  56698. this._context.fillRect(0, 0, size.width, size.height);
  56699. }
  56700. this._context.font = font;
  56701. if (x === null || x === undefined) {
  56702. var textSize = this._context.measureText(text);
  56703. x = (size.width - textSize.width) / 2;
  56704. }
  56705. if (y === null || y === undefined) {
  56706. var fontSize = parseInt((font.replace(/\D/g, '')));
  56707. ;
  56708. y = (size.height / 2) + (fontSize / 3.65);
  56709. }
  56710. this._context.fillStyle = color;
  56711. this._context.fillText(text, x, y);
  56712. if (update) {
  56713. this.update(invertY);
  56714. }
  56715. };
  56716. DynamicTexture.prototype.clone = function () {
  56717. var scene = this.getScene();
  56718. if (!scene) {
  56719. return this;
  56720. }
  56721. var textureSize = this.getSize();
  56722. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  56723. // Base texture
  56724. newTexture.hasAlpha = this.hasAlpha;
  56725. newTexture.level = this.level;
  56726. // Dynamic Texture
  56727. newTexture.wrapU = this.wrapU;
  56728. newTexture.wrapV = this.wrapV;
  56729. return newTexture;
  56730. };
  56731. DynamicTexture.prototype._rebuild = function () {
  56732. this.update();
  56733. };
  56734. return DynamicTexture;
  56735. }(BABYLON.Texture));
  56736. BABYLON.DynamicTexture = DynamicTexture;
  56737. })(BABYLON || (BABYLON = {}));
  56738. //# sourceMappingURL=babylon.dynamicTexture.js.map
  56739. var BABYLON;
  56740. (function (BABYLON) {
  56741. var VideoTexture = /** @class */ (function (_super) {
  56742. __extends(VideoTexture, _super);
  56743. /**
  56744. * Creates a video texture.
  56745. * Sample : https://doc.babylonjs.com/how_to/video_texture
  56746. * @param {string | null} name optional name, will detect from video source, if not defined
  56747. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  56748. * @param {BABYLON.Scene} scene is obviously the current scene.
  56749. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  56750. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  56751. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  56752. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  56753. */
  56754. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  56755. if (generateMipMaps === void 0) { generateMipMaps = false; }
  56756. if (invertY === void 0) { invertY = false; }
  56757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56758. if (settings === void 0) { settings = {
  56759. autoPlay: true,
  56760. loop: true,
  56761. autoUpdateTexture: true,
  56762. }; }
  56763. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  56764. _this._createInternalTexture = function () {
  56765. if (_this._texture != null) {
  56766. return;
  56767. }
  56768. if (!_this._engine.needPOTTextures ||
  56769. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  56770. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56771. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56772. }
  56773. else {
  56774. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56775. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56776. _this._generateMipMaps = false;
  56777. }
  56778. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  56779. _this._texture.isReady = true;
  56780. _this._updateInternalTexture();
  56781. };
  56782. _this.reset = function () {
  56783. if (_this._texture == null) {
  56784. return;
  56785. }
  56786. _this._texture.dispose();
  56787. _this._texture = null;
  56788. };
  56789. _this._updateInternalTexture = function (e) {
  56790. if (_this._texture == null || !_this._texture.isReady) {
  56791. return;
  56792. }
  56793. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  56794. return;
  56795. }
  56796. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  56797. };
  56798. _this._engine = _this.getScene().getEngine();
  56799. _this._generateMipMaps = generateMipMaps;
  56800. _this._samplingMode = samplingMode;
  56801. _this.autoUpdateTexture = settings.autoUpdateTexture;
  56802. _this.name = name || _this._getName(src);
  56803. _this.video = _this._getVideo(src);
  56804. if (settings.autoPlay !== undefined) {
  56805. _this.video.autoplay = settings.autoPlay;
  56806. }
  56807. if (settings.loop !== undefined) {
  56808. _this.video.loop = settings.loop;
  56809. }
  56810. _this.video.addEventListener("canplay", _this._createInternalTexture);
  56811. _this.video.addEventListener("paused", _this._updateInternalTexture);
  56812. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  56813. _this.video.addEventListener("emptied", _this.reset);
  56814. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  56815. _this._createInternalTexture();
  56816. }
  56817. return _this;
  56818. }
  56819. VideoTexture.prototype._getName = function (src) {
  56820. if (src instanceof HTMLVideoElement) {
  56821. return src.currentSrc;
  56822. }
  56823. if (typeof src === "object") {
  56824. return src.toString();
  56825. }
  56826. return src;
  56827. };
  56828. ;
  56829. VideoTexture.prototype._getVideo = function (src) {
  56830. if (src instanceof HTMLVideoElement) {
  56831. return src;
  56832. }
  56833. var video = document.createElement("video");
  56834. if (typeof src === "string") {
  56835. video.src = src;
  56836. }
  56837. else {
  56838. src.forEach(function (url) {
  56839. var source = document.createElement("source");
  56840. source.src = url;
  56841. video.appendChild(source);
  56842. });
  56843. }
  56844. return video;
  56845. };
  56846. ;
  56847. /**
  56848. * Internal method to initiate `update`.
  56849. */
  56850. VideoTexture.prototype._rebuild = function () {
  56851. this.update();
  56852. };
  56853. /**
  56854. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  56855. */
  56856. VideoTexture.prototype.update = function () {
  56857. if (!this.autoUpdateTexture) {
  56858. // Expecting user to call `updateTexture` manually
  56859. return;
  56860. }
  56861. this.updateTexture(true);
  56862. };
  56863. /**
  56864. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  56865. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  56866. */
  56867. VideoTexture.prototype.updateTexture = function (isVisible) {
  56868. if (!isVisible) {
  56869. return;
  56870. }
  56871. if (this.video.paused) {
  56872. return;
  56873. }
  56874. this._updateInternalTexture();
  56875. };
  56876. /**
  56877. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  56878. * @param url New url.
  56879. */
  56880. VideoTexture.prototype.updateURL = function (url) {
  56881. this.video.src = url;
  56882. };
  56883. VideoTexture.prototype.dispose = function () {
  56884. _super.prototype.dispose.call(this);
  56885. this.video.removeEventListener("canplay", this._createInternalTexture);
  56886. this.video.removeEventListener("paused", this._updateInternalTexture);
  56887. this.video.removeEventListener("seeked", this._updateInternalTexture);
  56888. this.video.removeEventListener("emptied", this.reset);
  56889. };
  56890. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  56891. var video = document.createElement("video");
  56892. var constraintsDeviceId;
  56893. if (constraints && constraints.deviceId) {
  56894. constraintsDeviceId = {
  56895. exact: constraints.deviceId,
  56896. };
  56897. }
  56898. navigator.getUserMedia =
  56899. navigator.getUserMedia ||
  56900. navigator.webkitGetUserMedia ||
  56901. navigator.mozGetUserMedia ||
  56902. navigator.msGetUserMedia;
  56903. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  56904. if (navigator.getUserMedia) {
  56905. navigator.getUserMedia({
  56906. video: {
  56907. deviceId: constraintsDeviceId,
  56908. width: {
  56909. min: (constraints && constraints.minWidth) || 256,
  56910. max: (constraints && constraints.maxWidth) || 640,
  56911. },
  56912. height: {
  56913. min: (constraints && constraints.minHeight) || 256,
  56914. max: (constraints && constraints.maxHeight) || 480,
  56915. },
  56916. },
  56917. }, function (stream) {
  56918. if (video.mozSrcObject !== undefined) {
  56919. // hack for Firefox < 19
  56920. video.mozSrcObject = stream;
  56921. }
  56922. else {
  56923. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  56924. }
  56925. video.play();
  56926. if (onReady) {
  56927. onReady(new VideoTexture("video", video, scene, true, true));
  56928. }
  56929. }, function (e) {
  56930. BABYLON.Tools.Error(e.name);
  56931. });
  56932. }
  56933. };
  56934. return VideoTexture;
  56935. }(BABYLON.Texture));
  56936. BABYLON.VideoTexture = VideoTexture;
  56937. })(BABYLON || (BABYLON = {}));
  56938. //# sourceMappingURL=babylon.videoTexture.js.map
  56939. var BABYLON;
  56940. (function (BABYLON) {
  56941. var RawTexture = /** @class */ (function (_super) {
  56942. __extends(RawTexture, _super);
  56943. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  56944. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56945. if (invertY === void 0) { invertY = false; }
  56946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56947. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56948. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  56949. _this.format = format;
  56950. _this._engine = scene.getEngine();
  56951. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  56952. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56953. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56954. return _this;
  56955. }
  56956. RawTexture.prototype.update = function (data) {
  56957. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  56958. };
  56959. // Statics
  56960. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  56961. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56962. if (invertY === void 0) { invertY = false; }
  56963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56964. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  56965. };
  56966. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  56967. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56968. if (invertY === void 0) { invertY = false; }
  56969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56970. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  56971. };
  56972. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  56973. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56974. if (invertY === void 0) { invertY = false; }
  56975. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56976. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  56977. };
  56978. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  56979. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56980. if (invertY === void 0) { invertY = false; }
  56981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56982. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56983. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  56984. };
  56985. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  56986. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56987. if (invertY === void 0) { invertY = false; }
  56988. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56989. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56990. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  56991. };
  56992. return RawTexture;
  56993. }(BABYLON.Texture));
  56994. BABYLON.RawTexture = RawTexture;
  56995. })(BABYLON || (BABYLON = {}));
  56996. //# sourceMappingURL=babylon.rawTexture.js.map
  56997. var BABYLON;
  56998. (function (BABYLON) {
  56999. /**
  57000. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57001. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57002. */
  57003. var PostProcess = /** @class */ (function () {
  57004. /**
  57005. * Creates a new instance of @see PostProcess
  57006. * @param name The name of the PostProcess.
  57007. * @param fragmentUrl The url of the fragment shader to be used.
  57008. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57009. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57010. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57011. * @param camera The camera to apply the render pass to.
  57012. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57013. * @param engine The engine which the post process will be applied. (default: current engine)
  57014. * @param reusable If the post process can be reused on the same frame. (default: false)
  57015. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57016. * @param textureType Type of textures used when performing the post process. (default: 0)
  57017. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57018. * @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
  57019. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57020. */
  57021. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57023. if (defines === void 0) { defines = null; }
  57024. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57025. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57026. if (blockCompilation === void 0) { blockCompilation = false; }
  57027. this.name = name;
  57028. /**
  57029. * Width of the texture to apply the post process on
  57030. */
  57031. this.width = -1;
  57032. /**
  57033. * Height of the texture to apply the post process on
  57034. */
  57035. this.height = -1;
  57036. /**
  57037. * If the buffer needs to be cleared before applying the post process. (default: true)
  57038. * Should be set to false if shader will overwrite all previous pixels.
  57039. */
  57040. this.autoClear = true;
  57041. /**
  57042. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57043. */
  57044. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57045. /**
  57046. * Animations to be used for the post processing
  57047. */
  57048. this.animations = new Array();
  57049. /**
  57050. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57051. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57052. */
  57053. this.enablePixelPerfectMode = false;
  57054. /**
  57055. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57056. */
  57057. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57058. /**
  57059. * Force textures to be a power of two (default: false)
  57060. */
  57061. this.alwaysForcePOT = false;
  57062. /**
  57063. * Number of sample textures (default: 1)
  57064. */
  57065. this.samples = 1;
  57066. /**
  57067. * Modify the scale of the post process to be the same as the viewport (default: false)
  57068. */
  57069. this.adaptScaleToCurrentViewport = false;
  57070. this._reusable = false;
  57071. /**
  57072. * Smart array of input and output textures for the post process.
  57073. */
  57074. this._textures = new BABYLON.SmartArray(2);
  57075. /**
  57076. * The index in _textures that corresponds to the output texture.
  57077. */
  57078. this._currentRenderTextureInd = 0;
  57079. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57080. this._texelSize = BABYLON.Vector2.Zero();
  57081. // Events
  57082. /**
  57083. * An event triggered when the postprocess is activated.
  57084. * @type {BABYLON.Observable}
  57085. */
  57086. this.onActivateObservable = new BABYLON.Observable();
  57087. /**
  57088. * An event triggered when the postprocess changes its size.
  57089. * @type {BABYLON.Observable}
  57090. */
  57091. this.onSizeChangedObservable = new BABYLON.Observable();
  57092. /**
  57093. * An event triggered when the postprocess applies its effect.
  57094. * @type {BABYLON.Observable}
  57095. */
  57096. this.onApplyObservable = new BABYLON.Observable();
  57097. /**
  57098. * An event triggered before rendering the postprocess
  57099. * @type {BABYLON.Observable}
  57100. */
  57101. this.onBeforeRenderObservable = new BABYLON.Observable();
  57102. /**
  57103. * An event triggered after rendering the postprocess
  57104. * @type {BABYLON.Observable}
  57105. */
  57106. this.onAfterRenderObservable = new BABYLON.Observable();
  57107. if (camera != null) {
  57108. this._camera = camera;
  57109. this._scene = camera.getScene();
  57110. camera.attachPostProcess(this);
  57111. this._engine = this._scene.getEngine();
  57112. this._scene.postProcesses.push(this);
  57113. }
  57114. else if (engine) {
  57115. this._engine = engine;
  57116. this._engine.postProcesses.push(this);
  57117. }
  57118. this._options = options;
  57119. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57120. this._reusable = reusable || false;
  57121. this._textureType = textureType;
  57122. this._samplers = samplers || [];
  57123. this._samplers.push("textureSampler");
  57124. this._fragmentUrl = fragmentUrl;
  57125. this._vertexUrl = vertexUrl;
  57126. this._parameters = parameters || [];
  57127. this._parameters.push("scale");
  57128. this._indexParameters = indexParameters;
  57129. if (!blockCompilation) {
  57130. this.updateEffect(defines);
  57131. }
  57132. }
  57133. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57134. /**
  57135. * A function that is added to the onActivateObservable
  57136. */
  57137. set: function (callback) {
  57138. if (this._onActivateObserver) {
  57139. this.onActivateObservable.remove(this._onActivateObserver);
  57140. }
  57141. if (callback) {
  57142. this._onActivateObserver = this.onActivateObservable.add(callback);
  57143. }
  57144. },
  57145. enumerable: true,
  57146. configurable: true
  57147. });
  57148. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57149. /**
  57150. * A function that is added to the onSizeChangedObservable
  57151. */
  57152. set: function (callback) {
  57153. if (this._onSizeChangedObserver) {
  57154. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57155. }
  57156. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57157. },
  57158. enumerable: true,
  57159. configurable: true
  57160. });
  57161. Object.defineProperty(PostProcess.prototype, "onApply", {
  57162. /**
  57163. * A function that is added to the onApplyObservable
  57164. */
  57165. set: function (callback) {
  57166. if (this._onApplyObserver) {
  57167. this.onApplyObservable.remove(this._onApplyObserver);
  57168. }
  57169. this._onApplyObserver = this.onApplyObservable.add(callback);
  57170. },
  57171. enumerable: true,
  57172. configurable: true
  57173. });
  57174. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57175. /**
  57176. * A function that is added to the onBeforeRenderObservable
  57177. */
  57178. set: function (callback) {
  57179. if (this._onBeforeRenderObserver) {
  57180. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57181. }
  57182. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57183. },
  57184. enumerable: true,
  57185. configurable: true
  57186. });
  57187. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57188. /**
  57189. * A function that is added to the onAfterRenderObservable
  57190. */
  57191. set: function (callback) {
  57192. if (this._onAfterRenderObserver) {
  57193. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57194. }
  57195. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57196. },
  57197. enumerable: true,
  57198. configurable: true
  57199. });
  57200. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57201. /**
  57202. * 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
  57203. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57204. */
  57205. get: function () {
  57206. return this._textures.data[this._currentRenderTextureInd];
  57207. },
  57208. set: function (value) {
  57209. this._forcedOutputTexture = value;
  57210. },
  57211. enumerable: true,
  57212. configurable: true
  57213. });
  57214. /**
  57215. * Gets the camera which post process is applied to.
  57216. * @returns The camera the post process is applied to.
  57217. */
  57218. PostProcess.prototype.getCamera = function () {
  57219. return this._camera;
  57220. };
  57221. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57222. /**
  57223. * Gets the texel size of the postprocess.
  57224. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57225. */
  57226. get: function () {
  57227. if (this._shareOutputWithPostProcess) {
  57228. return this._shareOutputWithPostProcess.texelSize;
  57229. }
  57230. if (this._forcedOutputTexture) {
  57231. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57232. }
  57233. return this._texelSize;
  57234. },
  57235. enumerable: true,
  57236. configurable: true
  57237. });
  57238. /**
  57239. * Gets the engine which this post process belongs to.
  57240. * @returns The engine the post process was enabled with.
  57241. */
  57242. PostProcess.prototype.getEngine = function () {
  57243. return this._engine;
  57244. };
  57245. /**
  57246. * The effect that is created when initializing the post process.
  57247. * @returns The created effect corrisponding the the postprocess.
  57248. */
  57249. PostProcess.prototype.getEffect = function () {
  57250. return this._effect;
  57251. };
  57252. /**
  57253. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57254. * @param postProcess The post process to share the output with.
  57255. * @returns This post process.
  57256. */
  57257. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57258. this._disposeTextures();
  57259. this._shareOutputWithPostProcess = postProcess;
  57260. return this;
  57261. };
  57262. /**
  57263. * Updates the effect with the current post process compile time values and recompiles the shader.
  57264. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57265. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57266. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57267. * @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
  57268. * @param onCompiled Called when the shader has been compiled.
  57269. * @param onError Called if there is an error when compiling a shader.
  57270. */
  57271. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57272. if (defines === void 0) { defines = null; }
  57273. if (uniforms === void 0) { uniforms = null; }
  57274. if (samplers === void 0) { samplers = null; }
  57275. 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);
  57276. };
  57277. /**
  57278. * The post process is reusable if it can be used multiple times within one frame.
  57279. * @returns If the post process is reusable
  57280. */
  57281. PostProcess.prototype.isReusable = function () {
  57282. return this._reusable;
  57283. };
  57284. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57285. PostProcess.prototype.markTextureDirty = function () {
  57286. this.width = -1;
  57287. };
  57288. /**
  57289. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57290. * 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.
  57291. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57292. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57293. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57294. */
  57295. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57296. var _this = this;
  57297. if (sourceTexture === void 0) { sourceTexture = null; }
  57298. camera = camera || this._camera;
  57299. var scene = camera.getScene();
  57300. var engine = scene.getEngine();
  57301. var maxSize = engine.getCaps().maxTextureSize;
  57302. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57303. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57304. var desiredWidth = (this._options.width || requiredWidth);
  57305. var desiredHeight = this._options.height || requiredHeight;
  57306. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57307. if (this.adaptScaleToCurrentViewport) {
  57308. var currentViewport = engine.currentViewport;
  57309. if (currentViewport) {
  57310. desiredWidth *= currentViewport.width;
  57311. desiredHeight *= currentViewport.height;
  57312. }
  57313. }
  57314. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57315. if (!this._options.width) {
  57316. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57317. }
  57318. if (!this._options.height) {
  57319. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57320. }
  57321. }
  57322. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57323. if (this._textures.length > 0) {
  57324. for (var i = 0; i < this._textures.length; i++) {
  57325. this._engine._releaseTexture(this._textures.data[i]);
  57326. }
  57327. this._textures.reset();
  57328. }
  57329. this.width = desiredWidth;
  57330. this.height = desiredHeight;
  57331. var textureSize = { width: this.width, height: this.height };
  57332. var textureOptions = {
  57333. generateMipMaps: false,
  57334. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57335. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57336. samplingMode: this.renderTargetSamplingMode,
  57337. type: this._textureType
  57338. };
  57339. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57340. if (this._reusable) {
  57341. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57342. }
  57343. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57344. this.onSizeChangedObservable.notifyObservers(this);
  57345. }
  57346. this._textures.forEach(function (texture) {
  57347. if (texture.samples !== _this.samples) {
  57348. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57349. }
  57350. });
  57351. }
  57352. var target;
  57353. if (this._shareOutputWithPostProcess) {
  57354. target = this._shareOutputWithPostProcess.inputTexture;
  57355. }
  57356. else if (this._forcedOutputTexture) {
  57357. target = this._forcedOutputTexture;
  57358. this.width = this._forcedOutputTexture.width;
  57359. this.height = this._forcedOutputTexture.height;
  57360. }
  57361. else {
  57362. target = this.inputTexture;
  57363. }
  57364. // Bind the input of this post process to be used as the output of the previous post process.
  57365. if (this.enablePixelPerfectMode) {
  57366. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57367. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57368. }
  57369. else {
  57370. this._scaleRatio.copyFromFloats(1, 1);
  57371. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57372. }
  57373. this.onActivateObservable.notifyObservers(camera);
  57374. // Clear
  57375. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57376. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57377. }
  57378. if (this._reusable) {
  57379. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57380. }
  57381. };
  57382. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57383. /**
  57384. * If the post process is supported.
  57385. */
  57386. get: function () {
  57387. return this._effect.isSupported;
  57388. },
  57389. enumerable: true,
  57390. configurable: true
  57391. });
  57392. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57393. /**
  57394. * The aspect ratio of the output texture.
  57395. */
  57396. get: function () {
  57397. if (this._shareOutputWithPostProcess) {
  57398. return this._shareOutputWithPostProcess.aspectRatio;
  57399. }
  57400. if (this._forcedOutputTexture) {
  57401. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57402. }
  57403. return this.width / this.height;
  57404. },
  57405. enumerable: true,
  57406. configurable: true
  57407. });
  57408. /**
  57409. * Get a value indicating if the post-process is ready to be used
  57410. * @returns true if the post-process is ready (shader is compiled)
  57411. */
  57412. PostProcess.prototype.isReady = function () {
  57413. return this._effect && this._effect.isReady();
  57414. };
  57415. /**
  57416. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57417. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57418. */
  57419. PostProcess.prototype.apply = function () {
  57420. // Check
  57421. if (!this._effect || !this._effect.isReady())
  57422. return null;
  57423. // States
  57424. this._engine.enableEffect(this._effect);
  57425. this._engine.setState(false);
  57426. this._engine.setDepthBuffer(false);
  57427. this._engine.setDepthWrite(false);
  57428. // Alpha
  57429. this._engine.setAlphaMode(this.alphaMode);
  57430. if (this.alphaConstants) {
  57431. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57432. }
  57433. // Bind the output texture of the preivous post process as the input to this post process.
  57434. var source;
  57435. if (this._shareOutputWithPostProcess) {
  57436. source = this._shareOutputWithPostProcess.inputTexture;
  57437. }
  57438. else if (this._forcedOutputTexture) {
  57439. source = this._forcedOutputTexture;
  57440. }
  57441. else {
  57442. source = this.inputTexture;
  57443. }
  57444. this._effect._bindTexture("textureSampler", source);
  57445. // Parameters
  57446. this._effect.setVector2("scale", this._scaleRatio);
  57447. this.onApplyObservable.notifyObservers(this._effect);
  57448. return this._effect;
  57449. };
  57450. PostProcess.prototype._disposeTextures = function () {
  57451. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57452. return;
  57453. }
  57454. if (this._textures.length > 0) {
  57455. for (var i = 0; i < this._textures.length; i++) {
  57456. this._engine._releaseTexture(this._textures.data[i]);
  57457. }
  57458. }
  57459. this._textures.dispose();
  57460. };
  57461. /**
  57462. * Disposes the post process.
  57463. * @param camera The camera to dispose the post process on.
  57464. */
  57465. PostProcess.prototype.dispose = function (camera) {
  57466. camera = camera || this._camera;
  57467. this._disposeTextures();
  57468. if (this._scene) {
  57469. var index_1 = this._scene.postProcesses.indexOf(this);
  57470. if (index_1 !== -1) {
  57471. this._scene.postProcesses.splice(index_1, 1);
  57472. }
  57473. }
  57474. else {
  57475. var index_2 = this._engine.postProcesses.indexOf(this);
  57476. if (index_2 !== -1) {
  57477. this._engine.postProcesses.splice(index_2, 1);
  57478. }
  57479. }
  57480. if (!camera) {
  57481. return;
  57482. }
  57483. camera.detachPostProcess(this);
  57484. var index = camera._postProcesses.indexOf(this);
  57485. if (index === 0 && camera._postProcesses.length > 0) {
  57486. this._camera._postProcesses[0].markTextureDirty();
  57487. }
  57488. this.onActivateObservable.clear();
  57489. this.onAfterRenderObservable.clear();
  57490. this.onApplyObservable.clear();
  57491. this.onBeforeRenderObservable.clear();
  57492. this.onSizeChangedObservable.clear();
  57493. };
  57494. return PostProcess;
  57495. }());
  57496. BABYLON.PostProcess = PostProcess;
  57497. })(BABYLON || (BABYLON = {}));
  57498. //# sourceMappingURL=babylon.postProcess.js.map
  57499. var BABYLON;
  57500. (function (BABYLON) {
  57501. var PassPostProcess = /** @class */ (function (_super) {
  57502. __extends(PassPostProcess, _super);
  57503. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57504. if (camera === void 0) { camera = null; }
  57505. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57506. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  57507. }
  57508. return PassPostProcess;
  57509. }(BABYLON.PostProcess));
  57510. BABYLON.PassPostProcess = PassPostProcess;
  57511. })(BABYLON || (BABYLON = {}));
  57512. //# sourceMappingURL=babylon.passPostProcess.js.map
  57513. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57514. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57515. s = arguments[i];
  57516. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57517. t[p] = s[p];
  57518. }
  57519. return t;
  57520. };
  57521. var BABYLON;
  57522. (function (BABYLON) {
  57523. /**
  57524. * Default implementation of @see IShadowGenerator.
  57525. * This is the main object responsible of generating shadows in the framework.
  57526. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  57527. */
  57528. var ShadowGenerator = /** @class */ (function () {
  57529. /**
  57530. * Creates a ShadowGenerator object.
  57531. * A ShadowGenerator is the required tool to use the shadows.
  57532. * Each light casting shadows needs to use its own ShadowGenerator.
  57533. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  57534. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  57535. * @param light The light object generating the shadows.
  57536. * @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.
  57537. */
  57538. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  57539. this._bias = 0.00005;
  57540. this._blurBoxOffset = 1;
  57541. this._blurScale = 2;
  57542. this._blurKernel = 1;
  57543. this._useKernelBlur = false;
  57544. this._filter = ShadowGenerator.FILTER_NONE;
  57545. this._darkness = 0;
  57546. this._transparencyShadow = false;
  57547. /**
  57548. * Controls the extent to which the shadows fade out at the edge of the frustum
  57549. * Used only by directionals and spots
  57550. */
  57551. this.frustumEdgeFalloff = 0;
  57552. /**
  57553. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  57554. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  57555. * It might on the other hand introduce peter panning.
  57556. */
  57557. this.forceBackFacesOnly = false;
  57558. this._lightDirection = BABYLON.Vector3.Zero();
  57559. this._viewMatrix = BABYLON.Matrix.Zero();
  57560. this._projectionMatrix = BABYLON.Matrix.Zero();
  57561. this._transformMatrix = BABYLON.Matrix.Zero();
  57562. this._currentFaceIndex = 0;
  57563. this._currentFaceIndexCache = 0;
  57564. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  57565. this._mapSize = mapSize;
  57566. this._light = light;
  57567. this._scene = light.getScene();
  57568. light._shadowGenerator = this;
  57569. // Texture type fallback from float to int if not supported.
  57570. var caps = this._scene.getEngine().getCaps();
  57571. if (!useFullFloatFirst) {
  57572. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57573. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57574. }
  57575. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57576. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57577. }
  57578. else {
  57579. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57580. }
  57581. }
  57582. else {
  57583. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57584. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57585. }
  57586. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57587. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57588. }
  57589. else {
  57590. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57591. }
  57592. }
  57593. this._initializeGenerator();
  57594. }
  57595. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  57596. /**
  57597. * Shadow generator mode None: no filtering applied.
  57598. */
  57599. get: function () {
  57600. return ShadowGenerator._FILTER_NONE;
  57601. },
  57602. enumerable: true,
  57603. configurable: true
  57604. });
  57605. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  57606. /**
  57607. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  57608. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  57609. */
  57610. get: function () {
  57611. return ShadowGenerator._FILTER_POISSONSAMPLING;
  57612. },
  57613. enumerable: true,
  57614. configurable: true
  57615. });
  57616. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  57617. /**
  57618. * Shadow generator mode ESM: Exponential Shadow Mapping.
  57619. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57620. */
  57621. get: function () {
  57622. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  57623. },
  57624. enumerable: true,
  57625. configurable: true
  57626. });
  57627. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  57628. /**
  57629. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  57630. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57631. */
  57632. get: function () {
  57633. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  57634. },
  57635. enumerable: true,
  57636. configurable: true
  57637. });
  57638. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  57639. /**
  57640. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  57641. * edge artifacts on steep falloff.
  57642. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57643. */
  57644. get: function () {
  57645. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  57646. },
  57647. enumerable: true,
  57648. configurable: true
  57649. });
  57650. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  57651. /**
  57652. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  57653. * edge artifacts on steep falloff.
  57654. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57655. */
  57656. get: function () {
  57657. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  57658. },
  57659. enumerable: true,
  57660. configurable: true
  57661. });
  57662. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  57663. /**
  57664. * Gets the bias: offset applied on the depth preventing acnea.
  57665. */
  57666. get: function () {
  57667. return this._bias;
  57668. },
  57669. /**
  57670. * Sets the bias: offset applied on the depth preventing acnea.
  57671. */
  57672. set: function (bias) {
  57673. this._bias = bias;
  57674. },
  57675. enumerable: true,
  57676. configurable: true
  57677. });
  57678. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  57679. /**
  57680. * Gets the blur box offset: offset applied during the blur pass.
  57681. * Only usefull if useKernelBlur = false
  57682. */
  57683. get: function () {
  57684. return this._blurBoxOffset;
  57685. },
  57686. /**
  57687. * Sets the blur box offset: offset applied during the blur pass.
  57688. * Only usefull if useKernelBlur = false
  57689. */
  57690. set: function (value) {
  57691. if (this._blurBoxOffset === value) {
  57692. return;
  57693. }
  57694. this._blurBoxOffset = value;
  57695. this._disposeBlurPostProcesses();
  57696. },
  57697. enumerable: true,
  57698. configurable: true
  57699. });
  57700. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  57701. /**
  57702. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  57703. * 2 means half of the size.
  57704. */
  57705. get: function () {
  57706. return this._blurScale;
  57707. },
  57708. /**
  57709. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  57710. * 2 means half of the size.
  57711. */
  57712. set: function (value) {
  57713. if (this._blurScale === value) {
  57714. return;
  57715. }
  57716. this._blurScale = value;
  57717. this._disposeBlurPostProcesses();
  57718. },
  57719. enumerable: true,
  57720. configurable: true
  57721. });
  57722. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  57723. /**
  57724. * Gets the blur kernel: kernel size of the blur pass.
  57725. * Only usefull if useKernelBlur = true
  57726. */
  57727. get: function () {
  57728. return this._blurKernel;
  57729. },
  57730. /**
  57731. * Sets the blur kernel: kernel size of the blur pass.
  57732. * Only usefull if useKernelBlur = true
  57733. */
  57734. set: function (value) {
  57735. if (this._blurKernel === value) {
  57736. return;
  57737. }
  57738. this._blurKernel = value;
  57739. this._disposeBlurPostProcesses();
  57740. },
  57741. enumerable: true,
  57742. configurable: true
  57743. });
  57744. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  57745. /**
  57746. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  57747. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  57748. */
  57749. get: function () {
  57750. return this._useKernelBlur;
  57751. },
  57752. /**
  57753. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  57754. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  57755. */
  57756. set: function (value) {
  57757. if (this._useKernelBlur === value) {
  57758. return;
  57759. }
  57760. this._useKernelBlur = value;
  57761. this._disposeBlurPostProcesses();
  57762. },
  57763. enumerable: true,
  57764. configurable: true
  57765. });
  57766. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  57767. /**
  57768. * Gets the depth scale used in ESM mode.
  57769. */
  57770. get: function () {
  57771. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  57772. },
  57773. /**
  57774. * Sets the depth scale used in ESM mode.
  57775. * This can override the scale stored on the light.
  57776. */
  57777. set: function (value) {
  57778. this._depthScale = value;
  57779. },
  57780. enumerable: true,
  57781. configurable: true
  57782. });
  57783. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  57784. /**
  57785. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  57786. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  57787. */
  57788. get: function () {
  57789. return this._filter;
  57790. },
  57791. /**
  57792. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  57793. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  57794. */
  57795. set: function (value) {
  57796. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  57797. if (this._light.needCube()) {
  57798. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  57799. this.useExponentialShadowMap = true;
  57800. return;
  57801. }
  57802. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  57803. this.useCloseExponentialShadowMap = true;
  57804. return;
  57805. }
  57806. }
  57807. if (this._filter === value) {
  57808. return;
  57809. }
  57810. this._filter = value;
  57811. this._disposeBlurPostProcesses();
  57812. this._applyFilterValues();
  57813. this._light._markMeshesAsLightDirty();
  57814. },
  57815. enumerable: true,
  57816. configurable: true
  57817. });
  57818. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  57819. /**
  57820. * Gets if the current filter is set to Poisson Sampling aka PCF.
  57821. */
  57822. get: function () {
  57823. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  57824. },
  57825. /**
  57826. * Sets the current filter to Poisson Sampling aka PCF.
  57827. */
  57828. set: function (value) {
  57829. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  57830. return;
  57831. }
  57832. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  57833. },
  57834. enumerable: true,
  57835. configurable: true
  57836. });
  57837. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  57838. /**
  57839. * Gets if the current filter is set to VSM.
  57840. * DEPRECATED. Should use useExponentialShadowMap instead.
  57841. */
  57842. get: function () {
  57843. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  57844. return this.useExponentialShadowMap;
  57845. },
  57846. /**
  57847. * Sets the current filter is to VSM.
  57848. * DEPRECATED. Should use useExponentialShadowMap instead.
  57849. */
  57850. set: function (value) {
  57851. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  57852. this.useExponentialShadowMap = value;
  57853. },
  57854. enumerable: true,
  57855. configurable: true
  57856. });
  57857. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  57858. /**
  57859. * Gets if the current filter is set to blurred VSM.
  57860. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  57861. */
  57862. get: function () {
  57863. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  57864. return this.useBlurExponentialShadowMap;
  57865. },
  57866. /**
  57867. * Sets the current filter is to blurred VSM.
  57868. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  57869. */
  57870. set: function (value) {
  57871. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  57872. this.useBlurExponentialShadowMap = value;
  57873. },
  57874. enumerable: true,
  57875. configurable: true
  57876. });
  57877. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  57878. /**
  57879. * Gets if the current filter is set to ESM.
  57880. */
  57881. get: function () {
  57882. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  57883. },
  57884. /**
  57885. * Sets the current filter is to ESM.
  57886. */
  57887. set: function (value) {
  57888. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  57889. return;
  57890. }
  57891. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  57892. },
  57893. enumerable: true,
  57894. configurable: true
  57895. });
  57896. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  57897. /**
  57898. * Gets if the current filter is set to filtered ESM.
  57899. */
  57900. get: function () {
  57901. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  57902. },
  57903. /**
  57904. * Gets if the current filter is set to filtered ESM.
  57905. */
  57906. set: function (value) {
  57907. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  57908. return;
  57909. }
  57910. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  57911. },
  57912. enumerable: true,
  57913. configurable: true
  57914. });
  57915. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  57916. /**
  57917. * Gets if the current filter is set to "close ESM" (using the inverse of the
  57918. * exponential to prevent steep falloff artifacts).
  57919. */
  57920. get: function () {
  57921. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  57922. },
  57923. /**
  57924. * Sets the current filter to "close ESM" (using the inverse of the
  57925. * exponential to prevent steep falloff artifacts).
  57926. */
  57927. set: function (value) {
  57928. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  57929. return;
  57930. }
  57931. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  57932. },
  57933. enumerable: true,
  57934. configurable: true
  57935. });
  57936. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  57937. /**
  57938. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  57939. * exponential to prevent steep falloff artifacts).
  57940. */
  57941. get: function () {
  57942. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  57943. },
  57944. /**
  57945. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  57946. * exponential to prevent steep falloff artifacts).
  57947. */
  57948. set: function (value) {
  57949. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  57950. return;
  57951. }
  57952. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  57953. },
  57954. enumerable: true,
  57955. configurable: true
  57956. });
  57957. /**
  57958. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  57959. * 0 means strongest and 1 would means no shadow.
  57960. * @returns the darkness.
  57961. */
  57962. ShadowGenerator.prototype.getDarkness = function () {
  57963. return this._darkness;
  57964. };
  57965. /**
  57966. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  57967. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  57968. * @returns the shadow generator allowing fluent coding.
  57969. */
  57970. ShadowGenerator.prototype.setDarkness = function (darkness) {
  57971. if (darkness >= 1.0)
  57972. this._darkness = 1.0;
  57973. else if (darkness <= 0.0)
  57974. this._darkness = 0.0;
  57975. else
  57976. this._darkness = darkness;
  57977. return this;
  57978. };
  57979. /**
  57980. * Sets the ability to have transparent shadow (boolean).
  57981. * @param transparent True if transparent else False
  57982. * @returns the shadow generator allowing fluent coding
  57983. */
  57984. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  57985. this._transparencyShadow = transparent;
  57986. return this;
  57987. };
  57988. /**
  57989. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  57990. * @returns The render target texture if present otherwise, null
  57991. */
  57992. ShadowGenerator.prototype.getShadowMap = function () {
  57993. return this._shadowMap;
  57994. };
  57995. /**
  57996. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  57997. * @returns The render target texture if the shadow map is present otherwise, null
  57998. */
  57999. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58000. if (this._shadowMap2) {
  58001. return this._shadowMap2;
  58002. }
  58003. return this._shadowMap;
  58004. };
  58005. /**
  58006. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58007. * @param mesh Mesh to add
  58008. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58009. * @returns the Shadow Generator itself
  58010. */
  58011. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58012. if (includeDescendants === void 0) { includeDescendants = true; }
  58013. if (!this._shadowMap) {
  58014. return this;
  58015. }
  58016. if (!this._shadowMap.renderList) {
  58017. this._shadowMap.renderList = [];
  58018. }
  58019. this._shadowMap.renderList.push(mesh);
  58020. if (includeDescendants) {
  58021. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58022. }
  58023. return this;
  58024. var _a;
  58025. };
  58026. /**
  58027. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58028. * @param mesh Mesh to remove
  58029. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58030. * @returns the Shadow Generator itself
  58031. */
  58032. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58033. if (includeDescendants === void 0) { includeDescendants = true; }
  58034. if (!this._shadowMap || !this._shadowMap.renderList) {
  58035. return this;
  58036. }
  58037. var index = this._shadowMap.renderList.indexOf(mesh);
  58038. if (index !== -1) {
  58039. this._shadowMap.renderList.splice(index, 1);
  58040. }
  58041. if (includeDescendants) {
  58042. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58043. var child = _a[_i];
  58044. this.removeShadowCaster(child);
  58045. }
  58046. }
  58047. return this;
  58048. };
  58049. /**
  58050. * Returns the associated light object.
  58051. * @returns the light generating the shadow
  58052. */
  58053. ShadowGenerator.prototype.getLight = function () {
  58054. return this._light;
  58055. };
  58056. ShadowGenerator.prototype._initializeGenerator = function () {
  58057. this._light._markMeshesAsLightDirty();
  58058. this._initializeShadowMap();
  58059. };
  58060. ShadowGenerator.prototype._initializeShadowMap = function () {
  58061. var _this = this;
  58062. // Render target
  58063. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58064. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58065. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58066. this._shadowMap.anisotropicFilteringLevel = 1;
  58067. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58068. this._shadowMap.renderParticles = false;
  58069. this._shadowMap.ignoreCameraViewport = true;
  58070. // Record Face Index before render.
  58071. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58072. _this._currentFaceIndex = faceIndex;
  58073. });
  58074. // Custom render function.
  58075. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58076. // Blur if required afer render.
  58077. this._shadowMap.onAfterUnbindObservable.add(function () {
  58078. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58079. return;
  58080. }
  58081. var shadowMap = _this.getShadowMapForRendering();
  58082. if (shadowMap) {
  58083. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58084. }
  58085. });
  58086. // Clear according to the chosen filter.
  58087. this._shadowMap.onClearObservable.add(function (engine) {
  58088. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58089. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58090. }
  58091. else {
  58092. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58093. }
  58094. });
  58095. };
  58096. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58097. var _this = this;
  58098. var engine = this._scene.getEngine();
  58099. var targetSize = this._mapSize / this.blurScale;
  58100. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58101. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58102. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58103. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58104. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58105. }
  58106. if (this.useKernelBlur) {
  58107. 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);
  58108. this._kernelBlurXPostprocess.width = targetSize;
  58109. this._kernelBlurXPostprocess.height = targetSize;
  58110. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58111. effect.setTexture("textureSampler", _this._shadowMap);
  58112. });
  58113. 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);
  58114. this._kernelBlurXPostprocess.autoClear = false;
  58115. this._kernelBlurYPostprocess.autoClear = false;
  58116. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58117. this._kernelBlurXPostprocess.packedFloat = true;
  58118. this._kernelBlurYPostprocess.packedFloat = true;
  58119. }
  58120. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58121. }
  58122. else {
  58123. 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);
  58124. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58125. effect.setFloat2("screenSize", targetSize, targetSize);
  58126. effect.setTexture("textureSampler", _this._shadowMap);
  58127. });
  58128. this._boxBlurPostprocess.autoClear = false;
  58129. this._blurPostProcesses = [this._boxBlurPostprocess];
  58130. }
  58131. };
  58132. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58133. var index;
  58134. var engine = this._scene.getEngine();
  58135. if (depthOnlySubMeshes.length) {
  58136. engine.setColorWrite(false);
  58137. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58138. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58139. }
  58140. engine.setColorWrite(true);
  58141. }
  58142. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58143. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58144. }
  58145. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58146. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58147. }
  58148. if (this._transparencyShadow) {
  58149. for (index = 0; index < transparentSubMeshes.length; index++) {
  58150. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58151. }
  58152. }
  58153. };
  58154. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58155. var _this = this;
  58156. var mesh = subMesh.getRenderingMesh();
  58157. var scene = this._scene;
  58158. var engine = scene.getEngine();
  58159. var material = subMesh.getMaterial();
  58160. if (!material) {
  58161. return;
  58162. }
  58163. // Culling
  58164. engine.setState(material.backFaceCulling);
  58165. // Managing instances
  58166. var batch = mesh._getInstancesRenderList(subMesh._id);
  58167. if (batch.mustReturn) {
  58168. return;
  58169. }
  58170. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58171. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58172. engine.enableEffect(this._effect);
  58173. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58174. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58175. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58176. this._effect.setVector3("lightPosition", this.getLight().position);
  58177. if (scene.activeCamera) {
  58178. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58179. }
  58180. // Alpha test
  58181. if (material && material.needAlphaTesting()) {
  58182. var alphaTexture = material.getAlphaTestTexture();
  58183. if (alphaTexture) {
  58184. this._effect.setTexture("diffuseSampler", alphaTexture);
  58185. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58186. }
  58187. }
  58188. // Bones
  58189. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58190. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58191. }
  58192. if (this.forceBackFacesOnly) {
  58193. engine.setState(true, 0, false, true);
  58194. }
  58195. // Draw
  58196. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58197. if (this.forceBackFacesOnly) {
  58198. engine.setState(true, 0, false, false);
  58199. }
  58200. }
  58201. else {
  58202. // Need to reset refresh rate of the shadowMap
  58203. if (this._shadowMap) {
  58204. this._shadowMap.resetRefreshCounter();
  58205. }
  58206. }
  58207. };
  58208. ShadowGenerator.prototype._applyFilterValues = function () {
  58209. if (!this._shadowMap) {
  58210. return;
  58211. }
  58212. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58213. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58214. }
  58215. else {
  58216. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58217. }
  58218. };
  58219. /**
  58220. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58221. * @param onCompiled Callback triggered at the and of the effects compilation
  58222. * @param options Sets of optional options forcing the compilation with different modes
  58223. */
  58224. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58225. var _this = this;
  58226. var localOptions = __assign({ useInstances: false }, options);
  58227. var shadowMap = this.getShadowMap();
  58228. if (!shadowMap) {
  58229. if (onCompiled) {
  58230. onCompiled(this);
  58231. }
  58232. return;
  58233. }
  58234. var renderList = shadowMap.renderList;
  58235. if (!renderList) {
  58236. if (onCompiled) {
  58237. onCompiled(this);
  58238. }
  58239. return;
  58240. }
  58241. var subMeshes = new Array();
  58242. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58243. var mesh = renderList_1[_i];
  58244. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58245. }
  58246. if (subMeshes.length === 0) {
  58247. if (onCompiled) {
  58248. onCompiled(this);
  58249. }
  58250. return;
  58251. }
  58252. var currentIndex = 0;
  58253. var checkReady = function () {
  58254. if (!_this._scene || !_this._scene.getEngine()) {
  58255. return;
  58256. }
  58257. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58258. currentIndex++;
  58259. if (currentIndex >= subMeshes.length) {
  58260. if (onCompiled) {
  58261. onCompiled(_this);
  58262. }
  58263. return;
  58264. }
  58265. }
  58266. setTimeout(checkReady, 16);
  58267. };
  58268. checkReady();
  58269. };
  58270. /**
  58271. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58272. * @param subMesh The submesh we want to render in the shadow map
  58273. * @param useInstances Defines wether will draw in the map using instances
  58274. * @returns true if ready otherwise, false
  58275. */
  58276. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58277. var defines = [];
  58278. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58279. defines.push("#define FLOAT");
  58280. }
  58281. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58282. defines.push("#define ESM");
  58283. }
  58284. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58285. var mesh = subMesh.getMesh();
  58286. var material = subMesh.getMaterial();
  58287. // Alpha test
  58288. if (material && material.needAlphaTesting()) {
  58289. var alphaTexture = material.getAlphaTestTexture();
  58290. if (alphaTexture) {
  58291. defines.push("#define ALPHATEST");
  58292. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58293. attribs.push(BABYLON.VertexBuffer.UVKind);
  58294. defines.push("#define UV1");
  58295. }
  58296. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58297. if (alphaTexture.coordinatesIndex === 1) {
  58298. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58299. defines.push("#define UV2");
  58300. }
  58301. }
  58302. }
  58303. }
  58304. // Bones
  58305. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58306. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58307. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58308. if (mesh.numBoneInfluencers > 4) {
  58309. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58310. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58311. }
  58312. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58313. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58314. }
  58315. else {
  58316. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58317. }
  58318. // Instances
  58319. if (useInstances) {
  58320. defines.push("#define INSTANCES");
  58321. attribs.push("world0");
  58322. attribs.push("world1");
  58323. attribs.push("world2");
  58324. attribs.push("world3");
  58325. }
  58326. // Get correct effect
  58327. var join = defines.join("\n");
  58328. if (this._cachedDefines !== join) {
  58329. this._cachedDefines = join;
  58330. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58331. }
  58332. if (!this._effect.isReady()) {
  58333. return false;
  58334. }
  58335. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58336. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58337. this._initializeBlurRTTAndPostProcesses();
  58338. }
  58339. }
  58340. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58341. return false;
  58342. }
  58343. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58344. return false;
  58345. }
  58346. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58347. return false;
  58348. }
  58349. return true;
  58350. };
  58351. /**
  58352. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58353. * @param defines Defines of the material we want to update
  58354. * @param lightIndex Index of the light in the enabled light list of the material
  58355. */
  58356. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58357. var scene = this._scene;
  58358. var light = this._light;
  58359. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58360. return;
  58361. }
  58362. defines["SHADOW" + lightIndex] = true;
  58363. if (this.usePoissonSampling) {
  58364. defines["SHADOWPCF" + lightIndex] = true;
  58365. }
  58366. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58367. defines["SHADOWESM" + lightIndex] = true;
  58368. }
  58369. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58370. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58371. }
  58372. if (light.needCube()) {
  58373. defines["SHADOWCUBE" + lightIndex] = true;
  58374. }
  58375. };
  58376. /**
  58377. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58378. * defined in the generator but impacting the effect).
  58379. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58380. * @param effect The effect we are binfing the information for
  58381. */
  58382. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58383. var light = this._light;
  58384. var scene = this._scene;
  58385. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58386. return;
  58387. }
  58388. var camera = scene.activeCamera;
  58389. if (!camera) {
  58390. return;
  58391. }
  58392. var shadowMap = this.getShadowMap();
  58393. if (!shadowMap) {
  58394. return;
  58395. }
  58396. if (!light.needCube()) {
  58397. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58398. }
  58399. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58400. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58401. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58402. };
  58403. /**
  58404. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58405. * (eq to shadow prjection matrix * light transform matrix)
  58406. * @returns The transform matrix used to create the shadow map
  58407. */
  58408. ShadowGenerator.prototype.getTransformMatrix = function () {
  58409. var scene = this._scene;
  58410. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58411. return this._transformMatrix;
  58412. }
  58413. this._currentRenderID = scene.getRenderId();
  58414. this._currentFaceIndexCache = this._currentFaceIndex;
  58415. var lightPosition = this._light.position;
  58416. if (this._light.computeTransformedInformation()) {
  58417. lightPosition = this._light.transformedPosition;
  58418. }
  58419. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58420. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58421. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58422. }
  58423. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58424. this._cachedPosition = lightPosition.clone();
  58425. this._cachedDirection = this._lightDirection.clone();
  58426. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58427. var shadowMap = this.getShadowMap();
  58428. if (shadowMap) {
  58429. var renderList = shadowMap.renderList;
  58430. if (renderList) {
  58431. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58432. }
  58433. }
  58434. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58435. }
  58436. return this._transformMatrix;
  58437. };
  58438. /**
  58439. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58440. * Cube and 2D textures for instance.
  58441. */
  58442. ShadowGenerator.prototype.recreateShadowMap = function () {
  58443. var shadowMap = this._shadowMap;
  58444. if (!shadowMap) {
  58445. return;
  58446. }
  58447. // Track render list.
  58448. var renderList = shadowMap.renderList;
  58449. // Clean up existing data.
  58450. this._disposeRTTandPostProcesses();
  58451. // Reinitializes.
  58452. this._initializeGenerator();
  58453. // Reaffect the filter to ensure a correct fallback if necessary.
  58454. this.filter = this.filter;
  58455. // Reaffect the filter.
  58456. this._applyFilterValues();
  58457. // Reaffect Render List.
  58458. this._shadowMap.renderList = renderList;
  58459. };
  58460. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  58461. if (this._shadowMap2) {
  58462. this._shadowMap2.dispose();
  58463. this._shadowMap2 = null;
  58464. }
  58465. if (this._boxBlurPostprocess) {
  58466. this._boxBlurPostprocess.dispose();
  58467. this._boxBlurPostprocess = null;
  58468. }
  58469. if (this._kernelBlurXPostprocess) {
  58470. this._kernelBlurXPostprocess.dispose();
  58471. this._kernelBlurXPostprocess = null;
  58472. }
  58473. if (this._kernelBlurYPostprocess) {
  58474. this._kernelBlurYPostprocess.dispose();
  58475. this._kernelBlurYPostprocess = null;
  58476. }
  58477. this._blurPostProcesses = [];
  58478. };
  58479. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  58480. if (this._shadowMap) {
  58481. this._shadowMap.dispose();
  58482. this._shadowMap = null;
  58483. }
  58484. this._disposeBlurPostProcesses();
  58485. };
  58486. /**
  58487. * Disposes the ShadowGenerator.
  58488. * Returns nothing.
  58489. */
  58490. ShadowGenerator.prototype.dispose = function () {
  58491. this._disposeRTTandPostProcesses();
  58492. if (this._light) {
  58493. this._light._shadowGenerator = null;
  58494. this._light._markMeshesAsLightDirty();
  58495. }
  58496. };
  58497. /**
  58498. * Serializes the shadow generator setup to a json object.
  58499. * @returns The serialized JSON object
  58500. */
  58501. ShadowGenerator.prototype.serialize = function () {
  58502. var serializationObject = {};
  58503. var shadowMap = this.getShadowMap();
  58504. if (!shadowMap) {
  58505. return serializationObject;
  58506. }
  58507. serializationObject.lightId = this._light.id;
  58508. serializationObject.mapSize = shadowMap.getRenderSize();
  58509. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  58510. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  58511. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58512. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58513. serializationObject.usePoissonSampling = this.usePoissonSampling;
  58514. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  58515. serializationObject.depthScale = this.depthScale;
  58516. serializationObject.darkness = this.getDarkness();
  58517. serializationObject.blurBoxOffset = this.blurBoxOffset;
  58518. serializationObject.blurKernel = this.blurKernel;
  58519. serializationObject.blurScale = this.blurScale;
  58520. serializationObject.useKernelBlur = this.useKernelBlur;
  58521. serializationObject.transparencyShadow = this._transparencyShadow;
  58522. serializationObject.renderList = [];
  58523. if (shadowMap.renderList) {
  58524. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  58525. var mesh = shadowMap.renderList[meshIndex];
  58526. serializationObject.renderList.push(mesh.id);
  58527. }
  58528. }
  58529. return serializationObject;
  58530. };
  58531. /**
  58532. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  58533. * @param parsedShadowGenerator The JSON object to parse
  58534. * @param scene The scene to create the shadow map for
  58535. * @returns The parsed shadow generator
  58536. */
  58537. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  58538. //casting to point light, as light is missing the position attr and typescript complains.
  58539. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  58540. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  58541. var shadowMap = shadowGenerator.getShadowMap();
  58542. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  58543. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  58544. meshes.forEach(function (mesh) {
  58545. if (!shadowMap) {
  58546. return;
  58547. }
  58548. if (!shadowMap.renderList) {
  58549. shadowMap.renderList = [];
  58550. }
  58551. shadowMap.renderList.push(mesh);
  58552. });
  58553. }
  58554. if (parsedShadowGenerator.usePoissonSampling) {
  58555. shadowGenerator.usePoissonSampling = true;
  58556. }
  58557. else if (parsedShadowGenerator.useExponentialShadowMap) {
  58558. shadowGenerator.useExponentialShadowMap = true;
  58559. }
  58560. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  58561. shadowGenerator.useBlurExponentialShadowMap = true;
  58562. }
  58563. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  58564. shadowGenerator.useCloseExponentialShadowMap = true;
  58565. }
  58566. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  58567. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  58568. }
  58569. else if (parsedShadowGenerator.useVarianceShadowMap) {
  58570. shadowGenerator.useExponentialShadowMap = true;
  58571. }
  58572. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  58573. shadowGenerator.useBlurExponentialShadowMap = true;
  58574. }
  58575. if (parsedShadowGenerator.depthScale) {
  58576. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  58577. }
  58578. if (parsedShadowGenerator.blurScale) {
  58579. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  58580. }
  58581. if (parsedShadowGenerator.blurBoxOffset) {
  58582. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  58583. }
  58584. if (parsedShadowGenerator.useKernelBlur) {
  58585. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  58586. }
  58587. if (parsedShadowGenerator.blurKernel) {
  58588. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  58589. }
  58590. if (parsedShadowGenerator.bias !== undefined) {
  58591. shadowGenerator.bias = parsedShadowGenerator.bias;
  58592. }
  58593. if (parsedShadowGenerator.darkness) {
  58594. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  58595. }
  58596. if (parsedShadowGenerator.transparencyShadow) {
  58597. shadowGenerator.setTransparencyShadow(true);
  58598. }
  58599. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  58600. return shadowGenerator;
  58601. };
  58602. ShadowGenerator._FILTER_NONE = 0;
  58603. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  58604. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  58605. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  58606. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  58607. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  58608. return ShadowGenerator;
  58609. }());
  58610. BABYLON.ShadowGenerator = ShadowGenerator;
  58611. })(BABYLON || (BABYLON = {}));
  58612. //# sourceMappingURL=babylon.shadowGenerator.js.map
  58613. var BABYLON;
  58614. (function (BABYLON) {
  58615. var DefaultLoadingScreen = /** @class */ (function () {
  58616. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  58617. if (_loadingText === void 0) { _loadingText = ""; }
  58618. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  58619. var _this = this;
  58620. this._renderingCanvas = _renderingCanvas;
  58621. this._loadingText = _loadingText;
  58622. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  58623. // Resize
  58624. this._resizeLoadingUI = function () {
  58625. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  58626. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  58627. if (!_this._loadingDiv) {
  58628. return;
  58629. }
  58630. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  58631. _this._loadingDiv.style.left = canvasRect.left + "px";
  58632. _this._loadingDiv.style.top = canvasRect.top + "px";
  58633. _this._loadingDiv.style.width = canvasRect.width + "px";
  58634. _this._loadingDiv.style.height = canvasRect.height + "px";
  58635. };
  58636. }
  58637. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  58638. if (this._loadingDiv) {
  58639. // Do not add a loading screen if there is already one
  58640. return;
  58641. }
  58642. this._loadingDiv = document.createElement("div");
  58643. this._loadingDiv.id = "babylonjsLoadingDiv";
  58644. this._loadingDiv.style.opacity = "0";
  58645. this._loadingDiv.style.transition = "opacity 1.5s ease";
  58646. this._loadingDiv.style.pointerEvents = "none";
  58647. // Loading text
  58648. this._loadingTextDiv = document.createElement("div");
  58649. this._loadingTextDiv.style.position = "absolute";
  58650. this._loadingTextDiv.style.left = "0";
  58651. this._loadingTextDiv.style.top = "50%";
  58652. this._loadingTextDiv.style.marginTop = "80px";
  58653. this._loadingTextDiv.style.width = "100%";
  58654. this._loadingTextDiv.style.height = "20px";
  58655. this._loadingTextDiv.style.fontFamily = "Arial";
  58656. this._loadingTextDiv.style.fontSize = "14px";
  58657. this._loadingTextDiv.style.color = "white";
  58658. this._loadingTextDiv.style.textAlign = "center";
  58659. this._loadingTextDiv.innerHTML = "Loading";
  58660. this._loadingDiv.appendChild(this._loadingTextDiv);
  58661. //set the predefined text
  58662. this._loadingTextDiv.innerHTML = this._loadingText;
  58663. // Generating keyframes
  58664. var style = document.createElement('style');
  58665. style.type = 'text/css';
  58666. 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 }";
  58667. style.innerHTML = keyFrames;
  58668. document.getElementsByTagName('head')[0].appendChild(style);
  58669. // Loading img
  58670. var imgBack = new Image();
  58671. 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";
  58672. imgBack.style.position = "absolute";
  58673. imgBack.style.left = "50%";
  58674. imgBack.style.top = "50%";
  58675. imgBack.style.marginLeft = "-60px";
  58676. imgBack.style.marginTop = "-60px";
  58677. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  58678. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  58679. imgBack.style.transformOrigin = "50% 50%";
  58680. imgBack.style.webkitTransformOrigin = "50% 50%";
  58681. this._loadingDiv.appendChild(imgBack);
  58682. this._resizeLoadingUI();
  58683. window.addEventListener("resize", this._resizeLoadingUI);
  58684. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  58685. document.body.appendChild(this._loadingDiv);
  58686. this._loadingDiv.style.opacity = "1";
  58687. };
  58688. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  58689. var _this = this;
  58690. if (!this._loadingDiv) {
  58691. return;
  58692. }
  58693. var onTransitionEnd = function () {
  58694. if (!_this._loadingDiv) {
  58695. return;
  58696. }
  58697. document.body.removeChild(_this._loadingDiv);
  58698. window.removeEventListener("resize", _this._resizeLoadingUI);
  58699. _this._loadingDiv = null;
  58700. };
  58701. this._loadingDiv.style.opacity = "0";
  58702. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  58703. };
  58704. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  58705. set: function (text) {
  58706. this._loadingText = text;
  58707. if (this._loadingTextDiv) {
  58708. this._loadingTextDiv.innerHTML = this._loadingText;
  58709. }
  58710. },
  58711. enumerable: true,
  58712. configurable: true
  58713. });
  58714. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  58715. get: function () {
  58716. return this._loadingDivBackgroundColor;
  58717. },
  58718. set: function (color) {
  58719. this._loadingDivBackgroundColor = color;
  58720. if (!this._loadingDiv) {
  58721. return;
  58722. }
  58723. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  58724. },
  58725. enumerable: true,
  58726. configurable: true
  58727. });
  58728. return DefaultLoadingScreen;
  58729. }());
  58730. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  58731. })(BABYLON || (BABYLON = {}));
  58732. //# sourceMappingURL=babylon.loadingScreen.js.map
  58733. var BABYLON;
  58734. (function (BABYLON) {
  58735. var SceneLoaderProgressEvent = /** @class */ (function () {
  58736. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  58737. this.lengthComputable = lengthComputable;
  58738. this.loaded = loaded;
  58739. this.total = total;
  58740. }
  58741. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  58742. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  58743. };
  58744. return SceneLoaderProgressEvent;
  58745. }());
  58746. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  58747. var SceneLoader = /** @class */ (function () {
  58748. function SceneLoader() {
  58749. }
  58750. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  58751. get: function () {
  58752. return 0;
  58753. },
  58754. enumerable: true,
  58755. configurable: true
  58756. });
  58757. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  58758. get: function () {
  58759. return 1;
  58760. },
  58761. enumerable: true,
  58762. configurable: true
  58763. });
  58764. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  58765. get: function () {
  58766. return 2;
  58767. },
  58768. enumerable: true,
  58769. configurable: true
  58770. });
  58771. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  58772. get: function () {
  58773. return 3;
  58774. },
  58775. enumerable: true,
  58776. configurable: true
  58777. });
  58778. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  58779. get: function () {
  58780. return SceneLoader._ForceFullSceneLoadingForIncremental;
  58781. },
  58782. set: function (value) {
  58783. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  58784. },
  58785. enumerable: true,
  58786. configurable: true
  58787. });
  58788. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  58789. get: function () {
  58790. return SceneLoader._ShowLoadingScreen;
  58791. },
  58792. set: function (value) {
  58793. SceneLoader._ShowLoadingScreen = value;
  58794. },
  58795. enumerable: true,
  58796. configurable: true
  58797. });
  58798. Object.defineProperty(SceneLoader, "loggingLevel", {
  58799. get: function () {
  58800. return SceneLoader._loggingLevel;
  58801. },
  58802. set: function (value) {
  58803. SceneLoader._loggingLevel = value;
  58804. },
  58805. enumerable: true,
  58806. configurable: true
  58807. });
  58808. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  58809. get: function () {
  58810. return SceneLoader._CleanBoneMatrixWeights;
  58811. },
  58812. set: function (value) {
  58813. SceneLoader._CleanBoneMatrixWeights = value;
  58814. },
  58815. enumerable: true,
  58816. configurable: true
  58817. });
  58818. SceneLoader._getDefaultPlugin = function () {
  58819. return SceneLoader._registeredPlugins[".babylon"];
  58820. };
  58821. SceneLoader._getPluginForExtension = function (extension) {
  58822. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  58823. if (registeredPlugin) {
  58824. return registeredPlugin;
  58825. }
  58826. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  58827. return SceneLoader._getDefaultPlugin();
  58828. };
  58829. SceneLoader._getPluginForDirectLoad = function (data) {
  58830. for (var extension in SceneLoader._registeredPlugins) {
  58831. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  58832. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  58833. return SceneLoader._registeredPlugins[extension];
  58834. }
  58835. }
  58836. return SceneLoader._getDefaultPlugin();
  58837. };
  58838. SceneLoader._getPluginForFilename = function (sceneFilename) {
  58839. if (sceneFilename.name) {
  58840. sceneFilename = sceneFilename.name;
  58841. }
  58842. var queryStringPosition = sceneFilename.indexOf("?");
  58843. if (queryStringPosition !== -1) {
  58844. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  58845. }
  58846. var dotPosition = sceneFilename.lastIndexOf(".");
  58847. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  58848. return SceneLoader._getPluginForExtension(extension);
  58849. };
  58850. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  58851. SceneLoader._getDirectLoad = function (sceneFilename) {
  58852. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  58853. return sceneFilename.substr(5);
  58854. }
  58855. return null;
  58856. };
  58857. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  58858. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  58859. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  58860. var plugin;
  58861. if (registeredPlugin.plugin.createPlugin) {
  58862. plugin = registeredPlugin.plugin.createPlugin();
  58863. }
  58864. else {
  58865. plugin = registeredPlugin.plugin;
  58866. }
  58867. var useArrayBuffer = registeredPlugin.isBinary;
  58868. var database;
  58869. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  58870. var dataCallback = function (data, responseURL) {
  58871. if (scene.isDisposed) {
  58872. onError("Scene has been disposed");
  58873. return;
  58874. }
  58875. scene.database = database;
  58876. onSuccess(plugin, data, responseURL);
  58877. };
  58878. var request = null;
  58879. var pluginDisposed = false;
  58880. var onDisposeObservable = plugin.onDisposeObservable;
  58881. if (onDisposeObservable) {
  58882. onDisposeObservable.add(function () {
  58883. pluginDisposed = true;
  58884. if (request) {
  58885. request.abort();
  58886. request = null;
  58887. }
  58888. onDispose();
  58889. });
  58890. }
  58891. var manifestChecked = function () {
  58892. if (pluginDisposed) {
  58893. return;
  58894. }
  58895. var url = rootUrl + sceneFilename;
  58896. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  58897. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  58898. } : undefined, database, useArrayBuffer, function (request, exception) {
  58899. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  58900. });
  58901. };
  58902. if (directLoad) {
  58903. dataCallback(directLoad);
  58904. return plugin;
  58905. }
  58906. if (rootUrl.indexOf("file:") === -1) {
  58907. if (scene.getEngine().enableOfflineSupport) {
  58908. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  58909. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  58910. }
  58911. else {
  58912. manifestChecked();
  58913. }
  58914. }
  58915. else {
  58916. var fileOrString = sceneFilename;
  58917. if (fileOrString.name) {
  58918. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  58919. }
  58920. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  58921. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  58922. }
  58923. else {
  58924. onError("Unable to find file named " + sceneFilename);
  58925. }
  58926. }
  58927. return plugin;
  58928. };
  58929. // Public functions
  58930. SceneLoader.GetPluginForExtension = function (extension) {
  58931. return SceneLoader._getPluginForExtension(extension).plugin;
  58932. };
  58933. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  58934. return !!SceneLoader._registeredPlugins[extension];
  58935. };
  58936. SceneLoader.RegisterPlugin = function (plugin) {
  58937. if (typeof plugin.extensions === "string") {
  58938. var extension = plugin.extensions;
  58939. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  58940. plugin: plugin,
  58941. isBinary: false
  58942. };
  58943. }
  58944. else {
  58945. var extensions = plugin.extensions;
  58946. Object.keys(extensions).forEach(function (extension) {
  58947. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  58948. plugin: plugin,
  58949. isBinary: extensions[extension].isBinary
  58950. };
  58951. });
  58952. }
  58953. };
  58954. /**
  58955. * Import meshes into a scene
  58956. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  58957. * @param rootUrl a string that defines the root url for scene and resources
  58958. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  58959. * @param scene the instance of BABYLON.Scene to append to
  58960. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  58961. * @param onProgress a callback with a progress event for each file being loaded
  58962. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  58963. */
  58964. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  58965. if (onSuccess === void 0) { onSuccess = null; }
  58966. if (onProgress === void 0) { onProgress = null; }
  58967. if (onError === void 0) { onError = null; }
  58968. if (pluginExtension === void 0) { pluginExtension = null; }
  58969. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  58970. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  58971. return null;
  58972. }
  58973. var loadingToken = {};
  58974. scene._addPendingData(loadingToken);
  58975. var disposeHandler = function () {
  58976. scene._removePendingData(loadingToken);
  58977. };
  58978. var errorHandler = function (message, exception) {
  58979. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  58980. if (onError) {
  58981. onError(scene, errorMessage, exception);
  58982. }
  58983. else {
  58984. BABYLON.Tools.Error(errorMessage);
  58985. // should the exception be thrown?
  58986. }
  58987. disposeHandler();
  58988. };
  58989. var progressHandler = onProgress ? function (event) {
  58990. try {
  58991. onProgress(event);
  58992. }
  58993. catch (e) {
  58994. errorHandler("Error in onProgress callback", e);
  58995. }
  58996. } : undefined;
  58997. var successHandler = function (meshes, particleSystems, skeletons) {
  58998. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  58999. if (onSuccess) {
  59000. try {
  59001. onSuccess(meshes, particleSystems, skeletons);
  59002. }
  59003. catch (e) {
  59004. errorHandler("Error in onSuccess callback", e);
  59005. }
  59006. }
  59007. scene._removePendingData(loadingToken);
  59008. };
  59009. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59010. if (plugin.rewriteRootURL) {
  59011. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59012. }
  59013. if (sceneFilename === "") {
  59014. if (sceneFilename === "") {
  59015. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59016. }
  59017. }
  59018. if (plugin.importMesh) {
  59019. var syncedPlugin = plugin;
  59020. var meshes = new Array();
  59021. var particleSystems = new Array();
  59022. var skeletons = new Array();
  59023. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59024. return;
  59025. }
  59026. scene.loadingPluginName = plugin.name;
  59027. successHandler(meshes, particleSystems, skeletons);
  59028. }
  59029. else {
  59030. var asyncedPlugin = plugin;
  59031. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  59032. scene.loadingPluginName = plugin.name;
  59033. successHandler(meshes, particleSystems, skeletons);
  59034. }, progressHandler, errorHandler);
  59035. }
  59036. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59037. };
  59038. /**
  59039. * Load a scene
  59040. * @param rootUrl a string that defines the root url for scene and resources
  59041. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59042. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59043. * @param onSuccess a callback with the scene when import succeeds
  59044. * @param onProgress a callback with a progress event for each file being loaded
  59045. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59046. */
  59047. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59048. if (onSuccess === void 0) { onSuccess = null; }
  59049. if (onProgress === void 0) { onProgress = null; }
  59050. if (onError === void 0) { onError = null; }
  59051. if (pluginExtension === void 0) { pluginExtension = null; }
  59052. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59053. };
  59054. /**
  59055. * Append a scene
  59056. * @param rootUrl a string that defines the root url for scene and resources
  59057. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59058. * @param scene is the instance of BABYLON.Scene to append to
  59059. * @param onSuccess a callback with the scene when import succeeds
  59060. * @param onProgress a callback with a progress event for each file being loaded
  59061. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59062. */
  59063. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59064. if (onSuccess === void 0) { onSuccess = null; }
  59065. if (onProgress === void 0) { onProgress = null; }
  59066. if (onError === void 0) { onError = null; }
  59067. if (pluginExtension === void 0) { pluginExtension = null; }
  59068. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59069. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59070. return null;
  59071. }
  59072. if (SceneLoader.ShowLoadingScreen) {
  59073. scene.getEngine().displayLoadingUI();
  59074. }
  59075. var loadingToken = {};
  59076. scene._addPendingData(loadingToken);
  59077. var disposeHandler = function () {
  59078. scene._removePendingData(loadingToken);
  59079. scene.getEngine().hideLoadingUI();
  59080. };
  59081. var errorHandler = function (message, exception) {
  59082. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59083. if (onError) {
  59084. onError(scene, errorMessage, exception);
  59085. }
  59086. else {
  59087. BABYLON.Tools.Error(errorMessage);
  59088. // should the exception be thrown?
  59089. }
  59090. disposeHandler();
  59091. };
  59092. var progressHandler = onProgress ? function (event) {
  59093. try {
  59094. onProgress(event);
  59095. }
  59096. catch (e) {
  59097. errorHandler("Error in onProgress callback", e);
  59098. }
  59099. } : undefined;
  59100. var successHandler = function () {
  59101. if (onSuccess) {
  59102. try {
  59103. onSuccess(scene);
  59104. }
  59105. catch (e) {
  59106. errorHandler("Error in onSuccess callback", e);
  59107. }
  59108. }
  59109. scene._removePendingData(loadingToken);
  59110. };
  59111. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59112. if (sceneFilename === "") {
  59113. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59114. }
  59115. if (plugin.load) {
  59116. var syncedPlugin = plugin;
  59117. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59118. return;
  59119. }
  59120. scene.loadingPluginName = plugin.name;
  59121. successHandler();
  59122. }
  59123. else {
  59124. var asyncedPlugin = plugin;
  59125. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  59126. scene.loadingPluginName = plugin.name;
  59127. successHandler();
  59128. }, progressHandler, errorHandler);
  59129. }
  59130. if (SceneLoader.ShowLoadingScreen) {
  59131. scene.executeWhenReady(function () {
  59132. scene.getEngine().hideLoadingUI();
  59133. });
  59134. }
  59135. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59136. };
  59137. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59138. if (onSuccess === void 0) { onSuccess = null; }
  59139. if (onProgress === void 0) { onProgress = null; }
  59140. if (onError === void 0) { onError = null; }
  59141. if (pluginExtension === void 0) { pluginExtension = null; }
  59142. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59143. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59144. return null;
  59145. }
  59146. var loadingToken = {};
  59147. scene._addPendingData(loadingToken);
  59148. var disposeHandler = function () {
  59149. scene._removePendingData(loadingToken);
  59150. };
  59151. var errorHandler = function (message, exception) {
  59152. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59153. if (onError) {
  59154. onError(scene, errorMessage, exception);
  59155. }
  59156. else {
  59157. BABYLON.Tools.Error(errorMessage);
  59158. // should the exception be thrown?
  59159. }
  59160. disposeHandler();
  59161. };
  59162. var progressHandler = onProgress ? function (event) {
  59163. try {
  59164. onProgress(event);
  59165. }
  59166. catch (e) {
  59167. errorHandler("Error in onProgress callback", e);
  59168. }
  59169. } : undefined;
  59170. var successHandler = function (assets) {
  59171. if (onSuccess) {
  59172. try {
  59173. onSuccess(assets);
  59174. }
  59175. catch (e) {
  59176. errorHandler("Error in onSuccess callback", e);
  59177. }
  59178. }
  59179. scene._removePendingData(loadingToken);
  59180. };
  59181. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59182. if (plugin.loadAssets) {
  59183. var syncedPlugin = plugin;
  59184. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  59185. if (!assetContainer) {
  59186. return;
  59187. }
  59188. scene.loadingPluginName = plugin.name;
  59189. successHandler(assetContainer);
  59190. }
  59191. else if (plugin.loadAssetsAsync) {
  59192. var asyncedPlugin = plugin;
  59193. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  59194. if (assetContainer) {
  59195. scene.loadingPluginName = plugin.name;
  59196. successHandler(assetContainer);
  59197. }
  59198. }, progressHandler, errorHandler);
  59199. }
  59200. else {
  59201. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  59202. }
  59203. if (SceneLoader.ShowLoadingScreen) {
  59204. scene.executeWhenReady(function () {
  59205. scene.getEngine().hideLoadingUI();
  59206. });
  59207. }
  59208. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59209. };
  59210. // Flags
  59211. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59212. SceneLoader._ShowLoadingScreen = true;
  59213. SceneLoader._CleanBoneMatrixWeights = false;
  59214. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59215. // Members
  59216. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59217. SceneLoader._registeredPlugins = {};
  59218. return SceneLoader;
  59219. }());
  59220. BABYLON.SceneLoader = SceneLoader;
  59221. ;
  59222. })(BABYLON || (BABYLON = {}));
  59223. //# sourceMappingURL=babylon.sceneLoader.js.map
  59224. var BABYLON;
  59225. (function (BABYLON) {
  59226. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59227. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59228. var parsedMaterial = parsedData.materials[index];
  59229. if (parsedMaterial.id === id) {
  59230. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59231. }
  59232. }
  59233. return null;
  59234. };
  59235. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59236. for (var i in names) {
  59237. if (mesh.name === names[i]) {
  59238. hierarchyIds.push(mesh.id);
  59239. return true;
  59240. }
  59241. }
  59242. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59243. hierarchyIds.push(mesh.id);
  59244. return true;
  59245. }
  59246. return false;
  59247. };
  59248. var logOperation = function (operation, producer) {
  59249. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59250. };
  59251. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  59252. if (addToScene === void 0) { addToScene = false; }
  59253. var container = new BABYLON.AssetContainer(scene);
  59254. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59255. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59256. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59257. // and avoid problems with multiple concurrent .babylon loads.
  59258. var log = "importScene has failed JSON parse";
  59259. try {
  59260. var parsedData = JSON.parse(data);
  59261. log = "";
  59262. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59263. var index;
  59264. var cache;
  59265. // Lights
  59266. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59267. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59268. var parsedLight = parsedData.lights[index];
  59269. var light = BABYLON.Light.Parse(parsedLight, scene);
  59270. if (light) {
  59271. container.lights.push(light);
  59272. log += (index === 0 ? "\n\tLights:" : "");
  59273. log += "\n\t\t" + light.toString(fullDetails);
  59274. }
  59275. }
  59276. }
  59277. // Animations
  59278. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59279. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59280. var parsedAnimation = parsedData.animations[index];
  59281. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59282. scene.animations.push(animation);
  59283. container.animations.push(animation);
  59284. log += (index === 0 ? "\n\tAnimations:" : "");
  59285. log += "\n\t\t" + animation.toString(fullDetails);
  59286. }
  59287. }
  59288. // Materials
  59289. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59290. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59291. var parsedMaterial = parsedData.materials[index];
  59292. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59293. container.materials.push(mat);
  59294. log += (index === 0 ? "\n\tMaterials:" : "");
  59295. log += "\n\t\t" + mat.toString(fullDetails);
  59296. }
  59297. }
  59298. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59299. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59300. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59301. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59302. container.multiMaterials.push(mmat);
  59303. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59304. log += "\n\t\t" + mmat.toString(fullDetails);
  59305. }
  59306. }
  59307. // Morph targets
  59308. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59309. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59310. var managerData = _a[_i];
  59311. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59312. }
  59313. }
  59314. // Skeletons
  59315. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59316. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59317. var parsedSkeleton = parsedData.skeletons[index];
  59318. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59319. container.skeletons.push(skeleton);
  59320. log += (index === 0 ? "\n\tSkeletons:" : "");
  59321. log += "\n\t\t" + skeleton.toString(fullDetails);
  59322. }
  59323. }
  59324. // Geometries
  59325. var geometries = parsedData.geometries;
  59326. if (geometries !== undefined && geometries !== null) {
  59327. var addedGeometry = new Array();
  59328. // Boxes
  59329. var boxes = geometries.boxes;
  59330. if (boxes !== undefined && boxes !== null) {
  59331. for (index = 0, cache = boxes.length; index < cache; index++) {
  59332. var parsedBox = boxes[index];
  59333. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59334. }
  59335. }
  59336. // Spheres
  59337. var spheres = geometries.spheres;
  59338. if (spheres !== undefined && spheres !== null) {
  59339. for (index = 0, cache = spheres.length; index < cache; index++) {
  59340. var parsedSphere = spheres[index];
  59341. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  59342. }
  59343. }
  59344. // Cylinders
  59345. var cylinders = geometries.cylinders;
  59346. if (cylinders !== undefined && cylinders !== null) {
  59347. for (index = 0, cache = cylinders.length; index < cache; index++) {
  59348. var parsedCylinder = cylinders[index];
  59349. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  59350. }
  59351. }
  59352. // Toruses
  59353. var toruses = geometries.toruses;
  59354. if (toruses !== undefined && toruses !== null) {
  59355. for (index = 0, cache = toruses.length; index < cache; index++) {
  59356. var parsedTorus = toruses[index];
  59357. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  59358. }
  59359. }
  59360. // Grounds
  59361. var grounds = geometries.grounds;
  59362. if (grounds !== undefined && grounds !== null) {
  59363. for (index = 0, cache = grounds.length; index < cache; index++) {
  59364. var parsedGround = grounds[index];
  59365. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  59366. }
  59367. }
  59368. // Planes
  59369. var planes = geometries.planes;
  59370. if (planes !== undefined && planes !== null) {
  59371. for (index = 0, cache = planes.length; index < cache; index++) {
  59372. var parsedPlane = planes[index];
  59373. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  59374. }
  59375. }
  59376. // TorusKnots
  59377. var torusKnots = geometries.torusKnots;
  59378. if (torusKnots !== undefined && torusKnots !== null) {
  59379. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  59380. var parsedTorusKnot = torusKnots[index];
  59381. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  59382. }
  59383. }
  59384. // VertexData
  59385. var vertexData = geometries.vertexData;
  59386. if (vertexData !== undefined && vertexData !== null) {
  59387. for (index = 0, cache = vertexData.length; index < cache; index++) {
  59388. var parsedVertexData = vertexData[index];
  59389. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  59390. }
  59391. }
  59392. addedGeometry.forEach(function (g) {
  59393. if (g) {
  59394. container.geometries.push(g);
  59395. }
  59396. });
  59397. }
  59398. // Transform nodes
  59399. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  59400. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  59401. var parsedTransformNode = parsedData.transformNodes[index];
  59402. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  59403. container.transformNodes.push(node);
  59404. }
  59405. }
  59406. // Meshes
  59407. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  59408. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  59409. var parsedMesh = parsedData.meshes[index];
  59410. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  59411. container.meshes.push(mesh);
  59412. log += (index === 0 ? "\n\tMeshes:" : "");
  59413. log += "\n\t\t" + mesh.toString(fullDetails);
  59414. }
  59415. }
  59416. // Cameras
  59417. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  59418. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  59419. var parsedCamera = parsedData.cameras[index];
  59420. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  59421. container.cameras.push(camera);
  59422. log += (index === 0 ? "\n\tCameras:" : "");
  59423. log += "\n\t\t" + camera.toString(fullDetails);
  59424. }
  59425. }
  59426. // Browsing all the graph to connect the dots
  59427. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  59428. var camera = scene.cameras[index];
  59429. if (camera._waitingParentId) {
  59430. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  59431. camera._waitingParentId = null;
  59432. }
  59433. }
  59434. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59435. var light_1 = scene.lights[index];
  59436. if (light_1 && light_1._waitingParentId) {
  59437. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  59438. light_1._waitingParentId = null;
  59439. }
  59440. }
  59441. // Sounds
  59442. // TODO: add sound
  59443. var loadedSounds = [];
  59444. var loadedSound;
  59445. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  59446. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  59447. var parsedSound = parsedData.sounds[index];
  59448. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59449. if (!parsedSound.url)
  59450. parsedSound.url = parsedSound.name;
  59451. if (!loadedSounds[parsedSound.url]) {
  59452. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  59453. loadedSounds[parsedSound.url] = loadedSound;
  59454. container.sounds.push(loadedSound);
  59455. }
  59456. else {
  59457. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  59458. }
  59459. }
  59460. else {
  59461. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  59462. }
  59463. }
  59464. }
  59465. loadedSounds = [];
  59466. // Connect parents & children and parse actions
  59467. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  59468. var transformNode = scene.transformNodes[index];
  59469. if (transformNode._waitingParentId) {
  59470. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  59471. transformNode._waitingParentId = null;
  59472. }
  59473. }
  59474. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59475. var mesh = scene.meshes[index];
  59476. if (mesh._waitingParentId) {
  59477. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  59478. mesh._waitingParentId = null;
  59479. }
  59480. if (mesh._waitingActions) {
  59481. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  59482. mesh._waitingActions = null;
  59483. }
  59484. }
  59485. // freeze world matrix application
  59486. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59487. var currentMesh = scene.meshes[index];
  59488. if (currentMesh._waitingFreezeWorldMatrix) {
  59489. currentMesh.freezeWorldMatrix();
  59490. currentMesh._waitingFreezeWorldMatrix = null;
  59491. }
  59492. else {
  59493. currentMesh.computeWorldMatrix(true);
  59494. }
  59495. }
  59496. // Particles Systems
  59497. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59498. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59499. var parsedParticleSystem = parsedData.particleSystems[index];
  59500. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59501. container.particleSystems.push(ps);
  59502. }
  59503. }
  59504. // Lens flares
  59505. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  59506. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  59507. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  59508. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  59509. container.lensFlareSystems.push(lf);
  59510. }
  59511. }
  59512. // Shadows
  59513. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  59514. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  59515. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  59516. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  59517. container.shadowGenerators.push(sg);
  59518. }
  59519. }
  59520. // Lights exclusions / inclusions
  59521. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59522. var light_2 = scene.lights[index];
  59523. // Excluded check
  59524. if (light_2._excludedMeshesIds.length > 0) {
  59525. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  59526. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  59527. if (excludedMesh) {
  59528. light_2.excludedMeshes.push(excludedMesh);
  59529. }
  59530. }
  59531. light_2._excludedMeshesIds = [];
  59532. }
  59533. // Included check
  59534. if (light_2._includedOnlyMeshesIds.length > 0) {
  59535. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  59536. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  59537. if (includedOnlyMesh) {
  59538. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  59539. }
  59540. }
  59541. light_2._includedOnlyMeshesIds = [];
  59542. }
  59543. }
  59544. // Actions (scene)
  59545. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  59546. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  59547. }
  59548. if (!addToScene) {
  59549. container.removeAllFromScene();
  59550. }
  59551. return container;
  59552. }
  59553. catch (err) {
  59554. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  59555. if (onError) {
  59556. onError(msg, err);
  59557. }
  59558. else {
  59559. BABYLON.Tools.Log(msg);
  59560. throw err;
  59561. }
  59562. }
  59563. finally {
  59564. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  59565. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  59566. }
  59567. }
  59568. return null;
  59569. };
  59570. BABYLON.SceneLoader.RegisterPlugin({
  59571. name: "babylon.js",
  59572. extensions: ".babylon",
  59573. canDirectLoad: function (data) {
  59574. if (data.indexOf("babylon") !== -1) {
  59575. return true;
  59576. }
  59577. return false;
  59578. },
  59579. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  59580. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59581. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59582. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59583. // and avoid problems with multiple concurrent .babylon loads.
  59584. var log = "importMesh has failed JSON parse";
  59585. try {
  59586. var parsedData = JSON.parse(data);
  59587. log = "";
  59588. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59589. if (!meshesNames) {
  59590. meshesNames = null;
  59591. }
  59592. else if (!Array.isArray(meshesNames)) {
  59593. meshesNames = [meshesNames];
  59594. }
  59595. var hierarchyIds = new Array();
  59596. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  59597. var loadedSkeletonsIds = [];
  59598. var loadedMaterialsIds = [];
  59599. var index;
  59600. var cache;
  59601. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  59602. var parsedMesh = parsedData.meshes[index];
  59603. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  59604. if (meshesNames !== null) {
  59605. // Remove found mesh name from list.
  59606. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  59607. }
  59608. //Geometry?
  59609. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  59610. //does the file contain geometries?
  59611. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  59612. //find the correct geometry and add it to the scene
  59613. var found = false;
  59614. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  59615. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  59616. return;
  59617. }
  59618. else {
  59619. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  59620. if (parsedGeometryData.id === parsedMesh.geometryId) {
  59621. switch (geometryType) {
  59622. case "boxes":
  59623. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  59624. break;
  59625. case "spheres":
  59626. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  59627. break;
  59628. case "cylinders":
  59629. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  59630. break;
  59631. case "toruses":
  59632. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  59633. break;
  59634. case "grounds":
  59635. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  59636. break;
  59637. case "planes":
  59638. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  59639. break;
  59640. case "torusKnots":
  59641. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  59642. break;
  59643. case "vertexData":
  59644. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  59645. break;
  59646. }
  59647. found = true;
  59648. }
  59649. });
  59650. }
  59651. });
  59652. if (found === false) {
  59653. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  59654. }
  59655. }
  59656. }
  59657. // Material ?
  59658. if (parsedMesh.materialId) {
  59659. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  59660. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59661. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  59662. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  59663. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  59664. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  59665. var subMatId = parsedMultiMaterial.materials[matIndex];
  59666. loadedMaterialsIds.push(subMatId);
  59667. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  59668. if (mat) {
  59669. log += "\n\tMaterial " + mat.toString(fullDetails);
  59670. }
  59671. }
  59672. loadedMaterialsIds.push(parsedMultiMaterial.id);
  59673. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59674. if (mmat) {
  59675. materialFound = true;
  59676. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  59677. }
  59678. break;
  59679. }
  59680. }
  59681. }
  59682. if (materialFound === false) {
  59683. loadedMaterialsIds.push(parsedMesh.materialId);
  59684. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  59685. if (!mat) {
  59686. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  59687. }
  59688. else {
  59689. log += "\n\tMaterial " + mat.toString(fullDetails);
  59690. }
  59691. }
  59692. }
  59693. // Skeleton ?
  59694. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59695. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  59696. if (skeletonAlreadyLoaded === false) {
  59697. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  59698. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  59699. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  59700. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59701. skeletons.push(skeleton);
  59702. loadedSkeletonsIds.push(parsedSkeleton.id);
  59703. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  59704. }
  59705. }
  59706. }
  59707. }
  59708. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  59709. meshes.push(mesh);
  59710. log += "\n\tMesh " + mesh.toString(fullDetails);
  59711. }
  59712. }
  59713. // Connecting parents
  59714. var currentMesh;
  59715. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59716. currentMesh = scene.meshes[index];
  59717. if (currentMesh._waitingParentId) {
  59718. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  59719. currentMesh._waitingParentId = null;
  59720. }
  59721. }
  59722. // freeze and compute world matrix application
  59723. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59724. currentMesh = scene.meshes[index];
  59725. if (currentMesh._waitingFreezeWorldMatrix) {
  59726. currentMesh.freezeWorldMatrix();
  59727. currentMesh._waitingFreezeWorldMatrix = null;
  59728. }
  59729. else {
  59730. currentMesh.computeWorldMatrix(true);
  59731. }
  59732. }
  59733. }
  59734. // Particles
  59735. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59736. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59737. var parsedParticleSystem = parsedData.particleSystems[index];
  59738. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  59739. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  59740. }
  59741. }
  59742. }
  59743. return true;
  59744. }
  59745. catch (err) {
  59746. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  59747. if (onError) {
  59748. onError(msg, err);
  59749. }
  59750. else {
  59751. BABYLON.Tools.Log(msg);
  59752. throw err;
  59753. }
  59754. }
  59755. finally {
  59756. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  59757. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  59758. }
  59759. }
  59760. return false;
  59761. },
  59762. load: function (scene, data, rootUrl, onError) {
  59763. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59764. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59765. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59766. // and avoid problems with multiple concurrent .babylon loads.
  59767. var log = "importScene has failed JSON parse";
  59768. try {
  59769. var parsedData = JSON.parse(data);
  59770. log = "";
  59771. // Scene
  59772. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  59773. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  59774. }
  59775. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  59776. scene.autoClear = parsedData.autoClear;
  59777. }
  59778. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  59779. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  59780. }
  59781. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  59782. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  59783. }
  59784. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  59785. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  59786. }
  59787. // Fog
  59788. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  59789. scene.fogMode = parsedData.fogMode;
  59790. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  59791. scene.fogStart = parsedData.fogStart;
  59792. scene.fogEnd = parsedData.fogEnd;
  59793. scene.fogDensity = parsedData.fogDensity;
  59794. log += "\tFog mode for scene: ";
  59795. switch (scene.fogMode) {
  59796. // getters not compiling, so using hardcoded
  59797. case 1:
  59798. log += "exp\n";
  59799. break;
  59800. case 2:
  59801. log += "exp2\n";
  59802. break;
  59803. case 3:
  59804. log += "linear\n";
  59805. break;
  59806. }
  59807. }
  59808. //Physics
  59809. if (parsedData.physicsEnabled) {
  59810. var physicsPlugin;
  59811. if (parsedData.physicsEngine === "cannon") {
  59812. physicsPlugin = new BABYLON.CannonJSPlugin();
  59813. }
  59814. else if (parsedData.physicsEngine === "oimo") {
  59815. physicsPlugin = new BABYLON.OimoJSPlugin();
  59816. }
  59817. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  59818. //else - default engine, which is currently oimo
  59819. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  59820. scene.enablePhysics(physicsGravity, physicsPlugin);
  59821. }
  59822. // Metadata
  59823. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  59824. scene.metadata = parsedData.metadata;
  59825. }
  59826. //collisions, if defined. otherwise, default is true
  59827. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  59828. scene.collisionsEnabled = parsedData.collisionsEnabled;
  59829. }
  59830. scene.workerCollisions = !!parsedData.workerCollisions;
  59831. var container = loadAssets(scene, data, rootUrl, onerror, true);
  59832. if (!container) {
  59833. return false;
  59834. }
  59835. if (parsedData.autoAnimate) {
  59836. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  59837. }
  59838. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  59839. scene.setActiveCameraByID(parsedData.activeCameraID);
  59840. }
  59841. // Environment texture
  59842. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  59843. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  59844. if (parsedData.createDefaultSkybox === true) {
  59845. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  59846. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  59847. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  59848. }
  59849. }
  59850. // Finish
  59851. return true;
  59852. }
  59853. catch (err) {
  59854. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  59855. if (onError) {
  59856. onError(msg, err);
  59857. }
  59858. else {
  59859. BABYLON.Tools.Log(msg);
  59860. throw err;
  59861. }
  59862. }
  59863. finally {
  59864. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  59865. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  59866. }
  59867. }
  59868. return false;
  59869. },
  59870. loadAssets: function (scene, data, rootUrl, onError) {
  59871. var container = loadAssets(scene, data, rootUrl, onerror);
  59872. return container;
  59873. }
  59874. });
  59875. })(BABYLON || (BABYLON = {}));
  59876. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  59877. var BABYLON;
  59878. (function (BABYLON) {
  59879. var FilesInput = /** @class */ (function () {
  59880. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  59881. this.onProcessFileCallback = function () { return true; };
  59882. this._engine = engine;
  59883. this._currentScene = scene;
  59884. this._sceneLoadedCallback = sceneLoadedCallback;
  59885. this._progressCallback = progressCallback;
  59886. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  59887. this._textureLoadingCallback = textureLoadingCallback;
  59888. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  59889. this._onReloadCallback = onReloadCallback;
  59890. this._errorCallback = errorCallback;
  59891. }
  59892. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  59893. var _this = this;
  59894. if (elementToMonitor) {
  59895. this._elementToMonitor = elementToMonitor;
  59896. this._dragEnterHandler = function (e) { _this.drag(e); };
  59897. this._dragOverHandler = function (e) { _this.drag(e); };
  59898. this._dropHandler = function (e) { _this.drop(e); };
  59899. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  59900. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  59901. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  59902. }
  59903. };
  59904. FilesInput.prototype.dispose = function () {
  59905. if (!this._elementToMonitor) {
  59906. return;
  59907. }
  59908. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  59909. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  59910. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  59911. };
  59912. FilesInput.prototype.renderFunction = function () {
  59913. if (this._additionalRenderLoopLogicCallback) {
  59914. this._additionalRenderLoopLogicCallback();
  59915. }
  59916. if (this._currentScene) {
  59917. if (this._textureLoadingCallback) {
  59918. var remaining = this._currentScene.getWaitingItemsCount();
  59919. if (remaining > 0) {
  59920. this._textureLoadingCallback(remaining);
  59921. }
  59922. }
  59923. this._currentScene.render();
  59924. }
  59925. };
  59926. FilesInput.prototype.drag = function (e) {
  59927. e.stopPropagation();
  59928. e.preventDefault();
  59929. };
  59930. FilesInput.prototype.drop = function (eventDrop) {
  59931. eventDrop.stopPropagation();
  59932. eventDrop.preventDefault();
  59933. this.loadFiles(eventDrop);
  59934. };
  59935. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  59936. var _this = this;
  59937. var reader = folder.createReader();
  59938. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  59939. reader.readEntries(function (entries) {
  59940. remaining.count += entries.length;
  59941. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  59942. var entry = entries_1[_i];
  59943. if (entry.isFile) {
  59944. entry.file(function (file) {
  59945. file.correctName = relativePath + file.name;
  59946. files.push(file);
  59947. if (--remaining.count === 0) {
  59948. callback();
  59949. }
  59950. });
  59951. }
  59952. else if (entry.isDirectory) {
  59953. _this._traverseFolder(entry, files, remaining, callback);
  59954. }
  59955. }
  59956. if (--remaining.count) {
  59957. callback();
  59958. }
  59959. });
  59960. };
  59961. FilesInput.prototype._processFiles = function (files) {
  59962. for (var i = 0; i < files.length; i++) {
  59963. var name = files[i].correctName.toLowerCase();
  59964. var extension = name.split('.').pop();
  59965. if (!this.onProcessFileCallback(files[i], name, extension)) {
  59966. continue;
  59967. }
  59968. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  59969. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  59970. this._sceneFileToLoad = files[i];
  59971. }
  59972. else {
  59973. FilesInput.FilesToLoad[name] = files[i];
  59974. }
  59975. }
  59976. };
  59977. FilesInput.prototype.loadFiles = function (event) {
  59978. var _this = this;
  59979. if (this._startingProcessingFilesCallback)
  59980. this._startingProcessingFilesCallback();
  59981. // Handling data transfer via drag'n'drop
  59982. if (event && event.dataTransfer && event.dataTransfer.files) {
  59983. this._filesToLoad = event.dataTransfer.files;
  59984. }
  59985. // Handling files from input files
  59986. if (event && event.target && event.target.files) {
  59987. this._filesToLoad = event.target.files;
  59988. }
  59989. if (this._filesToLoad && this._filesToLoad.length > 0) {
  59990. var files_1 = new Array();
  59991. var folders = [];
  59992. var items = event.dataTransfer ? event.dataTransfer.items : null;
  59993. for (var i = 0; i < this._filesToLoad.length; i++) {
  59994. var fileToLoad = this._filesToLoad[i];
  59995. var name_1 = fileToLoad.name.toLowerCase();
  59996. var entry = void 0;
  59997. fileToLoad.correctName = name_1;
  59998. if (items) {
  59999. var item = items[i];
  60000. if (item.getAsEntry) {
  60001. entry = item.getAsEntry();
  60002. }
  60003. else if (item.webkitGetAsEntry) {
  60004. entry = item.webkitGetAsEntry();
  60005. }
  60006. }
  60007. if (!entry) {
  60008. files_1.push(fileToLoad);
  60009. }
  60010. else {
  60011. if (entry.isDirectory) {
  60012. folders.push(entry);
  60013. }
  60014. else {
  60015. files_1.push(fileToLoad);
  60016. }
  60017. }
  60018. }
  60019. if (folders.length === 0) {
  60020. this._processFiles(files_1);
  60021. this._processReload();
  60022. }
  60023. else {
  60024. var remaining = { count: folders.length };
  60025. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60026. var folder = folders_1[_i];
  60027. this._traverseFolder(folder, files_1, remaining, function () {
  60028. _this._processFiles(files_1);
  60029. if (remaining.count === 0) {
  60030. _this._processReload();
  60031. }
  60032. });
  60033. }
  60034. }
  60035. }
  60036. };
  60037. FilesInput.prototype._processReload = function () {
  60038. if (this._onReloadCallback) {
  60039. this._onReloadCallback(this._sceneFileToLoad);
  60040. }
  60041. else {
  60042. this.reload();
  60043. }
  60044. };
  60045. FilesInput.prototype.reload = function () {
  60046. var _this = this;
  60047. // If a scene file has been provided
  60048. if (this._sceneFileToLoad) {
  60049. if (this._currentScene) {
  60050. if (BABYLON.Tools.errorsCount > 0) {
  60051. BABYLON.Tools.ClearLogCache();
  60052. }
  60053. this._engine.stopRenderLoop();
  60054. this._currentScene.dispose();
  60055. }
  60056. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  60057. _this._currentScene = newScene;
  60058. if (_this._sceneLoadedCallback) {
  60059. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60060. }
  60061. // Wait for textures and shaders to be ready
  60062. _this._currentScene.executeWhenReady(function () {
  60063. _this._engine.runRenderLoop(function () {
  60064. _this.renderFunction();
  60065. });
  60066. });
  60067. }, function (progress) {
  60068. if (_this._progressCallback) {
  60069. _this._progressCallback(progress);
  60070. }
  60071. }, function (scene, message) {
  60072. _this._currentScene = scene;
  60073. if (_this._errorCallback) {
  60074. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  60075. }
  60076. });
  60077. }
  60078. else {
  60079. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60080. }
  60081. };
  60082. FilesInput.FilesToLoad = {};
  60083. return FilesInput;
  60084. }());
  60085. BABYLON.FilesInput = FilesInput;
  60086. })(BABYLON || (BABYLON = {}));
  60087. //# sourceMappingURL=babylon.filesInput.js.map
  60088. var BABYLON;
  60089. (function (BABYLON) {
  60090. /**
  60091. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60092. * The underlying implementation relies on an associative array to ensure the best performances.
  60093. * The value can be anything including 'null' but except 'undefined'
  60094. */
  60095. var StringDictionary = /** @class */ (function () {
  60096. function StringDictionary() {
  60097. this._count = 0;
  60098. this._data = {};
  60099. }
  60100. /**
  60101. * This will clear this dictionary and copy the content from the 'source' one.
  60102. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60103. * @param source the dictionary to take the content from and copy to this dictionary
  60104. */
  60105. StringDictionary.prototype.copyFrom = function (source) {
  60106. var _this = this;
  60107. this.clear();
  60108. source.forEach(function (t, v) { return _this.add(t, v); });
  60109. };
  60110. /**
  60111. * Get a value based from its key
  60112. * @param key the given key to get the matching value from
  60113. * @return the value if found, otherwise undefined is returned
  60114. */
  60115. StringDictionary.prototype.get = function (key) {
  60116. var val = this._data[key];
  60117. if (val !== undefined) {
  60118. return val;
  60119. }
  60120. return undefined;
  60121. };
  60122. /**
  60123. * Get a value from its key or add it if it doesn't exist.
  60124. * This method will ensure you that a given key/data will be present in the dictionary.
  60125. * @param key the given key to get the matching value from
  60126. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60127. * The factory will only be invoked if there's no data for the given key.
  60128. * @return the value corresponding to the key.
  60129. */
  60130. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60131. var val = this.get(key);
  60132. if (val !== undefined) {
  60133. return val;
  60134. }
  60135. val = factory(key);
  60136. if (val) {
  60137. this.add(key, val);
  60138. }
  60139. return val;
  60140. };
  60141. /**
  60142. * Get a value from its key if present in the dictionary otherwise add it
  60143. * @param key the key to get the value from
  60144. * @param val if there's no such key/value pair in the dictionary add it with this value
  60145. * @return the value corresponding to the key
  60146. */
  60147. StringDictionary.prototype.getOrAdd = function (key, val) {
  60148. var curVal = this.get(key);
  60149. if (curVal !== undefined) {
  60150. return curVal;
  60151. }
  60152. this.add(key, val);
  60153. return val;
  60154. };
  60155. /**
  60156. * Check if there's a given key in the dictionary
  60157. * @param key the key to check for
  60158. * @return true if the key is present, false otherwise
  60159. */
  60160. StringDictionary.prototype.contains = function (key) {
  60161. return this._data[key] !== undefined;
  60162. };
  60163. /**
  60164. * Add a new key and its corresponding value
  60165. * @param key the key to add
  60166. * @param value the value corresponding to the key
  60167. * @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
  60168. */
  60169. StringDictionary.prototype.add = function (key, value) {
  60170. if (this._data[key] !== undefined) {
  60171. return false;
  60172. }
  60173. this._data[key] = value;
  60174. ++this._count;
  60175. return true;
  60176. };
  60177. StringDictionary.prototype.set = function (key, value) {
  60178. if (this._data[key] === undefined) {
  60179. return false;
  60180. }
  60181. this._data[key] = value;
  60182. return true;
  60183. };
  60184. /**
  60185. * Get the element of the given key and remove it from the dictionary
  60186. * @param key
  60187. */
  60188. StringDictionary.prototype.getAndRemove = function (key) {
  60189. var val = this.get(key);
  60190. if (val !== undefined) {
  60191. delete this._data[key];
  60192. --this._count;
  60193. return val;
  60194. }
  60195. return null;
  60196. };
  60197. /**
  60198. * Remove a key/value from the dictionary.
  60199. * @param key the key to remove
  60200. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60201. */
  60202. StringDictionary.prototype.remove = function (key) {
  60203. if (this.contains(key)) {
  60204. delete this._data[key];
  60205. --this._count;
  60206. return true;
  60207. }
  60208. return false;
  60209. };
  60210. /**
  60211. * Clear the whole content of the dictionary
  60212. */
  60213. StringDictionary.prototype.clear = function () {
  60214. this._data = {};
  60215. this._count = 0;
  60216. };
  60217. Object.defineProperty(StringDictionary.prototype, "count", {
  60218. get: function () {
  60219. return this._count;
  60220. },
  60221. enumerable: true,
  60222. configurable: true
  60223. });
  60224. /**
  60225. * Execute a callback on each key/val of the dictionary.
  60226. * Note that you can remove any element in this dictionary in the callback implementation
  60227. * @param callback the callback to execute on a given key/value pair
  60228. */
  60229. StringDictionary.prototype.forEach = function (callback) {
  60230. for (var cur in this._data) {
  60231. var val = this._data[cur];
  60232. callback(cur, val);
  60233. }
  60234. };
  60235. /**
  60236. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60237. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60238. * Note that you can remove any element in this dictionary in the callback implementation
  60239. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60240. */
  60241. StringDictionary.prototype.first = function (callback) {
  60242. for (var cur in this._data) {
  60243. var val = this._data[cur];
  60244. var res = callback(cur, val);
  60245. if (res) {
  60246. return res;
  60247. }
  60248. }
  60249. return null;
  60250. };
  60251. return StringDictionary;
  60252. }());
  60253. BABYLON.StringDictionary = StringDictionary;
  60254. })(BABYLON || (BABYLON = {}));
  60255. //# sourceMappingURL=babylon.stringDictionary.js.map
  60256. var BABYLON;
  60257. (function (BABYLON) {
  60258. var Tags = /** @class */ (function () {
  60259. function Tags() {
  60260. }
  60261. Tags.EnableFor = function (obj) {
  60262. obj._tags = obj._tags || {};
  60263. obj.hasTags = function () {
  60264. return Tags.HasTags(obj);
  60265. };
  60266. obj.addTags = function (tagsString) {
  60267. return Tags.AddTagsTo(obj, tagsString);
  60268. };
  60269. obj.removeTags = function (tagsString) {
  60270. return Tags.RemoveTagsFrom(obj, tagsString);
  60271. };
  60272. obj.matchesTagsQuery = function (tagsQuery) {
  60273. return Tags.MatchesQuery(obj, tagsQuery);
  60274. };
  60275. };
  60276. Tags.DisableFor = function (obj) {
  60277. delete obj._tags;
  60278. delete obj.hasTags;
  60279. delete obj.addTags;
  60280. delete obj.removeTags;
  60281. delete obj.matchesTagsQuery;
  60282. };
  60283. Tags.HasTags = function (obj) {
  60284. if (!obj._tags) {
  60285. return false;
  60286. }
  60287. return !BABYLON.Tools.IsEmpty(obj._tags);
  60288. };
  60289. Tags.GetTags = function (obj, asString) {
  60290. if (asString === void 0) { asString = true; }
  60291. if (!obj._tags) {
  60292. return null;
  60293. }
  60294. if (asString) {
  60295. var tagsArray = [];
  60296. for (var tag in obj._tags) {
  60297. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60298. tagsArray.push(tag);
  60299. }
  60300. }
  60301. return tagsArray.join(" ");
  60302. }
  60303. else {
  60304. return obj._tags;
  60305. }
  60306. };
  60307. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60308. // a tag cannot start with '||', '&&', and '!'
  60309. // it cannot contain whitespaces
  60310. Tags.AddTagsTo = function (obj, tagsString) {
  60311. if (!tagsString) {
  60312. return;
  60313. }
  60314. if (typeof tagsString !== "string") {
  60315. return;
  60316. }
  60317. var tags = tagsString.split(" ");
  60318. tags.forEach(function (tag, index, array) {
  60319. Tags._AddTagTo(obj, tag);
  60320. });
  60321. };
  60322. Tags._AddTagTo = function (obj, tag) {
  60323. tag = tag.trim();
  60324. if (tag === "" || tag === "true" || tag === "false") {
  60325. return;
  60326. }
  60327. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60328. return;
  60329. }
  60330. Tags.EnableFor(obj);
  60331. obj._tags[tag] = true;
  60332. };
  60333. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60334. if (!Tags.HasTags(obj)) {
  60335. return;
  60336. }
  60337. var tags = tagsString.split(" ");
  60338. for (var t in tags) {
  60339. Tags._RemoveTagFrom(obj, tags[t]);
  60340. }
  60341. };
  60342. Tags._RemoveTagFrom = function (obj, tag) {
  60343. delete obj._tags[tag];
  60344. };
  60345. Tags.MatchesQuery = function (obj, tagsQuery) {
  60346. if (tagsQuery === undefined) {
  60347. return true;
  60348. }
  60349. if (tagsQuery === "") {
  60350. return Tags.HasTags(obj);
  60351. }
  60352. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  60353. };
  60354. return Tags;
  60355. }());
  60356. BABYLON.Tags = Tags;
  60357. })(BABYLON || (BABYLON = {}));
  60358. //# sourceMappingURL=babylon.tags.js.map
  60359. var BABYLON;
  60360. (function (BABYLON) {
  60361. var AndOrNotEvaluator = /** @class */ (function () {
  60362. function AndOrNotEvaluator() {
  60363. }
  60364. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  60365. if (!query.match(/\([^\(\)]*\)/g)) {
  60366. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  60367. }
  60368. else {
  60369. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  60370. // remove parenthesis
  60371. r = r.slice(1, r.length - 1);
  60372. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  60373. });
  60374. }
  60375. if (query === "true") {
  60376. return true;
  60377. }
  60378. if (query === "false") {
  60379. return false;
  60380. }
  60381. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  60382. };
  60383. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  60384. evaluateCallback = evaluateCallback || (function (r) {
  60385. return r === "true" ? true : false;
  60386. });
  60387. var result;
  60388. var or = parenthesisContent.split("||");
  60389. for (var i in or) {
  60390. if (or.hasOwnProperty(i)) {
  60391. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  60392. var and = ori.split("&&");
  60393. if (and.length > 1) {
  60394. for (var j = 0; j < and.length; ++j) {
  60395. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  60396. if (andj !== "true" && andj !== "false") {
  60397. if (andj[0] === "!") {
  60398. result = !evaluateCallback(andj.substring(1));
  60399. }
  60400. else {
  60401. result = evaluateCallback(andj);
  60402. }
  60403. }
  60404. else {
  60405. result = andj === "true" ? true : false;
  60406. }
  60407. if (!result) {
  60408. ori = "false";
  60409. break;
  60410. }
  60411. }
  60412. }
  60413. if (result || ori === "true") {
  60414. result = true;
  60415. break;
  60416. }
  60417. // result equals false (or undefined)
  60418. if (ori !== "true" && ori !== "false") {
  60419. if (ori[0] === "!") {
  60420. result = !evaluateCallback(ori.substring(1));
  60421. }
  60422. else {
  60423. result = evaluateCallback(ori);
  60424. }
  60425. }
  60426. else {
  60427. result = ori === "true" ? true : false;
  60428. }
  60429. }
  60430. }
  60431. // the whole parenthesis scope is replaced by 'true' or 'false'
  60432. return result ? "true" : "false";
  60433. };
  60434. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  60435. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  60436. // remove whitespaces
  60437. r = r.replace(/[\s]/g, function () { return ""; });
  60438. return r.length % 2 ? "!" : "";
  60439. });
  60440. booleanString = booleanString.trim();
  60441. if (booleanString === "!true") {
  60442. booleanString = "false";
  60443. }
  60444. else if (booleanString === "!false") {
  60445. booleanString = "true";
  60446. }
  60447. return booleanString;
  60448. };
  60449. return AndOrNotEvaluator;
  60450. }());
  60451. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  60452. })(BABYLON || (BABYLON = {}));
  60453. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  60454. var BABYLON;
  60455. (function (BABYLON) {
  60456. var Database = /** @class */ (function () {
  60457. function Database(urlToScene, callbackManifestChecked) {
  60458. // Handling various flavors of prefixed version of IndexedDB
  60459. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  60460. this.callbackManifestChecked = callbackManifestChecked;
  60461. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  60462. this.db = null;
  60463. this._enableSceneOffline = false;
  60464. this._enableTexturesOffline = false;
  60465. this.manifestVersionFound = 0;
  60466. this.mustUpdateRessources = false;
  60467. this.hasReachedQuota = false;
  60468. if (!Database.IDBStorageEnabled) {
  60469. this.callbackManifestChecked(true);
  60470. }
  60471. else {
  60472. this.checkManifestFile();
  60473. }
  60474. }
  60475. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  60476. get: function () {
  60477. return this._enableSceneOffline;
  60478. },
  60479. enumerable: true,
  60480. configurable: true
  60481. });
  60482. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  60483. get: function () {
  60484. return this._enableTexturesOffline;
  60485. },
  60486. enumerable: true,
  60487. configurable: true
  60488. });
  60489. Database.prototype.checkManifestFile = function () {
  60490. var _this = this;
  60491. var noManifestFile = function () {
  60492. _this._enableSceneOffline = false;
  60493. _this._enableTexturesOffline = false;
  60494. _this.callbackManifestChecked(false);
  60495. };
  60496. var timeStampUsed = false;
  60497. var manifestURL = this.currentSceneUrl + ".manifest";
  60498. var xhr = new XMLHttpRequest();
  60499. if (navigator.onLine) {
  60500. // Adding a timestamp to by-pass browsers' cache
  60501. timeStampUsed = true;
  60502. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  60503. }
  60504. xhr.open("GET", manifestURL, true);
  60505. xhr.addEventListener("load", function () {
  60506. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60507. try {
  60508. var manifestFile = JSON.parse(xhr.response);
  60509. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  60510. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  60511. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  60512. _this.manifestVersionFound = manifestFile.version;
  60513. }
  60514. if (_this.callbackManifestChecked) {
  60515. _this.callbackManifestChecked(true);
  60516. }
  60517. }
  60518. catch (ex) {
  60519. noManifestFile();
  60520. }
  60521. }
  60522. else {
  60523. noManifestFile();
  60524. }
  60525. }, false);
  60526. xhr.addEventListener("error", function (event) {
  60527. if (timeStampUsed) {
  60528. timeStampUsed = false;
  60529. // Let's retry without the timeStamp
  60530. // It could fail when coupled with HTML5 Offline API
  60531. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  60532. xhr.open("GET", retryManifestURL, true);
  60533. xhr.send();
  60534. }
  60535. else {
  60536. noManifestFile();
  60537. }
  60538. }, false);
  60539. try {
  60540. xhr.send();
  60541. }
  60542. catch (ex) {
  60543. BABYLON.Tools.Error("Error on XHR send request.");
  60544. this.callbackManifestChecked(false);
  60545. }
  60546. };
  60547. Database.prototype.openAsync = function (successCallback, errorCallback) {
  60548. var _this = this;
  60549. var handleError = function () {
  60550. _this.isSupported = false;
  60551. if (errorCallback)
  60552. errorCallback();
  60553. };
  60554. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  60555. // Your browser doesn't support IndexedDB
  60556. this.isSupported = false;
  60557. if (errorCallback)
  60558. errorCallback();
  60559. }
  60560. else {
  60561. // If the DB hasn't been opened or created yet
  60562. if (!this.db) {
  60563. this.hasReachedQuota = false;
  60564. this.isSupported = true;
  60565. var request = this.idbFactory.open("babylonjs", 1);
  60566. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  60567. request.onerror = function (event) {
  60568. handleError();
  60569. };
  60570. // executes when a version change transaction cannot complete due to other active transactions
  60571. request.onblocked = function (event) {
  60572. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  60573. handleError();
  60574. };
  60575. // DB has been opened successfully
  60576. request.onsuccess = function (event) {
  60577. _this.db = request.result;
  60578. successCallback();
  60579. };
  60580. // Initialization of the DB. Creating Scenes & Textures stores
  60581. request.onupgradeneeded = function (event) {
  60582. _this.db = (event.target).result;
  60583. if (_this.db) {
  60584. try {
  60585. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  60586. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  60587. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  60588. }
  60589. catch (ex) {
  60590. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  60591. handleError();
  60592. }
  60593. }
  60594. };
  60595. }
  60596. else {
  60597. if (successCallback)
  60598. successCallback();
  60599. }
  60600. }
  60601. };
  60602. Database.prototype.loadImageFromDB = function (url, image) {
  60603. var _this = this;
  60604. var completeURL = Database.ReturnFullUrlLocation(url);
  60605. var saveAndLoadImage = function () {
  60606. if (!_this.hasReachedQuota && _this.db !== null) {
  60607. // the texture is not yet in the DB, let's try to save it
  60608. _this._saveImageIntoDBAsync(completeURL, image);
  60609. }
  60610. else {
  60611. image.src = url;
  60612. }
  60613. };
  60614. if (!this.mustUpdateRessources) {
  60615. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  60616. }
  60617. else {
  60618. saveAndLoadImage();
  60619. }
  60620. };
  60621. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  60622. if (this.isSupported && this.db !== null) {
  60623. var texture;
  60624. var transaction = this.db.transaction(["textures"]);
  60625. transaction.onabort = function (event) {
  60626. image.src = url;
  60627. };
  60628. transaction.oncomplete = function (event) {
  60629. var blobTextureURL;
  60630. if (texture) {
  60631. var URL = window.URL || window.webkitURL;
  60632. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  60633. image.onerror = function () {
  60634. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  60635. image.src = url;
  60636. };
  60637. image.src = blobTextureURL;
  60638. }
  60639. else {
  60640. notInDBCallback();
  60641. }
  60642. };
  60643. var getRequest = transaction.objectStore("textures").get(url);
  60644. getRequest.onsuccess = function (event) {
  60645. texture = (event.target).result;
  60646. };
  60647. getRequest.onerror = function (event) {
  60648. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  60649. image.src = url;
  60650. };
  60651. }
  60652. else {
  60653. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60654. image.src = url;
  60655. }
  60656. };
  60657. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  60658. var _this = this;
  60659. if (this.isSupported) {
  60660. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  60661. var generateBlobUrl = function () {
  60662. var blobTextureURL;
  60663. if (blob) {
  60664. var URL = window.URL || window.webkitURL;
  60665. try {
  60666. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  60667. }
  60668. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  60669. catch (ex) {
  60670. blobTextureURL = URL.createObjectURL(blob);
  60671. }
  60672. }
  60673. if (blobTextureURL) {
  60674. image.src = blobTextureURL;
  60675. }
  60676. };
  60677. if (Database.IsUASupportingBlobStorage) {
  60678. var xhr = new XMLHttpRequest(), blob;
  60679. xhr.open("GET", url, true);
  60680. xhr.responseType = "blob";
  60681. xhr.addEventListener("load", function () {
  60682. if (xhr.status === 200 && _this.db) {
  60683. // Blob as response (XHR2)
  60684. blob = xhr.response;
  60685. var transaction = _this.db.transaction(["textures"], "readwrite");
  60686. // the transaction could abort because of a QuotaExceededError error
  60687. transaction.onabort = function (event) {
  60688. try {
  60689. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  60690. var srcElement = (event.srcElement || event.target);
  60691. var error = srcElement.error;
  60692. if (error && error.name === "QuotaExceededError") {
  60693. _this.hasReachedQuota = true;
  60694. }
  60695. }
  60696. catch (ex) { }
  60697. generateBlobUrl();
  60698. };
  60699. transaction.oncomplete = function (event) {
  60700. generateBlobUrl();
  60701. };
  60702. var newTexture = { textureUrl: url, data: blob };
  60703. try {
  60704. // Put the blob into the dabase
  60705. var addRequest = transaction.objectStore("textures").put(newTexture);
  60706. addRequest.onsuccess = function (event) {
  60707. };
  60708. addRequest.onerror = function (event) {
  60709. generateBlobUrl();
  60710. };
  60711. }
  60712. catch (ex) {
  60713. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  60714. if (ex.code === 25) {
  60715. Database.IsUASupportingBlobStorage = false;
  60716. }
  60717. image.src = url;
  60718. }
  60719. }
  60720. else {
  60721. image.src = url;
  60722. }
  60723. }, false);
  60724. xhr.addEventListener("error", function (event) {
  60725. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  60726. image.src = url;
  60727. }, false);
  60728. xhr.send();
  60729. }
  60730. else {
  60731. image.src = url;
  60732. }
  60733. }
  60734. else {
  60735. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60736. image.src = url;
  60737. }
  60738. };
  60739. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  60740. var _this = this;
  60741. var updateVersion = function () {
  60742. // the version is not yet in the DB or we need to update it
  60743. _this._saveVersionIntoDBAsync(url, versionLoaded);
  60744. };
  60745. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  60746. };
  60747. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  60748. var _this = this;
  60749. if (this.isSupported && this.db) {
  60750. var version;
  60751. try {
  60752. var transaction = this.db.transaction(["versions"]);
  60753. transaction.oncomplete = function (event) {
  60754. if (version) {
  60755. // If the version in the JSON file is > than the version in DB
  60756. if (_this.manifestVersionFound > version.data) {
  60757. _this.mustUpdateRessources = true;
  60758. updateInDBCallback();
  60759. }
  60760. else {
  60761. callback(version.data);
  60762. }
  60763. }
  60764. else {
  60765. _this.mustUpdateRessources = true;
  60766. updateInDBCallback();
  60767. }
  60768. };
  60769. transaction.onabort = function (event) {
  60770. callback(-1);
  60771. };
  60772. var getRequest = transaction.objectStore("versions").get(url);
  60773. getRequest.onsuccess = function (event) {
  60774. version = (event.target).result;
  60775. };
  60776. getRequest.onerror = function (event) {
  60777. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  60778. callback(-1);
  60779. };
  60780. }
  60781. catch (ex) {
  60782. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  60783. callback(-1);
  60784. }
  60785. }
  60786. else {
  60787. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60788. callback(-1);
  60789. }
  60790. };
  60791. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  60792. var _this = this;
  60793. if (this.isSupported && !this.hasReachedQuota && this.db) {
  60794. try {
  60795. // Open a transaction to the database
  60796. var transaction = this.db.transaction(["versions"], "readwrite");
  60797. // the transaction could abort because of a QuotaExceededError error
  60798. transaction.onabort = function (event) {
  60799. try {
  60800. var error = event.srcElement['error'];
  60801. if (error && error.name === "QuotaExceededError") {
  60802. _this.hasReachedQuota = true;
  60803. }
  60804. }
  60805. catch (ex) { }
  60806. callback(-1);
  60807. };
  60808. transaction.oncomplete = function (event) {
  60809. callback(_this.manifestVersionFound);
  60810. };
  60811. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  60812. // Put the scene into the database
  60813. var addRequest = transaction.objectStore("versions").put(newVersion);
  60814. addRequest.onsuccess = function (event) {
  60815. };
  60816. addRequest.onerror = function (event) {
  60817. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  60818. };
  60819. }
  60820. catch (ex) {
  60821. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  60822. callback(-1);
  60823. }
  60824. }
  60825. else {
  60826. callback(-1);
  60827. }
  60828. };
  60829. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  60830. var _this = this;
  60831. var completeUrl = Database.ReturnFullUrlLocation(url);
  60832. var saveAndLoadFile = function () {
  60833. // the scene is not yet in the DB, let's try to save it
  60834. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  60835. };
  60836. this._checkVersionFromDB(completeUrl, function (version) {
  60837. if (version !== -1) {
  60838. if (!_this.mustUpdateRessources) {
  60839. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  60840. }
  60841. else {
  60842. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  60843. }
  60844. }
  60845. else {
  60846. if (errorCallback) {
  60847. errorCallback();
  60848. }
  60849. }
  60850. });
  60851. };
  60852. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  60853. if (this.isSupported && this.db) {
  60854. var targetStore;
  60855. if (url.indexOf(".babylon") !== -1) {
  60856. targetStore = "scenes";
  60857. }
  60858. else {
  60859. targetStore = "textures";
  60860. }
  60861. var file;
  60862. var transaction = this.db.transaction([targetStore]);
  60863. transaction.oncomplete = function (event) {
  60864. if (file) {
  60865. callback(file.data);
  60866. }
  60867. else {
  60868. notInDBCallback();
  60869. }
  60870. };
  60871. transaction.onabort = function (event) {
  60872. notInDBCallback();
  60873. };
  60874. var getRequest = transaction.objectStore(targetStore).get(url);
  60875. getRequest.onsuccess = function (event) {
  60876. file = (event.target).result;
  60877. };
  60878. getRequest.onerror = function (event) {
  60879. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  60880. notInDBCallback();
  60881. };
  60882. }
  60883. else {
  60884. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60885. callback();
  60886. }
  60887. };
  60888. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  60889. var _this = this;
  60890. if (this.isSupported) {
  60891. var targetStore;
  60892. if (url.indexOf(".babylon") !== -1) {
  60893. targetStore = "scenes";
  60894. }
  60895. else {
  60896. targetStore = "textures";
  60897. }
  60898. // Create XHR
  60899. var xhr = new XMLHttpRequest();
  60900. var fileData;
  60901. xhr.open("GET", url, true);
  60902. if (useArrayBuffer) {
  60903. xhr.responseType = "arraybuffer";
  60904. }
  60905. if (progressCallback) {
  60906. xhr.onprogress = progressCallback;
  60907. }
  60908. xhr.addEventListener("load", function () {
  60909. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  60910. // Blob as response (XHR2)
  60911. //fileData = xhr.responseText;
  60912. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  60913. if (!_this.hasReachedQuota && _this.db) {
  60914. // Open a transaction to the database
  60915. var transaction = _this.db.transaction([targetStore], "readwrite");
  60916. // the transaction could abort because of a QuotaExceededError error
  60917. transaction.onabort = function (event) {
  60918. try {
  60919. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  60920. var error = event.srcElement['error'];
  60921. if (error && error.name === "QuotaExceededError") {
  60922. _this.hasReachedQuota = true;
  60923. }
  60924. }
  60925. catch (ex) { }
  60926. callback(fileData);
  60927. };
  60928. transaction.oncomplete = function (event) {
  60929. callback(fileData);
  60930. };
  60931. var newFile;
  60932. if (targetStore === "scenes") {
  60933. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  60934. }
  60935. else {
  60936. newFile = { textureUrl: url, data: fileData };
  60937. }
  60938. try {
  60939. // Put the scene into the database
  60940. var addRequest = transaction.objectStore(targetStore).put(newFile);
  60941. addRequest.onsuccess = function (event) {
  60942. };
  60943. addRequest.onerror = function (event) {
  60944. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  60945. };
  60946. }
  60947. catch (ex) {
  60948. callback(fileData);
  60949. }
  60950. }
  60951. else {
  60952. callback(fileData);
  60953. }
  60954. }
  60955. else {
  60956. callback();
  60957. }
  60958. }, false);
  60959. xhr.addEventListener("error", function (event) {
  60960. BABYLON.Tools.Error("error on XHR request.");
  60961. callback();
  60962. }, false);
  60963. xhr.send();
  60964. }
  60965. else {
  60966. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60967. callback();
  60968. }
  60969. };
  60970. Database.IsUASupportingBlobStorage = true;
  60971. Database.IDBStorageEnabled = true;
  60972. Database.parseURL = function (url) {
  60973. var a = document.createElement('a');
  60974. a.href = url;
  60975. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  60976. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  60977. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  60978. return absLocation;
  60979. };
  60980. Database.ReturnFullUrlLocation = function (url) {
  60981. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  60982. return (Database.parseURL(window.location.href) + url);
  60983. }
  60984. else {
  60985. return url;
  60986. }
  60987. };
  60988. return Database;
  60989. }());
  60990. BABYLON.Database = Database;
  60991. })(BABYLON || (BABYLON = {}));
  60992. //# sourceMappingURL=babylon.database.js.map
  60993. var BABYLON;
  60994. (function (BABYLON) {
  60995. var FresnelParameters = /** @class */ (function () {
  60996. function FresnelParameters() {
  60997. this._isEnabled = true;
  60998. this.leftColor = BABYLON.Color3.White();
  60999. this.rightColor = BABYLON.Color3.Black();
  61000. this.bias = 0;
  61001. this.power = 1;
  61002. }
  61003. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61004. get: function () {
  61005. return this._isEnabled;
  61006. },
  61007. set: function (value) {
  61008. if (this._isEnabled === value) {
  61009. return;
  61010. }
  61011. this._isEnabled = value;
  61012. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61013. },
  61014. enumerable: true,
  61015. configurable: true
  61016. });
  61017. FresnelParameters.prototype.clone = function () {
  61018. var newFresnelParameters = new FresnelParameters();
  61019. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61020. return newFresnelParameters;
  61021. };
  61022. FresnelParameters.prototype.serialize = function () {
  61023. var serializationObject = {};
  61024. serializationObject.isEnabled = this.isEnabled;
  61025. serializationObject.leftColor = this.leftColor;
  61026. serializationObject.rightColor = this.rightColor;
  61027. serializationObject.bias = this.bias;
  61028. serializationObject.power = this.power;
  61029. return serializationObject;
  61030. };
  61031. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61032. var fresnelParameters = new FresnelParameters();
  61033. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61034. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61035. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61036. fresnelParameters.bias = parsedFresnelParameters.bias;
  61037. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61038. return fresnelParameters;
  61039. };
  61040. return FresnelParameters;
  61041. }());
  61042. BABYLON.FresnelParameters = FresnelParameters;
  61043. })(BABYLON || (BABYLON = {}));
  61044. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61045. var BABYLON;
  61046. (function (BABYLON) {
  61047. var MultiMaterial = /** @class */ (function (_super) {
  61048. __extends(MultiMaterial, _super);
  61049. function MultiMaterial(name, scene) {
  61050. var _this = _super.call(this, name, scene, true) || this;
  61051. scene.multiMaterials.push(_this);
  61052. _this.subMaterials = new Array();
  61053. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61054. return _this;
  61055. }
  61056. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61057. get: function () {
  61058. return this._subMaterials;
  61059. },
  61060. set: function (value) {
  61061. this._subMaterials = value;
  61062. this._hookArray(value);
  61063. },
  61064. enumerable: true,
  61065. configurable: true
  61066. });
  61067. MultiMaterial.prototype._hookArray = function (array) {
  61068. var _this = this;
  61069. var oldPush = array.push;
  61070. array.push = function () {
  61071. var items = [];
  61072. for (var _i = 0; _i < arguments.length; _i++) {
  61073. items[_i] = arguments[_i];
  61074. }
  61075. var result = oldPush.apply(array, items);
  61076. _this._markAllSubMeshesAsTexturesDirty();
  61077. return result;
  61078. };
  61079. var oldSplice = array.splice;
  61080. array.splice = function (index, deleteCount) {
  61081. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61082. _this._markAllSubMeshesAsTexturesDirty();
  61083. return deleted;
  61084. };
  61085. };
  61086. // Properties
  61087. MultiMaterial.prototype.getSubMaterial = function (index) {
  61088. if (index < 0 || index >= this.subMaterials.length) {
  61089. return this.getScene().defaultMaterial;
  61090. }
  61091. return this.subMaterials[index];
  61092. };
  61093. MultiMaterial.prototype.getActiveTextures = function () {
  61094. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61095. if (subMaterial) {
  61096. return subMaterial.getActiveTextures();
  61097. }
  61098. else {
  61099. return [];
  61100. }
  61101. }));
  61102. var _a;
  61103. };
  61104. // Methods
  61105. MultiMaterial.prototype.getClassName = function () {
  61106. return "MultiMaterial";
  61107. };
  61108. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61109. for (var index = 0; index < this.subMaterials.length; index++) {
  61110. var subMaterial = this.subMaterials[index];
  61111. if (subMaterial) {
  61112. if (subMaterial.storeEffectOnSubMeshes) {
  61113. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61114. return false;
  61115. }
  61116. continue;
  61117. }
  61118. if (!subMaterial.isReady(mesh)) {
  61119. return false;
  61120. }
  61121. }
  61122. }
  61123. return true;
  61124. };
  61125. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61126. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61127. for (var index = 0; index < this.subMaterials.length; index++) {
  61128. var subMaterial = null;
  61129. var current = this.subMaterials[index];
  61130. if (cloneChildren && current) {
  61131. subMaterial = current.clone(name + "-" + current.name);
  61132. }
  61133. else {
  61134. subMaterial = this.subMaterials[index];
  61135. }
  61136. newMultiMaterial.subMaterials.push(subMaterial);
  61137. }
  61138. return newMultiMaterial;
  61139. };
  61140. MultiMaterial.prototype.serialize = function () {
  61141. var serializationObject = {};
  61142. serializationObject.name = this.name;
  61143. serializationObject.id = this.id;
  61144. if (BABYLON.Tags) {
  61145. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61146. }
  61147. serializationObject.materials = [];
  61148. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61149. var subMat = this.subMaterials[matIndex];
  61150. if (subMat) {
  61151. serializationObject.materials.push(subMat.id);
  61152. }
  61153. else {
  61154. serializationObject.materials.push(null);
  61155. }
  61156. }
  61157. return serializationObject;
  61158. };
  61159. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61160. var scene = this.getScene();
  61161. if (!scene) {
  61162. return;
  61163. }
  61164. var index = scene.multiMaterials.indexOf(this);
  61165. if (index >= 0) {
  61166. scene.multiMaterials.splice(index, 1);
  61167. }
  61168. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61169. };
  61170. return MultiMaterial;
  61171. }(BABYLON.Material));
  61172. BABYLON.MultiMaterial = MultiMaterial;
  61173. })(BABYLON || (BABYLON = {}));
  61174. //# sourceMappingURL=babylon.multiMaterial.js.map
  61175. var BABYLON;
  61176. (function (BABYLON) {
  61177. var FreeCameraTouchInput = /** @class */ (function () {
  61178. function FreeCameraTouchInput() {
  61179. this._offsetX = null;
  61180. this._offsetY = null;
  61181. this._pointerPressed = new Array();
  61182. this.touchAngularSensibility = 200000.0;
  61183. this.touchMoveSensibility = 250.0;
  61184. }
  61185. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61186. var _this = this;
  61187. var previousPosition = null;
  61188. if (this._pointerInput === undefined) {
  61189. this._onLostFocus = function (evt) {
  61190. _this._offsetX = null;
  61191. _this._offsetY = null;
  61192. };
  61193. this._pointerInput = function (p, s) {
  61194. var evt = p.event;
  61195. if (evt.pointerType === "mouse") {
  61196. return;
  61197. }
  61198. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61199. if (!noPreventDefault) {
  61200. evt.preventDefault();
  61201. }
  61202. _this._pointerPressed.push(evt.pointerId);
  61203. if (_this._pointerPressed.length !== 1) {
  61204. return;
  61205. }
  61206. previousPosition = {
  61207. x: evt.clientX,
  61208. y: evt.clientY
  61209. };
  61210. }
  61211. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61212. if (!noPreventDefault) {
  61213. evt.preventDefault();
  61214. }
  61215. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61216. if (index === -1) {
  61217. return;
  61218. }
  61219. _this._pointerPressed.splice(index, 1);
  61220. if (index != 0) {
  61221. return;
  61222. }
  61223. previousPosition = null;
  61224. _this._offsetX = null;
  61225. _this._offsetY = null;
  61226. }
  61227. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61228. if (!noPreventDefault) {
  61229. evt.preventDefault();
  61230. }
  61231. if (!previousPosition) {
  61232. return;
  61233. }
  61234. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61235. if (index != 0) {
  61236. return;
  61237. }
  61238. _this._offsetX = evt.clientX - previousPosition.x;
  61239. _this._offsetY = -(evt.clientY - previousPosition.y);
  61240. }
  61241. };
  61242. }
  61243. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61244. if (this._onLostFocus) {
  61245. element.addEventListener("blur", this._onLostFocus);
  61246. }
  61247. };
  61248. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61249. if (this._pointerInput && element) {
  61250. if (this._observer) {
  61251. this.camera.getScene().onPointerObservable.remove(this._observer);
  61252. this._observer = null;
  61253. }
  61254. if (this._onLostFocus) {
  61255. element.removeEventListener("blur", this._onLostFocus);
  61256. this._onLostFocus = null;
  61257. }
  61258. this._pointerPressed = [];
  61259. this._offsetX = null;
  61260. this._offsetY = null;
  61261. }
  61262. };
  61263. FreeCameraTouchInput.prototype.checkInputs = function () {
  61264. if (this._offsetX && this._offsetY) {
  61265. var camera = this.camera;
  61266. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61267. if (this._pointerPressed.length > 1) {
  61268. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61269. }
  61270. else {
  61271. var speed = camera._computeLocalCameraSpeed();
  61272. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61273. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61274. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61275. }
  61276. }
  61277. };
  61278. FreeCameraTouchInput.prototype.getClassName = function () {
  61279. return "FreeCameraTouchInput";
  61280. };
  61281. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61282. return "touch";
  61283. };
  61284. __decorate([
  61285. BABYLON.serialize()
  61286. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61287. __decorate([
  61288. BABYLON.serialize()
  61289. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61290. return FreeCameraTouchInput;
  61291. }());
  61292. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61293. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61294. })(BABYLON || (BABYLON = {}));
  61295. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61296. var BABYLON;
  61297. (function (BABYLON) {
  61298. // We're mainly based on the logic defined into the FreeCamera code
  61299. var TouchCamera = /** @class */ (function (_super) {
  61300. __extends(TouchCamera, _super);
  61301. //-- end properties for backward compatibility for inputs
  61302. function TouchCamera(name, position, scene) {
  61303. var _this = _super.call(this, name, position, scene) || this;
  61304. _this.inputs.addTouch();
  61305. _this._setupInputs();
  61306. return _this;
  61307. }
  61308. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61309. //-- Begin properties for backward compatibility for inputs
  61310. get: function () {
  61311. var touch = this.inputs.attached["touch"];
  61312. if (touch)
  61313. return touch.touchAngularSensibility;
  61314. return 0;
  61315. },
  61316. set: function (value) {
  61317. var touch = this.inputs.attached["touch"];
  61318. if (touch)
  61319. touch.touchAngularSensibility = value;
  61320. },
  61321. enumerable: true,
  61322. configurable: true
  61323. });
  61324. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61325. get: function () {
  61326. var touch = this.inputs.attached["touch"];
  61327. if (touch)
  61328. return touch.touchMoveSensibility;
  61329. return 0;
  61330. },
  61331. set: function (value) {
  61332. var touch = this.inputs.attached["touch"];
  61333. if (touch)
  61334. touch.touchMoveSensibility = value;
  61335. },
  61336. enumerable: true,
  61337. configurable: true
  61338. });
  61339. TouchCamera.prototype.getClassName = function () {
  61340. return "TouchCamera";
  61341. };
  61342. TouchCamera.prototype._setupInputs = function () {
  61343. var mouse = this.inputs.attached["mouse"];
  61344. if (mouse) {
  61345. mouse.touchEnabled = false;
  61346. }
  61347. };
  61348. return TouchCamera;
  61349. }(BABYLON.FreeCamera));
  61350. BABYLON.TouchCamera = TouchCamera;
  61351. })(BABYLON || (BABYLON = {}));
  61352. //# sourceMappingURL=babylon.touchCamera.js.map
  61353. var BABYLON;
  61354. (function (BABYLON) {
  61355. var ProceduralTexture = /** @class */ (function (_super) {
  61356. __extends(ProceduralTexture, _super);
  61357. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  61358. if (fallbackTexture === void 0) { fallbackTexture = null; }
  61359. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61360. if (isCube === void 0) { isCube = false; }
  61361. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61362. _this.isCube = isCube;
  61363. _this.isEnabled = true;
  61364. _this._currentRefreshId = -1;
  61365. _this._refreshRate = 1;
  61366. _this._vertexBuffers = {};
  61367. _this._uniforms = new Array();
  61368. _this._samplers = new Array();
  61369. _this._textures = {};
  61370. _this._floats = {};
  61371. _this._floatsArrays = {};
  61372. _this._colors3 = {};
  61373. _this._colors4 = {};
  61374. _this._vectors2 = {};
  61375. _this._vectors3 = {};
  61376. _this._matrices = {};
  61377. _this._fallbackTextureUsed = false;
  61378. scene._proceduralTextures.push(_this);
  61379. _this._engine = scene.getEngine();
  61380. _this.name = name;
  61381. _this.isRenderTarget = true;
  61382. _this._size = size;
  61383. _this._generateMipMaps = generateMipMaps;
  61384. _this.setFragment(fragment);
  61385. _this._fallbackTexture = fallbackTexture;
  61386. if (isCube) {
  61387. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  61388. _this.setFloat("face", 0);
  61389. }
  61390. else {
  61391. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  61392. }
  61393. // VBO
  61394. var vertices = [];
  61395. vertices.push(1, 1);
  61396. vertices.push(-1, 1);
  61397. vertices.push(-1, -1);
  61398. vertices.push(1, -1);
  61399. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61400. _this._createIndexBuffer();
  61401. return _this;
  61402. }
  61403. ProceduralTexture.prototype._createIndexBuffer = function () {
  61404. var engine = this._engine;
  61405. // Indices
  61406. var indices = [];
  61407. indices.push(0);
  61408. indices.push(1);
  61409. indices.push(2);
  61410. indices.push(0);
  61411. indices.push(2);
  61412. indices.push(3);
  61413. this._indexBuffer = engine.createIndexBuffer(indices);
  61414. };
  61415. ProceduralTexture.prototype._rebuild = function () {
  61416. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61417. if (vb) {
  61418. vb._rebuild();
  61419. }
  61420. this._createIndexBuffer();
  61421. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61422. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61423. }
  61424. };
  61425. ProceduralTexture.prototype.reset = function () {
  61426. if (this._effect === undefined) {
  61427. return;
  61428. }
  61429. var engine = this._engine;
  61430. engine._releaseEffect(this._effect);
  61431. };
  61432. ProceduralTexture.prototype.isReady = function () {
  61433. var _this = this;
  61434. var engine = this._engine;
  61435. var shaders;
  61436. if (!this._fragment) {
  61437. return false;
  61438. }
  61439. if (this._fallbackTextureUsed) {
  61440. return true;
  61441. }
  61442. if (this._fragment.fragmentElement !== undefined) {
  61443. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  61444. }
  61445. else {
  61446. shaders = { vertex: "procedural", fragment: this._fragment };
  61447. }
  61448. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  61449. _this.releaseInternalTexture();
  61450. if (_this._fallbackTexture) {
  61451. _this._texture = _this._fallbackTexture._texture;
  61452. if (_this._texture) {
  61453. _this._texture.incrementReferences();
  61454. }
  61455. }
  61456. _this._fallbackTextureUsed = true;
  61457. });
  61458. return this._effect.isReady();
  61459. };
  61460. ProceduralTexture.prototype.resetRefreshCounter = function () {
  61461. this._currentRefreshId = -1;
  61462. };
  61463. ProceduralTexture.prototype.setFragment = function (fragment) {
  61464. this._fragment = fragment;
  61465. };
  61466. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  61467. get: function () {
  61468. return this._refreshRate;
  61469. },
  61470. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61471. set: function (value) {
  61472. this._refreshRate = value;
  61473. this.resetRefreshCounter();
  61474. },
  61475. enumerable: true,
  61476. configurable: true
  61477. });
  61478. ProceduralTexture.prototype._shouldRender = function () {
  61479. if (!this.isEnabled || !this.isReady() || !this._texture) {
  61480. return false;
  61481. }
  61482. if (this._fallbackTextureUsed) {
  61483. return false;
  61484. }
  61485. if (this._currentRefreshId === -1) {
  61486. this._currentRefreshId = 1;
  61487. return true;
  61488. }
  61489. if (this.refreshRate === this._currentRefreshId) {
  61490. this._currentRefreshId = 1;
  61491. return true;
  61492. }
  61493. this._currentRefreshId++;
  61494. return false;
  61495. };
  61496. ProceduralTexture.prototype.getRenderSize = function () {
  61497. return this._size;
  61498. };
  61499. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  61500. if (this._fallbackTextureUsed) {
  61501. return;
  61502. }
  61503. this.releaseInternalTexture();
  61504. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  61505. };
  61506. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  61507. if (this._uniforms.indexOf(uniformName) === -1) {
  61508. this._uniforms.push(uniformName);
  61509. }
  61510. };
  61511. ProceduralTexture.prototype.setTexture = function (name, texture) {
  61512. if (this._samplers.indexOf(name) === -1) {
  61513. this._samplers.push(name);
  61514. }
  61515. this._textures[name] = texture;
  61516. return this;
  61517. };
  61518. ProceduralTexture.prototype.setFloat = function (name, value) {
  61519. this._checkUniform(name);
  61520. this._floats[name] = value;
  61521. return this;
  61522. };
  61523. ProceduralTexture.prototype.setFloats = function (name, value) {
  61524. this._checkUniform(name);
  61525. this._floatsArrays[name] = value;
  61526. return this;
  61527. };
  61528. ProceduralTexture.prototype.setColor3 = function (name, value) {
  61529. this._checkUniform(name);
  61530. this._colors3[name] = value;
  61531. return this;
  61532. };
  61533. ProceduralTexture.prototype.setColor4 = function (name, value) {
  61534. this._checkUniform(name);
  61535. this._colors4[name] = value;
  61536. return this;
  61537. };
  61538. ProceduralTexture.prototype.setVector2 = function (name, value) {
  61539. this._checkUniform(name);
  61540. this._vectors2[name] = value;
  61541. return this;
  61542. };
  61543. ProceduralTexture.prototype.setVector3 = function (name, value) {
  61544. this._checkUniform(name);
  61545. this._vectors3[name] = value;
  61546. return this;
  61547. };
  61548. ProceduralTexture.prototype.setMatrix = function (name, value) {
  61549. this._checkUniform(name);
  61550. this._matrices[name] = value;
  61551. return this;
  61552. };
  61553. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  61554. var scene = this.getScene();
  61555. if (!scene) {
  61556. return;
  61557. }
  61558. var engine = this._engine;
  61559. // Render
  61560. engine.enableEffect(this._effect);
  61561. engine.setState(false);
  61562. // Texture
  61563. for (var name in this._textures) {
  61564. this._effect.setTexture(name, this._textures[name]);
  61565. }
  61566. // Float
  61567. for (name in this._floats) {
  61568. this._effect.setFloat(name, this._floats[name]);
  61569. }
  61570. // Floats
  61571. for (name in this._floatsArrays) {
  61572. this._effect.setArray(name, this._floatsArrays[name]);
  61573. }
  61574. // Color3
  61575. for (name in this._colors3) {
  61576. this._effect.setColor3(name, this._colors3[name]);
  61577. }
  61578. // Color4
  61579. for (name in this._colors4) {
  61580. var color = this._colors4[name];
  61581. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  61582. }
  61583. // Vector2
  61584. for (name in this._vectors2) {
  61585. this._effect.setVector2(name, this._vectors2[name]);
  61586. }
  61587. // Vector3
  61588. for (name in this._vectors3) {
  61589. this._effect.setVector3(name, this._vectors3[name]);
  61590. }
  61591. // Matrix
  61592. for (name in this._matrices) {
  61593. this._effect.setMatrix(name, this._matrices[name]);
  61594. }
  61595. if (!this._texture) {
  61596. return;
  61597. }
  61598. if (this.isCube) {
  61599. for (var face = 0; face < 6; face++) {
  61600. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  61601. // VBOs
  61602. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  61603. this._effect.setFloat("face", face);
  61604. // Clear
  61605. engine.clear(scene.clearColor, true, true, true);
  61606. // Draw order
  61607. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  61608. // Mipmaps
  61609. if (face === 5) {
  61610. engine.generateMipMapsForCubemap(this._texture);
  61611. }
  61612. }
  61613. }
  61614. else {
  61615. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  61616. // VBOs
  61617. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  61618. // Clear
  61619. engine.clear(scene.clearColor, true, true, true);
  61620. // Draw order
  61621. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  61622. }
  61623. // Unbind
  61624. engine.unBindFramebuffer(this._texture, this.isCube);
  61625. if (this.onGenerated) {
  61626. this.onGenerated();
  61627. }
  61628. };
  61629. ProceduralTexture.prototype.clone = function () {
  61630. var textureSize = this.getSize();
  61631. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  61632. // Base texture
  61633. newTexture.hasAlpha = this.hasAlpha;
  61634. newTexture.level = this.level;
  61635. // RenderTarget Texture
  61636. newTexture.coordinatesMode = this.coordinatesMode;
  61637. return newTexture;
  61638. };
  61639. ProceduralTexture.prototype.dispose = function () {
  61640. var scene = this.getScene();
  61641. if (!scene) {
  61642. return;
  61643. }
  61644. var index = scene._proceduralTextures.indexOf(this);
  61645. if (index >= 0) {
  61646. scene._proceduralTextures.splice(index, 1);
  61647. }
  61648. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61649. if (vertexBuffer) {
  61650. vertexBuffer.dispose();
  61651. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61652. }
  61653. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  61654. this._indexBuffer = null;
  61655. }
  61656. _super.prototype.dispose.call(this);
  61657. };
  61658. return ProceduralTexture;
  61659. }(BABYLON.Texture));
  61660. BABYLON.ProceduralTexture = ProceduralTexture;
  61661. })(BABYLON || (BABYLON = {}));
  61662. //# sourceMappingURL=babylon.proceduralTexture.js.map
  61663. var BABYLON;
  61664. (function (BABYLON) {
  61665. var CustomProceduralTexture = /** @class */ (function (_super) {
  61666. __extends(CustomProceduralTexture, _super);
  61667. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  61668. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  61669. _this._animate = true;
  61670. _this._time = 0;
  61671. _this._texturePath = texturePath;
  61672. //Try to load json
  61673. _this.loadJson(texturePath);
  61674. _this.refreshRate = 1;
  61675. return _this;
  61676. }
  61677. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  61678. var _this = this;
  61679. var noConfigFile = function () {
  61680. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  61681. try {
  61682. _this.setFragment(_this._texturePath);
  61683. }
  61684. catch (ex) {
  61685. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  61686. }
  61687. };
  61688. var configFileUrl = jsonUrl + "/config.json";
  61689. var xhr = new XMLHttpRequest();
  61690. xhr.open("GET", configFileUrl, true);
  61691. xhr.addEventListener("load", function () {
  61692. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61693. try {
  61694. _this._config = JSON.parse(xhr.response);
  61695. _this.updateShaderUniforms();
  61696. _this.updateTextures();
  61697. _this.setFragment(_this._texturePath + "/custom");
  61698. _this._animate = _this._config.animate;
  61699. _this.refreshRate = _this._config.refreshrate;
  61700. }
  61701. catch (ex) {
  61702. noConfigFile();
  61703. }
  61704. }
  61705. else {
  61706. noConfigFile();
  61707. }
  61708. }, false);
  61709. xhr.addEventListener("error", function () {
  61710. noConfigFile();
  61711. }, false);
  61712. try {
  61713. xhr.send();
  61714. }
  61715. catch (ex) {
  61716. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  61717. }
  61718. };
  61719. CustomProceduralTexture.prototype.isReady = function () {
  61720. if (!_super.prototype.isReady.call(this)) {
  61721. return false;
  61722. }
  61723. for (var name in this._textures) {
  61724. var texture = this._textures[name];
  61725. if (!texture.isReady()) {
  61726. return false;
  61727. }
  61728. }
  61729. return true;
  61730. };
  61731. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  61732. var scene = this.getScene();
  61733. if (this._animate && scene) {
  61734. this._time += scene.getAnimationRatio() * 0.03;
  61735. this.updateShaderUniforms();
  61736. }
  61737. _super.prototype.render.call(this, useCameraPostProcess);
  61738. };
  61739. CustomProceduralTexture.prototype.updateTextures = function () {
  61740. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  61741. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  61742. }
  61743. };
  61744. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  61745. if (this._config) {
  61746. for (var j = 0; j < this._config.uniforms.length; j++) {
  61747. var uniform = this._config.uniforms[j];
  61748. switch (uniform.type) {
  61749. case "float":
  61750. this.setFloat(uniform.name, uniform.value);
  61751. break;
  61752. case "color3":
  61753. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  61754. break;
  61755. case "color4":
  61756. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  61757. break;
  61758. case "vector2":
  61759. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  61760. break;
  61761. case "vector3":
  61762. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  61763. break;
  61764. }
  61765. }
  61766. }
  61767. this.setFloat("time", this._time);
  61768. };
  61769. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  61770. get: function () {
  61771. return this._animate;
  61772. },
  61773. set: function (value) {
  61774. this._animate = value;
  61775. },
  61776. enumerable: true,
  61777. configurable: true
  61778. });
  61779. return CustomProceduralTexture;
  61780. }(BABYLON.ProceduralTexture));
  61781. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  61782. })(BABYLON || (BABYLON = {}));
  61783. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  61784. var BABYLON;
  61785. (function (BABYLON) {
  61786. var FreeCameraGamepadInput = /** @class */ (function () {
  61787. function FreeCameraGamepadInput() {
  61788. this.gamepadAngularSensibility = 200;
  61789. this.gamepadMoveSensibility = 40;
  61790. // private members
  61791. this._cameraTransform = BABYLON.Matrix.Identity();
  61792. this._deltaTransform = BABYLON.Vector3.Zero();
  61793. this._vector3 = BABYLON.Vector3.Zero();
  61794. this._vector2 = BABYLON.Vector2.Zero();
  61795. }
  61796. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  61797. var _this = this;
  61798. var manager = this.camera.getScene().gamepadManager;
  61799. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  61800. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  61801. // prioritize XBOX gamepads.
  61802. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  61803. _this.gamepad = gamepad;
  61804. }
  61805. }
  61806. });
  61807. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  61808. if (_this.gamepad === gamepad) {
  61809. _this.gamepad = null;
  61810. }
  61811. });
  61812. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  61813. };
  61814. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  61815. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  61816. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  61817. this.gamepad = null;
  61818. };
  61819. FreeCameraGamepadInput.prototype.checkInputs = function () {
  61820. if (this.gamepad && this.gamepad.leftStick) {
  61821. var camera = this.camera;
  61822. var LSValues = this.gamepad.leftStick;
  61823. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  61824. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  61825. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  61826. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  61827. var RSValues = this.gamepad.rightStick;
  61828. if (RSValues) {
  61829. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  61830. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  61831. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  61832. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  61833. }
  61834. else {
  61835. RSValues = { x: 0, y: 0 };
  61836. }
  61837. if (!camera.rotationQuaternion) {
  61838. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  61839. }
  61840. else {
  61841. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  61842. }
  61843. var speed = camera._computeLocalCameraSpeed() * 50.0;
  61844. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  61845. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  61846. camera.cameraDirection.addInPlace(this._deltaTransform);
  61847. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  61848. camera.cameraRotation.addInPlace(this._vector2);
  61849. }
  61850. };
  61851. FreeCameraGamepadInput.prototype.getClassName = function () {
  61852. return "FreeCameraGamepadInput";
  61853. };
  61854. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  61855. return "gamepad";
  61856. };
  61857. __decorate([
  61858. BABYLON.serialize()
  61859. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  61860. __decorate([
  61861. BABYLON.serialize()
  61862. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  61863. return FreeCameraGamepadInput;
  61864. }());
  61865. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  61866. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  61867. })(BABYLON || (BABYLON = {}));
  61868. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  61869. var BABYLON;
  61870. (function (BABYLON) {
  61871. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  61872. function ArcRotateCameraGamepadInput() {
  61873. this.gamepadRotationSensibility = 80;
  61874. this.gamepadMoveSensibility = 40;
  61875. }
  61876. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  61877. var _this = this;
  61878. var manager = this.camera.getScene().gamepadManager;
  61879. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  61880. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  61881. // prioritize XBOX gamepads.
  61882. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  61883. _this.gamepad = gamepad;
  61884. }
  61885. }
  61886. });
  61887. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  61888. if (_this.gamepad === gamepad) {
  61889. _this.gamepad = null;
  61890. }
  61891. });
  61892. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  61893. };
  61894. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  61895. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  61896. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  61897. this.gamepad = null;
  61898. };
  61899. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  61900. if (this.gamepad) {
  61901. var camera = this.camera;
  61902. var RSValues = this.gamepad.rightStick;
  61903. if (RSValues) {
  61904. if (RSValues.x != 0) {
  61905. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  61906. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  61907. camera.inertialAlphaOffset += normalizedRX;
  61908. }
  61909. }
  61910. if (RSValues.y != 0) {
  61911. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  61912. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  61913. camera.inertialBetaOffset += normalizedRY;
  61914. }
  61915. }
  61916. }
  61917. var LSValues = this.gamepad.leftStick;
  61918. if (LSValues && LSValues.y != 0) {
  61919. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  61920. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  61921. this.camera.inertialRadiusOffset -= normalizedLY;
  61922. }
  61923. }
  61924. }
  61925. };
  61926. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  61927. return "ArcRotateCameraGamepadInput";
  61928. };
  61929. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  61930. return "gamepad";
  61931. };
  61932. __decorate([
  61933. BABYLON.serialize()
  61934. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  61935. __decorate([
  61936. BABYLON.serialize()
  61937. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  61938. return ArcRotateCameraGamepadInput;
  61939. }());
  61940. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  61941. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  61942. })(BABYLON || (BABYLON = {}));
  61943. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  61944. var BABYLON;
  61945. (function (BABYLON) {
  61946. var GamepadManager = /** @class */ (function () {
  61947. function GamepadManager(_scene) {
  61948. var _this = this;
  61949. this._scene = _scene;
  61950. this._babylonGamepads = [];
  61951. this._oneGamepadConnected = false;
  61952. this._isMonitoring = false;
  61953. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  61954. if (!BABYLON.Tools.IsWindowObjectExist()) {
  61955. this._gamepadEventSupported = false;
  61956. }
  61957. else {
  61958. this._gamepadEventSupported = 'GamepadEvent' in window;
  61959. this._gamepadSupport = (navigator.getGamepads ||
  61960. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  61961. }
  61962. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  61963. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  61964. for (var i in _this._babylonGamepads) {
  61965. var gamepad = _this._babylonGamepads[i];
  61966. if (gamepad && gamepad._isConnected) {
  61967. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  61968. }
  61969. }
  61970. });
  61971. this._onGamepadConnectedEvent = function (evt) {
  61972. var gamepad = evt.gamepad;
  61973. if (gamepad.index in _this._babylonGamepads) {
  61974. if (_this._babylonGamepads[gamepad.index].isConnected) {
  61975. return;
  61976. }
  61977. }
  61978. var newGamepad;
  61979. if (_this._babylonGamepads[gamepad.index]) {
  61980. newGamepad = _this._babylonGamepads[gamepad.index];
  61981. newGamepad.browserGamepad = gamepad;
  61982. newGamepad._isConnected = true;
  61983. }
  61984. else {
  61985. newGamepad = _this._addNewGamepad(gamepad);
  61986. }
  61987. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  61988. _this._startMonitoringGamepads();
  61989. };
  61990. this._onGamepadDisconnectedEvent = function (evt) {
  61991. var gamepad = evt.gamepad;
  61992. // Remove the gamepad from the list of gamepads to monitor.
  61993. for (var i in _this._babylonGamepads) {
  61994. if (_this._babylonGamepads[i].index === gamepad.index) {
  61995. var disconnectedGamepad = _this._babylonGamepads[i];
  61996. disconnectedGamepad._isConnected = false;
  61997. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  61998. break;
  61999. }
  62000. }
  62001. };
  62002. if (this._gamepadSupport) {
  62003. //first add already-connected gamepads
  62004. this._updateGamepadObjects();
  62005. if (this._babylonGamepads.length) {
  62006. this._startMonitoringGamepads();
  62007. }
  62008. // Checking if the gamepad connected event is supported (like in Firefox)
  62009. if (this._gamepadEventSupported) {
  62010. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62011. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62012. }
  62013. else {
  62014. this._startMonitoringGamepads();
  62015. }
  62016. }
  62017. }
  62018. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62019. get: function () {
  62020. return this._babylonGamepads;
  62021. },
  62022. enumerable: true,
  62023. configurable: true
  62024. });
  62025. GamepadManager.prototype.getGamepadByType = function (type) {
  62026. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62027. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62028. var gamepad = _a[_i];
  62029. if (gamepad && gamepad.type === type) {
  62030. return gamepad;
  62031. }
  62032. }
  62033. return null;
  62034. };
  62035. GamepadManager.prototype.dispose = function () {
  62036. if (this._gamepadEventSupported) {
  62037. if (this._onGamepadConnectedEvent) {
  62038. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62039. }
  62040. if (this._onGamepadDisconnectedEvent) {
  62041. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62042. }
  62043. this._onGamepadConnectedEvent = null;
  62044. this._onGamepadDisconnectedEvent = null;
  62045. }
  62046. this._babylonGamepads.forEach(function (gamepad) {
  62047. gamepad.dispose();
  62048. });
  62049. this.onGamepadConnectedObservable.clear();
  62050. this.onGamepadDisconnectedObservable.clear();
  62051. this._oneGamepadConnected = false;
  62052. this._stopMonitoringGamepads();
  62053. this._babylonGamepads = [];
  62054. };
  62055. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62056. if (!this._oneGamepadConnected) {
  62057. this._oneGamepadConnected = true;
  62058. }
  62059. var newGamepad;
  62060. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62061. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62062. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62063. }
  62064. else if (gamepad.pose) {
  62065. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62066. }
  62067. else {
  62068. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62069. }
  62070. this._babylonGamepads[newGamepad.index] = newGamepad;
  62071. return newGamepad;
  62072. };
  62073. GamepadManager.prototype._startMonitoringGamepads = function () {
  62074. if (!this._isMonitoring) {
  62075. this._isMonitoring = true;
  62076. //back-comp
  62077. if (!this._scene) {
  62078. this._checkGamepadsStatus();
  62079. }
  62080. }
  62081. };
  62082. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62083. this._isMonitoring = false;
  62084. };
  62085. GamepadManager.prototype._checkGamepadsStatus = function () {
  62086. var _this = this;
  62087. // Hack to be compatible Chrome
  62088. this._updateGamepadObjects();
  62089. for (var i in this._babylonGamepads) {
  62090. var gamepad = this._babylonGamepads[i];
  62091. if (!gamepad || !gamepad.isConnected) {
  62092. continue;
  62093. }
  62094. gamepad.update();
  62095. }
  62096. if (this._isMonitoring && !this._scene) {
  62097. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62098. }
  62099. };
  62100. // This function is called only on Chrome, which does not properly support
  62101. // connection/disconnection events and forces you to recopy again the gamepad object
  62102. GamepadManager.prototype._updateGamepadObjects = function () {
  62103. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62104. for (var i = 0; i < gamepads.length; i++) {
  62105. if (gamepads[i]) {
  62106. if (!this._babylonGamepads[gamepads[i].index]) {
  62107. var newGamepad = this._addNewGamepad(gamepads[i]);
  62108. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62109. }
  62110. else {
  62111. // Forced to copy again this object for Chrome for unknown reason
  62112. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62113. if (!this._babylonGamepads[i].isConnected) {
  62114. this._babylonGamepads[i]._isConnected = true;
  62115. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62116. }
  62117. }
  62118. }
  62119. }
  62120. };
  62121. return GamepadManager;
  62122. }());
  62123. BABYLON.GamepadManager = GamepadManager;
  62124. })(BABYLON || (BABYLON = {}));
  62125. //# sourceMappingURL=babylon.gamepadManager.js.map
  62126. var BABYLON;
  62127. (function (BABYLON) {
  62128. var StickValues = /** @class */ (function () {
  62129. function StickValues(x, y) {
  62130. this.x = x;
  62131. this.y = y;
  62132. }
  62133. return StickValues;
  62134. }());
  62135. BABYLON.StickValues = StickValues;
  62136. var Gamepad = /** @class */ (function () {
  62137. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62138. if (leftStickX === void 0) { leftStickX = 0; }
  62139. if (leftStickY === void 0) { leftStickY = 1; }
  62140. if (rightStickX === void 0) { rightStickX = 2; }
  62141. if (rightStickY === void 0) { rightStickY = 3; }
  62142. this.id = id;
  62143. this.index = index;
  62144. this.browserGamepad = browserGamepad;
  62145. this._isConnected = true;
  62146. this._invertLeftStickY = false;
  62147. this.type = Gamepad.GAMEPAD;
  62148. this._leftStickAxisX = leftStickX;
  62149. this._leftStickAxisY = leftStickY;
  62150. this._rightStickAxisX = rightStickX;
  62151. this._rightStickAxisY = rightStickY;
  62152. if (this.browserGamepad.axes.length >= 2) {
  62153. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62154. }
  62155. if (this.browserGamepad.axes.length >= 4) {
  62156. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62157. }
  62158. }
  62159. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62160. get: function () {
  62161. return this._isConnected;
  62162. },
  62163. enumerable: true,
  62164. configurable: true
  62165. });
  62166. Gamepad.prototype.onleftstickchanged = function (callback) {
  62167. this._onleftstickchanged = callback;
  62168. };
  62169. Gamepad.prototype.onrightstickchanged = function (callback) {
  62170. this._onrightstickchanged = callback;
  62171. };
  62172. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62173. get: function () {
  62174. return this._leftStick;
  62175. },
  62176. set: function (newValues) {
  62177. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62178. this._onleftstickchanged(newValues);
  62179. }
  62180. this._leftStick = newValues;
  62181. },
  62182. enumerable: true,
  62183. configurable: true
  62184. });
  62185. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62186. get: function () {
  62187. return this._rightStick;
  62188. },
  62189. set: function (newValues) {
  62190. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62191. this._onrightstickchanged(newValues);
  62192. }
  62193. this._rightStick = newValues;
  62194. },
  62195. enumerable: true,
  62196. configurable: true
  62197. });
  62198. Gamepad.prototype.update = function () {
  62199. if (this._leftStick) {
  62200. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62201. if (this._invertLeftStickY) {
  62202. this.leftStick.y *= -1;
  62203. }
  62204. }
  62205. if (this._rightStick) {
  62206. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62207. }
  62208. };
  62209. Gamepad.prototype.dispose = function () {
  62210. };
  62211. Gamepad.GAMEPAD = 0;
  62212. Gamepad.GENERIC = 1;
  62213. Gamepad.XBOX = 2;
  62214. Gamepad.POSE_ENABLED = 3;
  62215. return Gamepad;
  62216. }());
  62217. BABYLON.Gamepad = Gamepad;
  62218. var GenericPad = /** @class */ (function (_super) {
  62219. __extends(GenericPad, _super);
  62220. function GenericPad(id, index, browserGamepad) {
  62221. var _this = _super.call(this, id, index, browserGamepad) || this;
  62222. _this.onButtonDownObservable = new BABYLON.Observable();
  62223. _this.onButtonUpObservable = new BABYLON.Observable();
  62224. _this.type = Gamepad.GENERIC;
  62225. _this._buttons = new Array(browserGamepad.buttons.length);
  62226. return _this;
  62227. }
  62228. GenericPad.prototype.onbuttondown = function (callback) {
  62229. this._onbuttondown = callback;
  62230. };
  62231. GenericPad.prototype.onbuttonup = function (callback) {
  62232. this._onbuttonup = callback;
  62233. };
  62234. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62235. if (newValue !== currentValue) {
  62236. if (newValue === 1) {
  62237. if (this._onbuttondown) {
  62238. this._onbuttondown(buttonIndex);
  62239. }
  62240. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62241. }
  62242. if (newValue === 0) {
  62243. if (this._onbuttonup) {
  62244. this._onbuttonup(buttonIndex);
  62245. }
  62246. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62247. }
  62248. }
  62249. return newValue;
  62250. };
  62251. GenericPad.prototype.update = function () {
  62252. _super.prototype.update.call(this);
  62253. for (var index = 0; index < this._buttons.length; index++) {
  62254. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62255. }
  62256. };
  62257. GenericPad.prototype.dispose = function () {
  62258. _super.prototype.dispose.call(this);
  62259. this.onButtonDownObservable.clear();
  62260. this.onButtonUpObservable.clear();
  62261. };
  62262. return GenericPad;
  62263. }(Gamepad));
  62264. BABYLON.GenericPad = GenericPad;
  62265. })(BABYLON || (BABYLON = {}));
  62266. //# sourceMappingURL=babylon.gamepad.js.map
  62267. var BABYLON;
  62268. (function (BABYLON) {
  62269. var Xbox360Button;
  62270. (function (Xbox360Button) {
  62271. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62272. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62273. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62274. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62275. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62276. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62277. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62278. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62279. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62280. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62281. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62282. var Xbox360Dpad;
  62283. (function (Xbox360Dpad) {
  62284. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62285. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62286. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62287. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62288. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62289. var Xbox360Pad = /** @class */ (function (_super) {
  62290. __extends(Xbox360Pad, _super);
  62291. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62292. if (xboxOne === void 0) { xboxOne = false; }
  62293. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62294. _this._leftTrigger = 0;
  62295. _this._rightTrigger = 0;
  62296. _this.onButtonDownObservable = new BABYLON.Observable();
  62297. _this.onButtonUpObservable = new BABYLON.Observable();
  62298. _this.onPadDownObservable = new BABYLON.Observable();
  62299. _this.onPadUpObservable = new BABYLON.Observable();
  62300. _this._buttonA = 0;
  62301. _this._buttonB = 0;
  62302. _this._buttonX = 0;
  62303. _this._buttonY = 0;
  62304. _this._buttonBack = 0;
  62305. _this._buttonStart = 0;
  62306. _this._buttonLB = 0;
  62307. _this._buttonRB = 0;
  62308. _this._buttonLeftStick = 0;
  62309. _this._buttonRightStick = 0;
  62310. _this._dPadUp = 0;
  62311. _this._dPadDown = 0;
  62312. _this._dPadLeft = 0;
  62313. _this._dPadRight = 0;
  62314. _this._isXboxOnePad = false;
  62315. _this.type = BABYLON.Gamepad.XBOX;
  62316. _this._isXboxOnePad = xboxOne;
  62317. return _this;
  62318. }
  62319. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62320. this._onlefttriggerchanged = callback;
  62321. };
  62322. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62323. this._onrighttriggerchanged = callback;
  62324. };
  62325. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62326. get: function () {
  62327. return this._leftTrigger;
  62328. },
  62329. set: function (newValue) {
  62330. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62331. this._onlefttriggerchanged(newValue);
  62332. }
  62333. this._leftTrigger = newValue;
  62334. },
  62335. enumerable: true,
  62336. configurable: true
  62337. });
  62338. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62339. get: function () {
  62340. return this._rightTrigger;
  62341. },
  62342. set: function (newValue) {
  62343. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  62344. this._onrighttriggerchanged(newValue);
  62345. }
  62346. this._rightTrigger = newValue;
  62347. },
  62348. enumerable: true,
  62349. configurable: true
  62350. });
  62351. Xbox360Pad.prototype.onbuttondown = function (callback) {
  62352. this._onbuttondown = callback;
  62353. };
  62354. Xbox360Pad.prototype.onbuttonup = function (callback) {
  62355. this._onbuttonup = callback;
  62356. };
  62357. Xbox360Pad.prototype.ondpaddown = function (callback) {
  62358. this._ondpaddown = callback;
  62359. };
  62360. Xbox360Pad.prototype.ondpadup = function (callback) {
  62361. this._ondpadup = callback;
  62362. };
  62363. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  62364. if (newValue !== currentValue) {
  62365. if (newValue === 1) {
  62366. if (this._onbuttondown) {
  62367. this._onbuttondown(buttonType);
  62368. }
  62369. this.onButtonDownObservable.notifyObservers(buttonType);
  62370. }
  62371. if (newValue === 0) {
  62372. if (this._onbuttonup) {
  62373. this._onbuttonup(buttonType);
  62374. }
  62375. this.onButtonUpObservable.notifyObservers(buttonType);
  62376. }
  62377. }
  62378. return newValue;
  62379. };
  62380. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  62381. if (newValue !== currentValue) {
  62382. if (newValue === 1) {
  62383. if (this._ondpaddown) {
  62384. this._ondpaddown(buttonType);
  62385. }
  62386. this.onPadDownObservable.notifyObservers(buttonType);
  62387. }
  62388. if (newValue === 0) {
  62389. if (this._ondpadup) {
  62390. this._ondpadup(buttonType);
  62391. }
  62392. this.onPadUpObservable.notifyObservers(buttonType);
  62393. }
  62394. }
  62395. return newValue;
  62396. };
  62397. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  62398. get: function () {
  62399. return this._buttonA;
  62400. },
  62401. set: function (value) {
  62402. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  62403. },
  62404. enumerable: true,
  62405. configurable: true
  62406. });
  62407. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  62408. get: function () {
  62409. return this._buttonB;
  62410. },
  62411. set: function (value) {
  62412. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  62413. },
  62414. enumerable: true,
  62415. configurable: true
  62416. });
  62417. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  62418. get: function () {
  62419. return this._buttonX;
  62420. },
  62421. set: function (value) {
  62422. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  62423. },
  62424. enumerable: true,
  62425. configurable: true
  62426. });
  62427. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  62428. get: function () {
  62429. return this._buttonY;
  62430. },
  62431. set: function (value) {
  62432. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  62433. },
  62434. enumerable: true,
  62435. configurable: true
  62436. });
  62437. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  62438. get: function () {
  62439. return this._buttonStart;
  62440. },
  62441. set: function (value) {
  62442. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  62443. },
  62444. enumerable: true,
  62445. configurable: true
  62446. });
  62447. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  62448. get: function () {
  62449. return this._buttonBack;
  62450. },
  62451. set: function (value) {
  62452. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  62453. },
  62454. enumerable: true,
  62455. configurable: true
  62456. });
  62457. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  62458. get: function () {
  62459. return this._buttonLB;
  62460. },
  62461. set: function (value) {
  62462. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  62463. },
  62464. enumerable: true,
  62465. configurable: true
  62466. });
  62467. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  62468. get: function () {
  62469. return this._buttonRB;
  62470. },
  62471. set: function (value) {
  62472. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  62473. },
  62474. enumerable: true,
  62475. configurable: true
  62476. });
  62477. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  62478. get: function () {
  62479. return this._buttonLeftStick;
  62480. },
  62481. set: function (value) {
  62482. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  62483. },
  62484. enumerable: true,
  62485. configurable: true
  62486. });
  62487. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  62488. get: function () {
  62489. return this._buttonRightStick;
  62490. },
  62491. set: function (value) {
  62492. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  62493. },
  62494. enumerable: true,
  62495. configurable: true
  62496. });
  62497. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  62498. get: function () {
  62499. return this._dPadUp;
  62500. },
  62501. set: function (value) {
  62502. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  62503. },
  62504. enumerable: true,
  62505. configurable: true
  62506. });
  62507. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  62508. get: function () {
  62509. return this._dPadDown;
  62510. },
  62511. set: function (value) {
  62512. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  62513. },
  62514. enumerable: true,
  62515. configurable: true
  62516. });
  62517. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  62518. get: function () {
  62519. return this._dPadLeft;
  62520. },
  62521. set: function (value) {
  62522. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  62523. },
  62524. enumerable: true,
  62525. configurable: true
  62526. });
  62527. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  62528. get: function () {
  62529. return this._dPadRight;
  62530. },
  62531. set: function (value) {
  62532. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  62533. },
  62534. enumerable: true,
  62535. configurable: true
  62536. });
  62537. Xbox360Pad.prototype.update = function () {
  62538. _super.prototype.update.call(this);
  62539. if (this._isXboxOnePad) {
  62540. this.buttonA = this.browserGamepad.buttons[0].value;
  62541. this.buttonB = this.browserGamepad.buttons[1].value;
  62542. this.buttonX = this.browserGamepad.buttons[2].value;
  62543. this.buttonY = this.browserGamepad.buttons[3].value;
  62544. this.buttonLB = this.browserGamepad.buttons[4].value;
  62545. this.buttonRB = this.browserGamepad.buttons[5].value;
  62546. this.leftTrigger = this.browserGamepad.axes[2];
  62547. this.rightTrigger = this.browserGamepad.axes[5];
  62548. this.buttonBack = this.browserGamepad.buttons[9].value;
  62549. this.buttonStart = this.browserGamepad.buttons[8].value;
  62550. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  62551. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  62552. this.dPadUp = this.browserGamepad.buttons[11].value;
  62553. this.dPadDown = this.browserGamepad.buttons[12].value;
  62554. this.dPadLeft = this.browserGamepad.buttons[13].value;
  62555. this.dPadRight = this.browserGamepad.buttons[14].value;
  62556. }
  62557. else {
  62558. this.buttonA = this.browserGamepad.buttons[0].value;
  62559. this.buttonB = this.browserGamepad.buttons[1].value;
  62560. this.buttonX = this.browserGamepad.buttons[2].value;
  62561. this.buttonY = this.browserGamepad.buttons[3].value;
  62562. this.buttonLB = this.browserGamepad.buttons[4].value;
  62563. this.buttonRB = this.browserGamepad.buttons[5].value;
  62564. this.leftTrigger = this.browserGamepad.buttons[6].value;
  62565. this.rightTrigger = this.browserGamepad.buttons[7].value;
  62566. this.buttonBack = this.browserGamepad.buttons[8].value;
  62567. this.buttonStart = this.browserGamepad.buttons[9].value;
  62568. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  62569. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  62570. this.dPadUp = this.browserGamepad.buttons[12].value;
  62571. this.dPadDown = this.browserGamepad.buttons[13].value;
  62572. this.dPadLeft = this.browserGamepad.buttons[14].value;
  62573. this.dPadRight = this.browserGamepad.buttons[15].value;
  62574. }
  62575. };
  62576. Xbox360Pad.prototype.dispose = function () {
  62577. _super.prototype.dispose.call(this);
  62578. this.onButtonDownObservable.clear();
  62579. this.onButtonUpObservable.clear();
  62580. this.onPadDownObservable.clear();
  62581. this.onPadUpObservable.clear();
  62582. };
  62583. return Xbox360Pad;
  62584. }(BABYLON.Gamepad));
  62585. BABYLON.Xbox360Pad = Xbox360Pad;
  62586. })(BABYLON || (BABYLON = {}));
  62587. //# sourceMappingURL=babylon.xboxGamepad.js.map
  62588. var BABYLON;
  62589. (function (BABYLON) {
  62590. var PoseEnabledControllerType;
  62591. (function (PoseEnabledControllerType) {
  62592. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  62593. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  62594. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  62595. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  62596. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  62597. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  62598. var PoseEnabledControllerHelper = /** @class */ (function () {
  62599. function PoseEnabledControllerHelper() {
  62600. }
  62601. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  62602. // Oculus Touch
  62603. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  62604. return new BABYLON.OculusTouchController(vrGamepad);
  62605. }
  62606. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  62607. return new BABYLON.WindowsMotionController(vrGamepad);
  62608. }
  62609. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  62610. return new BABYLON.ViveController(vrGamepad);
  62611. }
  62612. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  62613. return new BABYLON.GearVRController(vrGamepad);
  62614. }
  62615. else {
  62616. return new BABYLON.GenericController(vrGamepad);
  62617. }
  62618. };
  62619. return PoseEnabledControllerHelper;
  62620. }());
  62621. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  62622. var PoseEnabledController = /** @class */ (function (_super) {
  62623. __extends(PoseEnabledController, _super);
  62624. function PoseEnabledController(browserGamepad) {
  62625. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  62626. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  62627. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  62628. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  62629. // Represents device position and rotation in babylon space
  62630. _this.devicePosition = BABYLON.Vector3.Zero();
  62631. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  62632. _this.deviceScaleFactor = 1;
  62633. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  62634. _this._deviceToWorld = BABYLON.Matrix.Identity();
  62635. _this._workingMatrix = BABYLON.Matrix.Identity();
  62636. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  62637. _this.controllerType = PoseEnabledControllerType.GENERIC;
  62638. _this.position = BABYLON.Vector3.Zero();
  62639. _this.rotationQuaternion = new BABYLON.Quaternion();
  62640. _this._calculatedPosition = BABYLON.Vector3.Zero();
  62641. _this._calculatedRotation = new BABYLON.Quaternion();
  62642. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  62643. return _this;
  62644. }
  62645. PoseEnabledController.prototype.update = function () {
  62646. _super.prototype.update.call(this);
  62647. var pose = this.browserGamepad.pose;
  62648. this.updateFromDevice(pose);
  62649. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  62650. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  62651. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  62652. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  62653. if (this._mesh) {
  62654. this._mesh.position.copyFrom(this.devicePosition);
  62655. if (this._mesh.rotationQuaternion) {
  62656. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  62657. }
  62658. }
  62659. };
  62660. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  62661. if (poseData) {
  62662. this.rawPose = poseData;
  62663. if (poseData.position) {
  62664. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  62665. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  62666. this._deviceRoomPosition.z *= -1;
  62667. }
  62668. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  62669. this._calculatedPosition.addInPlace(this.position);
  62670. }
  62671. var pose = this.rawPose;
  62672. if (poseData.orientation && pose.orientation) {
  62673. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  62674. if (this._mesh) {
  62675. if (this._mesh.getScene().useRightHandedSystem) {
  62676. this._deviceRoomRotationQuaternion.z *= -1;
  62677. this._deviceRoomRotationQuaternion.w *= -1;
  62678. }
  62679. else {
  62680. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  62681. }
  62682. }
  62683. // if the camera is set, rotate to the camera's rotation
  62684. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  62685. }
  62686. }
  62687. };
  62688. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  62689. if (this._mesh) {
  62690. this._mesh.parent = null;
  62691. }
  62692. this._mesh = mesh;
  62693. if (this._poseControlledCamera) {
  62694. this._mesh.parent = this._poseControlledCamera;
  62695. }
  62696. if (!this._mesh.rotationQuaternion) {
  62697. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  62698. }
  62699. };
  62700. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  62701. this._poseControlledCamera = camera;
  62702. if (this._mesh) {
  62703. this._mesh.parent = this._poseControlledCamera;
  62704. }
  62705. };
  62706. PoseEnabledController.prototype.dispose = function () {
  62707. if (this._mesh) {
  62708. this._mesh.dispose();
  62709. }
  62710. this._mesh = null;
  62711. _super.prototype.dispose.call(this);
  62712. };
  62713. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  62714. get: function () {
  62715. return this._mesh;
  62716. },
  62717. enumerable: true,
  62718. configurable: true
  62719. });
  62720. PoseEnabledController.prototype.getForwardRay = function (length) {
  62721. if (length === void 0) { length = 100; }
  62722. if (!this.mesh) {
  62723. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  62724. }
  62725. var m = this.mesh.getWorldMatrix();
  62726. var origin = m.getTranslation();
  62727. var forward = new BABYLON.Vector3(0, 0, -1);
  62728. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  62729. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  62730. return new BABYLON.Ray(origin, direction, length);
  62731. };
  62732. return PoseEnabledController;
  62733. }(BABYLON.Gamepad));
  62734. BABYLON.PoseEnabledController = PoseEnabledController;
  62735. })(BABYLON || (BABYLON = {}));
  62736. //# sourceMappingURL=babylon.poseEnabledController.js.map
  62737. var BABYLON;
  62738. (function (BABYLON) {
  62739. var WebVRController = /** @class */ (function (_super) {
  62740. __extends(WebVRController, _super);
  62741. function WebVRController(vrGamepad) {
  62742. var _this = _super.call(this, vrGamepad) || this;
  62743. // Observables
  62744. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  62745. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  62746. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  62747. _this.onPadStateChangedObservable = new BABYLON.Observable();
  62748. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  62749. _this.pad = { x: 0, y: 0 };
  62750. // avoid GC, store state in a tmp object
  62751. _this._changes = {
  62752. pressChanged: false,
  62753. touchChanged: false,
  62754. valueChanged: false,
  62755. changed: false
  62756. };
  62757. _this._buttons = new Array(vrGamepad.buttons.length);
  62758. _this.hand = vrGamepad.hand;
  62759. return _this;
  62760. }
  62761. WebVRController.prototype.onButtonStateChange = function (callback) {
  62762. this._onButtonStateChange = callback;
  62763. };
  62764. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  62765. get: function () {
  62766. return this._defaultModel;
  62767. },
  62768. enumerable: true,
  62769. configurable: true
  62770. });
  62771. WebVRController.prototype.update = function () {
  62772. _super.prototype.update.call(this);
  62773. for (var index = 0; index < this._buttons.length; index++) {
  62774. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  62775. }
  62776. ;
  62777. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  62778. this.pad.x = this.leftStick.x;
  62779. this.pad.y = this.leftStick.y;
  62780. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  62781. }
  62782. };
  62783. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  62784. if (!newState) {
  62785. newState = {
  62786. pressed: false,
  62787. touched: false,
  62788. value: 0
  62789. };
  62790. }
  62791. if (!currentState) {
  62792. this._buttons[buttonIndex] = {
  62793. pressed: newState.pressed,
  62794. touched: newState.touched,
  62795. value: newState.value
  62796. };
  62797. return;
  62798. }
  62799. this._checkChanges(newState, currentState);
  62800. if (this._changes.changed) {
  62801. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  62802. this.handleButtonChange(buttonIndex, newState, this._changes);
  62803. }
  62804. this._buttons[buttonIndex].pressed = newState.pressed;
  62805. this._buttons[buttonIndex].touched = newState.touched;
  62806. // oculus triggers are never 0, thou not touched.
  62807. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  62808. };
  62809. WebVRController.prototype._checkChanges = function (newState, currentState) {
  62810. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  62811. this._changes.touchChanged = newState.touched !== currentState.touched;
  62812. this._changes.valueChanged = newState.value !== currentState.value;
  62813. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  62814. return this._changes;
  62815. };
  62816. WebVRController.prototype.dispose = function () {
  62817. _super.prototype.dispose.call(this);
  62818. this.onTriggerStateChangedObservable.clear();
  62819. this.onMainButtonStateChangedObservable.clear();
  62820. this.onSecondaryButtonStateChangedObservable.clear();
  62821. this.onPadStateChangedObservable.clear();
  62822. this.onPadValuesChangedObservable.clear();
  62823. };
  62824. return WebVRController;
  62825. }(BABYLON.PoseEnabledController));
  62826. BABYLON.WebVRController = WebVRController;
  62827. })(BABYLON || (BABYLON = {}));
  62828. //# sourceMappingURL=babylon.webVRController.js.map
  62829. var BABYLON;
  62830. (function (BABYLON) {
  62831. var OculusTouchController = /** @class */ (function (_super) {
  62832. __extends(OculusTouchController, _super);
  62833. function OculusTouchController(vrGamepad) {
  62834. var _this = _super.call(this, vrGamepad) || this;
  62835. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  62836. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  62837. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  62838. return _this;
  62839. }
  62840. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62841. var _this = this;
  62842. var meshName;
  62843. // Hand
  62844. if (this.hand === 'left') {
  62845. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  62846. }
  62847. else {
  62848. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  62849. }
  62850. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  62851. /*
  62852. Parent Mesh name: oculus_touch_left
  62853. - body
  62854. - trigger
  62855. - thumbstick
  62856. - grip
  62857. - button_y
  62858. - button_x
  62859. - button_enter
  62860. */
  62861. _this._defaultModel = newMeshes[1];
  62862. _this.attachToMesh(_this._defaultModel);
  62863. if (meshLoaded) {
  62864. meshLoaded(_this._defaultModel);
  62865. }
  62866. });
  62867. };
  62868. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  62869. // helper getters for left and right hand.
  62870. get: function () {
  62871. if (this.hand === 'right') {
  62872. return this.onMainButtonStateChangedObservable;
  62873. }
  62874. else {
  62875. throw new Error('No A button on left hand');
  62876. }
  62877. },
  62878. enumerable: true,
  62879. configurable: true
  62880. });
  62881. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  62882. get: function () {
  62883. if (this.hand === 'right') {
  62884. return this.onSecondaryButtonStateChangedObservable;
  62885. }
  62886. else {
  62887. throw new Error('No B button on left hand');
  62888. }
  62889. },
  62890. enumerable: true,
  62891. configurable: true
  62892. });
  62893. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  62894. get: function () {
  62895. if (this.hand === 'left') {
  62896. return this.onMainButtonStateChangedObservable;
  62897. }
  62898. else {
  62899. throw new Error('No X button on right hand');
  62900. }
  62901. },
  62902. enumerable: true,
  62903. configurable: true
  62904. });
  62905. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  62906. get: function () {
  62907. if (this.hand === 'left') {
  62908. return this.onSecondaryButtonStateChangedObservable;
  62909. }
  62910. else {
  62911. throw new Error('No Y button on right hand');
  62912. }
  62913. },
  62914. enumerable: true,
  62915. configurable: true
  62916. });
  62917. /*
  62918. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  62919. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  62920. 2) secondary trigger (same)
  62921. 3) A (right) X (left), touch, pressed = value
  62922. 4) B / Y
  62923. 5) thumb rest
  62924. */
  62925. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62926. var notifyObject = state; //{ state: state, changes: changes };
  62927. var triggerDirection = this.hand === 'right' ? -1 : 1;
  62928. switch (buttonIdx) {
  62929. case 0:
  62930. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  62931. return;
  62932. case 1:// index trigger
  62933. if (this._defaultModel) {
  62934. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  62935. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  62936. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  62937. }
  62938. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  62939. return;
  62940. case 2:// secondary trigger
  62941. if (this._defaultModel) {
  62942. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  62943. }
  62944. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  62945. return;
  62946. case 3:
  62947. if (this._defaultModel) {
  62948. if (notifyObject.pressed) {
  62949. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  62950. }
  62951. else {
  62952. (this._defaultModel.getChildren()[1]).position.y = 0;
  62953. }
  62954. }
  62955. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  62956. return;
  62957. case 4:
  62958. if (this._defaultModel) {
  62959. if (notifyObject.pressed) {
  62960. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  62961. }
  62962. else {
  62963. (this._defaultModel.getChildren()[2]).position.y = 0;
  62964. }
  62965. }
  62966. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  62967. return;
  62968. case 5:
  62969. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  62970. return;
  62971. }
  62972. };
  62973. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  62974. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  62975. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  62976. return OculusTouchController;
  62977. }(BABYLON.WebVRController));
  62978. BABYLON.OculusTouchController = OculusTouchController;
  62979. })(BABYLON || (BABYLON = {}));
  62980. //# sourceMappingURL=babylon.oculusTouchController.js.map
  62981. var BABYLON;
  62982. (function (BABYLON) {
  62983. var ViveController = /** @class */ (function (_super) {
  62984. __extends(ViveController, _super);
  62985. function ViveController(vrGamepad) {
  62986. var _this = _super.call(this, vrGamepad) || this;
  62987. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  62988. _this._invertLeftStickY = true;
  62989. return _this;
  62990. }
  62991. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62992. var _this = this;
  62993. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  62994. /*
  62995. Parent Mesh name: ViveWand
  62996. - body
  62997. - r_gripper
  62998. - l_gripper
  62999. - menu_button
  63000. - system_button
  63001. - trackpad
  63002. - trigger
  63003. - LED
  63004. */
  63005. _this._defaultModel = newMeshes[1];
  63006. _this.attachToMesh(_this._defaultModel);
  63007. if (meshLoaded) {
  63008. meshLoaded(_this._defaultModel);
  63009. }
  63010. });
  63011. };
  63012. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63013. get: function () {
  63014. return this.onMainButtonStateChangedObservable;
  63015. },
  63016. enumerable: true,
  63017. configurable: true
  63018. });
  63019. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63020. get: function () {
  63021. return this.onMainButtonStateChangedObservable;
  63022. },
  63023. enumerable: true,
  63024. configurable: true
  63025. });
  63026. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63027. get: function () {
  63028. return this.onSecondaryButtonStateChangedObservable;
  63029. },
  63030. enumerable: true,
  63031. configurable: true
  63032. });
  63033. /**
  63034. * Vive mapping:
  63035. * 0: touchpad
  63036. * 1: trigger
  63037. * 2: left AND right buttons
  63038. * 3: menu button
  63039. */
  63040. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63041. var notifyObject = state; //{ state: state, changes: changes };
  63042. switch (buttonIdx) {
  63043. case 0:
  63044. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63045. return;
  63046. case 1:// index trigger
  63047. if (this._defaultModel) {
  63048. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63049. }
  63050. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63051. return;
  63052. case 2:// left AND right button
  63053. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63054. return;
  63055. case 3:
  63056. if (this._defaultModel) {
  63057. if (notifyObject.pressed) {
  63058. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63059. }
  63060. else {
  63061. (this._defaultModel.getChildren()[2]).position.y = 0;
  63062. }
  63063. }
  63064. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63065. return;
  63066. }
  63067. };
  63068. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63069. ViveController.MODEL_FILENAME = 'wand.babylon';
  63070. return ViveController;
  63071. }(BABYLON.WebVRController));
  63072. BABYLON.ViveController = ViveController;
  63073. })(BABYLON || (BABYLON = {}));
  63074. //# sourceMappingURL=babylon.viveController.js.map
  63075. var BABYLON;
  63076. (function (BABYLON) {
  63077. var GenericController = /** @class */ (function (_super) {
  63078. __extends(GenericController, _super);
  63079. function GenericController(vrGamepad) {
  63080. return _super.call(this, vrGamepad) || this;
  63081. }
  63082. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63083. var _this = this;
  63084. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63085. _this._defaultModel = newMeshes[1];
  63086. _this.attachToMesh(_this._defaultModel);
  63087. if (meshLoaded) {
  63088. meshLoaded(_this._defaultModel);
  63089. }
  63090. });
  63091. };
  63092. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63093. console.log("Button id: " + buttonIdx + "state: ");
  63094. console.dir(state);
  63095. };
  63096. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63097. GenericController.MODEL_FILENAME = 'generic.babylon';
  63098. return GenericController;
  63099. }(BABYLON.WebVRController));
  63100. BABYLON.GenericController = GenericController;
  63101. })(BABYLON || (BABYLON = {}));
  63102. //# sourceMappingURL=babylon.genericController.js.map
  63103. var BABYLON;
  63104. (function (BABYLON) {
  63105. var LoadedMeshInfo = /** @class */ (function () {
  63106. function LoadedMeshInfo() {
  63107. this.buttonMeshes = {};
  63108. this.axisMeshes = {};
  63109. }
  63110. return LoadedMeshInfo;
  63111. }());
  63112. var WindowsMotionController = /** @class */ (function (_super) {
  63113. __extends(WindowsMotionController, _super);
  63114. function WindowsMotionController(vrGamepad) {
  63115. var _this = _super.call(this, vrGamepad) || this;
  63116. _this._mapping = {
  63117. // Semantic button names
  63118. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63119. // A mapping of the button name to glTF model node name
  63120. // that should be transformed by button value.
  63121. buttonMeshNames: {
  63122. 'trigger': 'SELECT',
  63123. 'menu': 'MENU',
  63124. 'grip': 'GRASP',
  63125. 'thumbstick': 'THUMBSTICK_PRESS',
  63126. 'trackpad': 'TOUCHPAD_PRESS'
  63127. },
  63128. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63129. buttonObservableNames: {
  63130. 'trigger': 'onTriggerStateChangedObservable',
  63131. 'menu': 'onSecondaryButtonStateChangedObservable',
  63132. 'grip': 'onMainButtonStateChangedObservable',
  63133. 'thumbstick': 'onPadStateChangedObservable',
  63134. 'trackpad': 'onTrackpadChangedObservable'
  63135. },
  63136. // A mapping of the axis name to glTF model node name
  63137. // that should be transformed by axis value.
  63138. // This array mirrors the browserGamepad.axes array, such that
  63139. // the mesh corresponding to axis 0 is in this array index 0.
  63140. axisMeshNames: [
  63141. 'THUMBSTICK_X',
  63142. 'THUMBSTICK_Y',
  63143. 'TOUCHPAD_TOUCH_X',
  63144. 'TOUCHPAD_TOUCH_Y'
  63145. ],
  63146. pointingPoseMeshName: 'POINTING_POSE'
  63147. };
  63148. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63149. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63150. _this.trackpad = { x: 0, y: 0 };
  63151. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63152. _this._loadedMeshInfo = null;
  63153. return _this;
  63154. }
  63155. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63156. get: function () {
  63157. return this.onTriggerStateChangedObservable;
  63158. },
  63159. enumerable: true,
  63160. configurable: true
  63161. });
  63162. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63163. get: function () {
  63164. return this.onSecondaryButtonStateChangedObservable;
  63165. },
  63166. enumerable: true,
  63167. configurable: true
  63168. });
  63169. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63170. get: function () {
  63171. return this.onMainButtonStateChangedObservable;
  63172. },
  63173. enumerable: true,
  63174. configurable: true
  63175. });
  63176. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63177. get: function () {
  63178. return this.onPadStateChangedObservable;
  63179. },
  63180. enumerable: true,
  63181. configurable: true
  63182. });
  63183. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63184. get: function () {
  63185. return this.onTrackpadChangedObservable;
  63186. },
  63187. enumerable: true,
  63188. configurable: true
  63189. });
  63190. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63191. get: function () {
  63192. return this.onTrackpadValuesChangedObservable;
  63193. },
  63194. enumerable: true,
  63195. configurable: true
  63196. });
  63197. /**
  63198. * Called once per frame by the engine.
  63199. */
  63200. WindowsMotionController.prototype.update = function () {
  63201. _super.prototype.update.call(this);
  63202. // Only need to animate axes if there is a loaded mesh
  63203. if (this._loadedMeshInfo) {
  63204. if (this.browserGamepad.axes) {
  63205. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63206. this.trackpad.x = this.browserGamepad["axes"][2];
  63207. this.trackpad.y = this.browserGamepad["axes"][3];
  63208. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63209. }
  63210. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63211. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63212. }
  63213. }
  63214. }
  63215. };
  63216. /**
  63217. * Called once for each button that changed state since the last frame
  63218. * @param buttonIdx Which button index changed
  63219. * @param state New state of the button
  63220. * @param changes Which properties on the state changed since last frame
  63221. */
  63222. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63223. var buttonName = this._mapping.buttons[buttonIdx];
  63224. if (!buttonName) {
  63225. return;
  63226. }
  63227. // Only emit events for buttons that we know how to map from index to name
  63228. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63229. if (observable) {
  63230. observable.notifyObservers(state);
  63231. }
  63232. this.lerpButtonTransform(buttonName, state.value);
  63233. };
  63234. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63235. // If there is no loaded mesh, there is nothing to transform.
  63236. if (!this._loadedMeshInfo) {
  63237. return;
  63238. }
  63239. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63240. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63241. return;
  63242. }
  63243. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63244. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63245. };
  63246. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63247. if (!this._loadedMeshInfo) {
  63248. return;
  63249. }
  63250. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63251. if (!meshInfo) {
  63252. return;
  63253. }
  63254. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63255. return;
  63256. }
  63257. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63258. var lerpValue = axisValue * 0.5 + 0.5;
  63259. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63260. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63261. };
  63262. /**
  63263. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63264. * @param scene scene in which to add meshes
  63265. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63266. */
  63267. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63268. var _this = this;
  63269. if (forceDefault === void 0) { forceDefault = false; }
  63270. var path;
  63271. var filename;
  63272. // Checking if GLB loader is present
  63273. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63274. // Determine the device specific folder based on the ID suffix
  63275. var device = 'default';
  63276. if (this.id && !forceDefault) {
  63277. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63278. device = ((match && match[0]) || device);
  63279. }
  63280. // Hand
  63281. if (this.hand === 'left') {
  63282. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63283. }
  63284. else {
  63285. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63286. }
  63287. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63288. }
  63289. else {
  63290. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63291. path = BABYLON.GenericController.MODEL_BASE_URL;
  63292. filename = BABYLON.GenericController.MODEL_FILENAME;
  63293. }
  63294. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63295. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63296. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63297. if (!_this._loadedMeshInfo) {
  63298. return;
  63299. }
  63300. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63301. _this.attachToMesh(_this._defaultModel);
  63302. if (meshLoaded) {
  63303. meshLoaded(_this._defaultModel);
  63304. }
  63305. }, null, function (scene, message) {
  63306. BABYLON.Tools.Log(message);
  63307. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63308. if (!forceDefault) {
  63309. _this.initControllerMesh(scene, meshLoaded, true);
  63310. }
  63311. });
  63312. };
  63313. /**
  63314. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63315. * can be transformed by button presses and axes values, based on this._mapping.
  63316. *
  63317. * @param scene scene in which the meshes exist
  63318. * @param meshes list of meshes that make up the controller model to process
  63319. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63320. */
  63321. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63322. var loadedMeshInfo = null;
  63323. // Create a new mesh to contain the glTF hierarchy
  63324. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63325. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63326. var childMesh = null;
  63327. for (var i = 0; i < meshes.length; i++) {
  63328. var mesh = meshes[i];
  63329. if (!mesh.parent) {
  63330. // Exclude controller meshes from picking results
  63331. mesh.isPickable = false;
  63332. // Handle root node, attach to the new parentMesh
  63333. childMesh = mesh;
  63334. break;
  63335. }
  63336. }
  63337. if (childMesh) {
  63338. childMesh.setParent(parentMesh);
  63339. // Create our mesh info. Note that this method will always return non-null.
  63340. loadedMeshInfo = this.createMeshInfo(parentMesh);
  63341. }
  63342. else {
  63343. BABYLON.Tools.Warn('Could not find root node in model file.');
  63344. }
  63345. return loadedMeshInfo;
  63346. };
  63347. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  63348. var loadedMeshInfo = new LoadedMeshInfo();
  63349. var i;
  63350. loadedMeshInfo.rootNode = rootNode;
  63351. // Reset the caches
  63352. loadedMeshInfo.buttonMeshes = {};
  63353. loadedMeshInfo.axisMeshes = {};
  63354. // Button Meshes
  63355. for (i = 0; i < this._mapping.buttons.length; i++) {
  63356. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  63357. if (!buttonMeshName) {
  63358. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  63359. continue;
  63360. }
  63361. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  63362. if (!buttonMesh) {
  63363. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  63364. continue;
  63365. }
  63366. var buttonMeshInfo = {
  63367. index: i,
  63368. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  63369. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  63370. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  63371. };
  63372. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  63373. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  63374. }
  63375. else {
  63376. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  63377. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  63378. '(VALUE: ' + !!buttonMeshInfo.value +
  63379. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  63380. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  63381. ')');
  63382. }
  63383. }
  63384. // Axis Meshes
  63385. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  63386. var axisMeshName = this._mapping.axisMeshNames[i];
  63387. if (!axisMeshName) {
  63388. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  63389. continue;
  63390. }
  63391. var axisMesh = getChildByName(rootNode, axisMeshName);
  63392. if (!axisMesh) {
  63393. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  63394. continue;
  63395. }
  63396. var axisMeshInfo = {
  63397. index: i,
  63398. value: getImmediateChildByName(axisMesh, 'VALUE'),
  63399. min: getImmediateChildByName(axisMesh, 'MIN'),
  63400. max: getImmediateChildByName(axisMesh, 'MAX')
  63401. };
  63402. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  63403. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  63404. }
  63405. else {
  63406. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  63407. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  63408. '(VALUE: ' + !!axisMeshInfo.value +
  63409. ', MIN: ' + !!axisMeshInfo.min +
  63410. ', MAX:' + !!axisMeshInfo.max +
  63411. ')');
  63412. }
  63413. }
  63414. // Pointing Ray
  63415. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  63416. if (!loadedMeshInfo.pointingPoseNode) {
  63417. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  63418. }
  63419. return loadedMeshInfo;
  63420. // Look through all children recursively. This will return null if no mesh exists with the given name.
  63421. function getChildByName(node, name) {
  63422. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  63423. }
  63424. // Look through only immediate children. This will return null if no mesh exists with the given name.
  63425. function getImmediateChildByName(node, name) {
  63426. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  63427. }
  63428. };
  63429. WindowsMotionController.prototype.getForwardRay = function (length) {
  63430. if (length === void 0) { length = 100; }
  63431. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  63432. return _super.prototype.getForwardRay.call(this, length);
  63433. }
  63434. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  63435. var origin = m.getTranslation();
  63436. var forward = new BABYLON.Vector3(0, 0, -1);
  63437. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63438. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63439. return new BABYLON.Ray(origin, direction, length);
  63440. };
  63441. WindowsMotionController.prototype.dispose = function () {
  63442. _super.prototype.dispose.call(this);
  63443. this.onTrackpadChangedObservable.clear();
  63444. };
  63445. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  63446. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  63447. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  63448. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  63449. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  63450. return WindowsMotionController;
  63451. }(BABYLON.WebVRController));
  63452. BABYLON.WindowsMotionController = WindowsMotionController;
  63453. })(BABYLON || (BABYLON = {}));
  63454. //# sourceMappingURL=babylon.windowsMotionController.js.map
  63455. var BABYLON;
  63456. (function (BABYLON) {
  63457. var GearVRController = /** @class */ (function (_super) {
  63458. __extends(GearVRController, _super);
  63459. function GearVRController(vrGamepad) {
  63460. var _this = _super.call(this, vrGamepad) || this;
  63461. _this._buttonIndexToObservableNameMap = [
  63462. 'onTrackpadChangedObservable',
  63463. 'onTriggerStateChangedObservable' // Trigger
  63464. ];
  63465. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  63466. return _this;
  63467. }
  63468. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63469. var _this = this;
  63470. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  63471. _this._defaultModel = newMeshes[1];
  63472. _this.attachToMesh(_this._defaultModel);
  63473. if (meshLoaded) {
  63474. meshLoaded(_this._defaultModel);
  63475. }
  63476. });
  63477. };
  63478. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63479. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  63480. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  63481. // Only emit events for buttons that we know how to map from index to observable
  63482. var observable = this[observableName];
  63483. if (observable) {
  63484. observable.notifyObservers(state);
  63485. }
  63486. }
  63487. };
  63488. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63489. GearVRController.MODEL_FILENAME = 'generic.babylon';
  63490. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  63491. return GearVRController;
  63492. }(BABYLON.WebVRController));
  63493. BABYLON.GearVRController = GearVRController;
  63494. })(BABYLON || (BABYLON = {}));
  63495. //# sourceMappingURL=babylon.gearVRController.js.map
  63496. var BABYLON;
  63497. (function (BABYLON) {
  63498. var FollowCamera = /** @class */ (function (_super) {
  63499. __extends(FollowCamera, _super);
  63500. function FollowCamera(name, position, scene, lockedTarget) {
  63501. if (lockedTarget === void 0) { lockedTarget = null; }
  63502. var _this = _super.call(this, name, position, scene) || this;
  63503. _this.radius = 12;
  63504. _this.rotationOffset = 0;
  63505. _this.heightOffset = 4;
  63506. _this.cameraAcceleration = 0.05;
  63507. _this.maxCameraSpeed = 20;
  63508. _this.lockedTarget = lockedTarget;
  63509. return _this;
  63510. }
  63511. FollowCamera.prototype.getRadians = function (degrees) {
  63512. return degrees * Math.PI / 180;
  63513. };
  63514. FollowCamera.prototype.follow = function (cameraTarget) {
  63515. if (!cameraTarget)
  63516. return;
  63517. var yRotation;
  63518. if (cameraTarget.rotationQuaternion) {
  63519. var rotMatrix = new BABYLON.Matrix();
  63520. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  63521. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  63522. }
  63523. else {
  63524. yRotation = cameraTarget.rotation.y;
  63525. }
  63526. var radians = this.getRadians(this.rotationOffset) + yRotation;
  63527. var targetPosition = cameraTarget.getAbsolutePosition();
  63528. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  63529. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  63530. var dx = targetX - this.position.x;
  63531. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  63532. var dz = (targetZ) - this.position.z;
  63533. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  63534. var vy = dy * this.cameraAcceleration;
  63535. var vz = dz * this.cameraAcceleration * 2;
  63536. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  63537. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63538. }
  63539. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  63540. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63541. }
  63542. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  63543. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63544. }
  63545. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  63546. this.setTarget(targetPosition);
  63547. };
  63548. FollowCamera.prototype._checkInputs = function () {
  63549. _super.prototype._checkInputs.call(this);
  63550. if (this.lockedTarget) {
  63551. this.follow(this.lockedTarget);
  63552. }
  63553. };
  63554. FollowCamera.prototype.getClassName = function () {
  63555. return "FollowCamera";
  63556. };
  63557. __decorate([
  63558. BABYLON.serialize()
  63559. ], FollowCamera.prototype, "radius", void 0);
  63560. __decorate([
  63561. BABYLON.serialize()
  63562. ], FollowCamera.prototype, "rotationOffset", void 0);
  63563. __decorate([
  63564. BABYLON.serialize()
  63565. ], FollowCamera.prototype, "heightOffset", void 0);
  63566. __decorate([
  63567. BABYLON.serialize()
  63568. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  63569. __decorate([
  63570. BABYLON.serialize()
  63571. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  63572. __decorate([
  63573. BABYLON.serializeAsMeshReference("lockedTargetId")
  63574. ], FollowCamera.prototype, "lockedTarget", void 0);
  63575. return FollowCamera;
  63576. }(BABYLON.TargetCamera));
  63577. BABYLON.FollowCamera = FollowCamera;
  63578. var ArcFollowCamera = /** @class */ (function (_super) {
  63579. __extends(ArcFollowCamera, _super);
  63580. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  63581. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  63582. _this.alpha = alpha;
  63583. _this.beta = beta;
  63584. _this.radius = radius;
  63585. _this.target = target;
  63586. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  63587. _this.follow();
  63588. return _this;
  63589. }
  63590. ArcFollowCamera.prototype.follow = function () {
  63591. if (!this.target) {
  63592. return;
  63593. }
  63594. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  63595. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  63596. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  63597. var targetPosition = this.target.getAbsolutePosition();
  63598. this.position = targetPosition.add(this._cartesianCoordinates);
  63599. this.setTarget(targetPosition);
  63600. };
  63601. ArcFollowCamera.prototype._checkInputs = function () {
  63602. _super.prototype._checkInputs.call(this);
  63603. this.follow();
  63604. };
  63605. ArcFollowCamera.prototype.getClassName = function () {
  63606. return "ArcFollowCamera";
  63607. };
  63608. return ArcFollowCamera;
  63609. }(BABYLON.TargetCamera));
  63610. BABYLON.ArcFollowCamera = ArcFollowCamera;
  63611. })(BABYLON || (BABYLON = {}));
  63612. //# sourceMappingURL=babylon.followCamera.js.map
  63613. var BABYLON;
  63614. (function (BABYLON) {
  63615. // We're mainly based on the logic defined into the FreeCamera code
  63616. var UniversalCamera = /** @class */ (function (_super) {
  63617. __extends(UniversalCamera, _super);
  63618. //-- end properties for backward compatibility for inputs
  63619. function UniversalCamera(name, position, scene) {
  63620. var _this = _super.call(this, name, position, scene) || this;
  63621. _this.inputs.addGamepad();
  63622. return _this;
  63623. }
  63624. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  63625. //-- Begin properties for backward compatibility for inputs
  63626. get: function () {
  63627. var gamepad = this.inputs.attached["gamepad"];
  63628. if (gamepad)
  63629. return gamepad.gamepadAngularSensibility;
  63630. return 0;
  63631. },
  63632. set: function (value) {
  63633. var gamepad = this.inputs.attached["gamepad"];
  63634. if (gamepad)
  63635. gamepad.gamepadAngularSensibility = value;
  63636. },
  63637. enumerable: true,
  63638. configurable: true
  63639. });
  63640. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  63641. get: function () {
  63642. var gamepad = this.inputs.attached["gamepad"];
  63643. if (gamepad)
  63644. return gamepad.gamepadMoveSensibility;
  63645. return 0;
  63646. },
  63647. set: function (value) {
  63648. var gamepad = this.inputs.attached["gamepad"];
  63649. if (gamepad)
  63650. gamepad.gamepadMoveSensibility = value;
  63651. },
  63652. enumerable: true,
  63653. configurable: true
  63654. });
  63655. UniversalCamera.prototype.getClassName = function () {
  63656. return "UniversalCamera";
  63657. };
  63658. return UniversalCamera;
  63659. }(BABYLON.TouchCamera));
  63660. BABYLON.UniversalCamera = UniversalCamera;
  63661. })(BABYLON || (BABYLON = {}));
  63662. //# sourceMappingURL=babylon.universalCamera.js.map
  63663. var BABYLON;
  63664. (function (BABYLON) {
  63665. // We're mainly based on the logic defined into the FreeCamera code
  63666. var GamepadCamera = /** @class */ (function (_super) {
  63667. __extends(GamepadCamera, _super);
  63668. //-- end properties for backward compatibility for inputs
  63669. function GamepadCamera(name, position, scene) {
  63670. return _super.call(this, name, position, scene) || this;
  63671. }
  63672. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  63673. //-- Begin properties for backward compatibility for inputs
  63674. get: function () {
  63675. var gamepad = this.inputs.attached["gamepad"];
  63676. if (gamepad)
  63677. return gamepad.gamepadAngularSensibility;
  63678. return 0;
  63679. },
  63680. set: function (value) {
  63681. var gamepad = this.inputs.attached["gamepad"];
  63682. if (gamepad)
  63683. gamepad.gamepadAngularSensibility = value;
  63684. },
  63685. enumerable: true,
  63686. configurable: true
  63687. });
  63688. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  63689. get: function () {
  63690. var gamepad = this.inputs.attached["gamepad"];
  63691. if (gamepad)
  63692. return gamepad.gamepadMoveSensibility;
  63693. return 0;
  63694. },
  63695. set: function (value) {
  63696. var gamepad = this.inputs.attached["gamepad"];
  63697. if (gamepad)
  63698. gamepad.gamepadMoveSensibility = value;
  63699. },
  63700. enumerable: true,
  63701. configurable: true
  63702. });
  63703. GamepadCamera.prototype.getClassName = function () {
  63704. return "GamepadCamera";
  63705. };
  63706. return GamepadCamera;
  63707. }(BABYLON.UniversalCamera));
  63708. BABYLON.GamepadCamera = GamepadCamera;
  63709. })(BABYLON || (BABYLON = {}));
  63710. //# sourceMappingURL=babylon.gamepadCamera.js.map
  63711. var BABYLON;
  63712. (function (BABYLON) {
  63713. var PostProcessRenderPipelineManager = /** @class */ (function () {
  63714. function PostProcessRenderPipelineManager() {
  63715. this._renderPipelines = {};
  63716. }
  63717. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  63718. this._renderPipelines[renderPipeline._name] = renderPipeline;
  63719. };
  63720. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  63721. if (unique === void 0) { unique = false; }
  63722. var renderPipeline = this._renderPipelines[renderPipelineName];
  63723. if (!renderPipeline) {
  63724. return;
  63725. }
  63726. renderPipeline._attachCameras(cameras, unique);
  63727. };
  63728. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  63729. var renderPipeline = this._renderPipelines[renderPipelineName];
  63730. if (!renderPipeline) {
  63731. return;
  63732. }
  63733. renderPipeline._detachCameras(cameras);
  63734. };
  63735. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  63736. var renderPipeline = this._renderPipelines[renderPipelineName];
  63737. if (!renderPipeline) {
  63738. return;
  63739. }
  63740. renderPipeline._enableEffect(renderEffectName, cameras);
  63741. };
  63742. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  63743. var renderPipeline = this._renderPipelines[renderPipelineName];
  63744. if (!renderPipeline) {
  63745. return;
  63746. }
  63747. renderPipeline._disableEffect(renderEffectName, cameras);
  63748. };
  63749. PostProcessRenderPipelineManager.prototype.update = function () {
  63750. for (var renderPipelineName in this._renderPipelines) {
  63751. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  63752. var pipeline = this._renderPipelines[renderPipelineName];
  63753. if (!pipeline.isSupported) {
  63754. pipeline.dispose();
  63755. delete this._renderPipelines[renderPipelineName];
  63756. }
  63757. else {
  63758. pipeline._update();
  63759. }
  63760. }
  63761. }
  63762. };
  63763. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  63764. for (var renderPipelineName in this._renderPipelines) {
  63765. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  63766. var pipeline = this._renderPipelines[renderPipelineName];
  63767. pipeline._rebuild();
  63768. }
  63769. }
  63770. };
  63771. PostProcessRenderPipelineManager.prototype.dispose = function () {
  63772. for (var renderPipelineName in this._renderPipelines) {
  63773. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  63774. var pipeline = this._renderPipelines[renderPipelineName];
  63775. pipeline.dispose();
  63776. }
  63777. }
  63778. };
  63779. return PostProcessRenderPipelineManager;
  63780. }());
  63781. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  63782. })(BABYLON || (BABYLON = {}));
  63783. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  63784. var BABYLON;
  63785. (function (BABYLON) {
  63786. /**
  63787. * This represents a set of one or more post processes in Babylon.
  63788. * A post process can be used to apply a shader to a texture after it is rendered.
  63789. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  63790. */
  63791. var PostProcessRenderEffect = /** @class */ (function () {
  63792. /**
  63793. * Instantiates a post process render effect.
  63794. * A post process can be used to apply a shader to a texture after it is rendered.
  63795. * @param engine The engine the effect is tied to
  63796. * @param name The name of the effect
  63797. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  63798. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  63799. */
  63800. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  63801. this._name = name;
  63802. this._singleInstance = singleInstance || true;
  63803. this._getPostProcesses = getPostProcesses;
  63804. this._cameras = {};
  63805. this._indicesForCamera = {};
  63806. this._postProcesses = {};
  63807. }
  63808. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  63809. /**
  63810. * Checks if all the post processes in the effect are supported.
  63811. */
  63812. get: function () {
  63813. for (var index in this._postProcesses) {
  63814. for (var ppIndex in this._postProcesses[index]) {
  63815. if (!this._postProcesses[index][ppIndex].isSupported) {
  63816. return false;
  63817. }
  63818. }
  63819. }
  63820. return true;
  63821. },
  63822. enumerable: true,
  63823. configurable: true
  63824. });
  63825. /**
  63826. * Updates the current state of the effect
  63827. */
  63828. PostProcessRenderEffect.prototype._update = function () {
  63829. };
  63830. /**
  63831. * Attaches the effect on cameras
  63832. * @param cameras The camera to attach to.
  63833. */
  63834. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  63835. var _this = this;
  63836. var cameraKey;
  63837. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63838. if (!cams) {
  63839. return;
  63840. }
  63841. for (var i = 0; i < cams.length; i++) {
  63842. var camera = cams[i];
  63843. var cameraName = camera.name;
  63844. if (this._singleInstance) {
  63845. cameraKey = 0;
  63846. }
  63847. else {
  63848. cameraKey = cameraName;
  63849. }
  63850. if (!this._postProcesses[cameraKey]) {
  63851. var postProcess = this._getPostProcesses();
  63852. if (postProcess) {
  63853. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  63854. }
  63855. }
  63856. if (!this._indicesForCamera[cameraName]) {
  63857. this._indicesForCamera[cameraName] = [];
  63858. }
  63859. this._postProcesses[cameraKey].forEach(function (postProcess) {
  63860. var index = camera.attachPostProcess(postProcess);
  63861. _this._indicesForCamera[cameraName].push(index);
  63862. });
  63863. if (!this._cameras[cameraName]) {
  63864. this._cameras[cameraName] = camera;
  63865. }
  63866. }
  63867. };
  63868. /**
  63869. * Detatches the effect on cameras
  63870. * @param cameras The camera to detatch from.
  63871. */
  63872. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  63873. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63874. if (!cams) {
  63875. return;
  63876. }
  63877. for (var i = 0; i < cams.length; i++) {
  63878. var camera = cams[i];
  63879. var cameraName = camera.name;
  63880. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  63881. camera.detachPostProcess(postProcess);
  63882. });
  63883. if (this._cameras[cameraName]) {
  63884. //this._indicesForCamera.splice(index, 1);
  63885. this._cameras[cameraName] = null;
  63886. }
  63887. }
  63888. };
  63889. /**
  63890. * Enables the effect on given cameras
  63891. * @param cameras The camera to enable.
  63892. */
  63893. PostProcessRenderEffect.prototype._enable = function (cameras) {
  63894. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63895. if (!cams) {
  63896. return;
  63897. }
  63898. for (var i = 0; i < cams.length; i++) {
  63899. var camera = cams[i];
  63900. var cameraName = camera.name;
  63901. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  63902. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  63903. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  63904. }
  63905. }
  63906. }
  63907. };
  63908. /**
  63909. * Disables the effect on the given cameras
  63910. * @param cameras The camera to disable.
  63911. */
  63912. PostProcessRenderEffect.prototype._disable = function (cameras) {
  63913. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63914. if (!cams) {
  63915. return;
  63916. }
  63917. for (var i = 0; i < cams.length; i++) {
  63918. var camera = cams[i];
  63919. var cameraName = camera.Name;
  63920. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  63921. }
  63922. };
  63923. /**
  63924. * Gets a list of the post processes contained in the effect.
  63925. * @param camera The camera to get the post processes on.
  63926. * @returns The list of the post processes in the effect.
  63927. */
  63928. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  63929. if (this._singleInstance) {
  63930. return this._postProcesses[0];
  63931. }
  63932. else {
  63933. if (!camera) {
  63934. return null;
  63935. }
  63936. return this._postProcesses[camera.name];
  63937. }
  63938. };
  63939. return PostProcessRenderEffect;
  63940. }());
  63941. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  63942. })(BABYLON || (BABYLON = {}));
  63943. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  63944. var BABYLON;
  63945. (function (BABYLON) {
  63946. var PostProcessRenderPipeline = /** @class */ (function () {
  63947. function PostProcessRenderPipeline(engine, name) {
  63948. this._name = name;
  63949. this._renderEffects = {};
  63950. this._renderEffectsForIsolatedPass = new Array();
  63951. this._cameras = [];
  63952. }
  63953. PostProcessRenderPipeline.prototype.getClassName = function () {
  63954. return "PostProcessRenderPipeline";
  63955. };
  63956. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  63957. get: function () {
  63958. for (var renderEffectName in this._renderEffects) {
  63959. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  63960. if (!this._renderEffects[renderEffectName].isSupported) {
  63961. return false;
  63962. }
  63963. }
  63964. }
  63965. return true;
  63966. },
  63967. enumerable: true,
  63968. configurable: true
  63969. });
  63970. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  63971. this._renderEffects[renderEffect._name] = renderEffect;
  63972. };
  63973. // private
  63974. PostProcessRenderPipeline.prototype._rebuild = function () {
  63975. };
  63976. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  63977. var renderEffects = this._renderEffects[renderEffectName];
  63978. if (!renderEffects) {
  63979. return;
  63980. }
  63981. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  63982. };
  63983. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  63984. var renderEffects = this._renderEffects[renderEffectName];
  63985. if (!renderEffects) {
  63986. return;
  63987. }
  63988. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  63989. };
  63990. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  63991. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63992. if (!cams) {
  63993. return;
  63994. }
  63995. var indicesToDelete = [];
  63996. var i;
  63997. for (i = 0; i < cams.length; i++) {
  63998. var camera = cams[i];
  63999. var cameraName = camera.name;
  64000. if (this._cameras.indexOf(camera) === -1) {
  64001. this._cameras[cameraName] = camera;
  64002. }
  64003. else if (unique) {
  64004. indicesToDelete.push(i);
  64005. }
  64006. }
  64007. for (i = 0; i < indicesToDelete.length; i++) {
  64008. cameras.splice(indicesToDelete[i], 1);
  64009. }
  64010. for (var renderEffectName in this._renderEffects) {
  64011. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64012. this._renderEffects[renderEffectName]._attachCameras(cams);
  64013. }
  64014. }
  64015. };
  64016. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64017. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64018. if (!cams) {
  64019. return;
  64020. }
  64021. for (var renderEffectName in this._renderEffects) {
  64022. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64023. this._renderEffects[renderEffectName]._detachCameras(cams);
  64024. }
  64025. }
  64026. for (var i = 0; i < cams.length; i++) {
  64027. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64028. }
  64029. };
  64030. PostProcessRenderPipeline.prototype._update = function () {
  64031. for (var renderEffectName in this._renderEffects) {
  64032. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64033. this._renderEffects[renderEffectName]._update();
  64034. }
  64035. }
  64036. for (var i = 0; i < this._cameras.length; i++) {
  64037. var cameraName = this._cameras[i].name;
  64038. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64039. this._renderEffectsForIsolatedPass[cameraName]._update();
  64040. }
  64041. }
  64042. };
  64043. PostProcessRenderPipeline.prototype._reset = function () {
  64044. this._renderEffects = {};
  64045. this._renderEffectsForIsolatedPass = new Array();
  64046. };
  64047. PostProcessRenderPipeline.prototype.dispose = function () {
  64048. // Must be implemented by children
  64049. };
  64050. __decorate([
  64051. BABYLON.serialize()
  64052. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64053. return PostProcessRenderPipeline;
  64054. }());
  64055. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64056. })(BABYLON || (BABYLON = {}));
  64057. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64058. var BABYLON;
  64059. (function (BABYLON) {
  64060. var DepthRenderer = /** @class */ (function () {
  64061. function DepthRenderer(scene, type) {
  64062. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64063. var _this = this;
  64064. this._scene = scene;
  64065. var engine = scene.getEngine();
  64066. // Render target
  64067. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64068. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64069. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64070. this._depthMap.refreshRate = 1;
  64071. this._depthMap.renderParticles = false;
  64072. this._depthMap.renderList = null;
  64073. // set default depth value to 1.0 (far away)
  64074. this._depthMap.onClearObservable.add(function (engine) {
  64075. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64076. });
  64077. // Custom render function
  64078. var renderSubMesh = function (subMesh) {
  64079. var mesh = subMesh.getRenderingMesh();
  64080. var scene = _this._scene;
  64081. var engine = scene.getEngine();
  64082. var material = subMesh.getMaterial();
  64083. if (!material) {
  64084. return;
  64085. }
  64086. // Culling and reverse (right handed system)
  64087. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64088. // Managing instances
  64089. var batch = mesh._getInstancesRenderList(subMesh._id);
  64090. if (batch.mustReturn) {
  64091. return;
  64092. }
  64093. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64094. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64095. engine.enableEffect(_this._effect);
  64096. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64097. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64098. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64099. // Alpha test
  64100. if (material && material.needAlphaTesting()) {
  64101. var alphaTexture = material.getAlphaTestTexture();
  64102. if (alphaTexture) {
  64103. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64104. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64105. }
  64106. }
  64107. // Bones
  64108. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64109. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64110. }
  64111. // Draw
  64112. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64113. }
  64114. };
  64115. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64116. var index;
  64117. if (depthOnlySubMeshes.length) {
  64118. engine.setColorWrite(false);
  64119. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64120. renderSubMesh(depthOnlySubMeshes.data[index]);
  64121. }
  64122. engine.setColorWrite(true);
  64123. }
  64124. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64125. renderSubMesh(opaqueSubMeshes.data[index]);
  64126. }
  64127. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64128. renderSubMesh(alphaTestSubMeshes.data[index]);
  64129. }
  64130. };
  64131. }
  64132. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64133. var material = subMesh.getMaterial();
  64134. if (material.disableDepthWrite) {
  64135. return false;
  64136. }
  64137. var defines = [];
  64138. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64139. var mesh = subMesh.getMesh();
  64140. // Alpha test
  64141. if (material && material.needAlphaTesting()) {
  64142. defines.push("#define ALPHATEST");
  64143. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64144. attribs.push(BABYLON.VertexBuffer.UVKind);
  64145. defines.push("#define UV1");
  64146. }
  64147. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64148. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64149. defines.push("#define UV2");
  64150. }
  64151. }
  64152. // Bones
  64153. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64154. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64155. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64156. if (mesh.numBoneInfluencers > 4) {
  64157. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64158. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64159. }
  64160. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64161. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64162. }
  64163. else {
  64164. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64165. }
  64166. // Instances
  64167. if (useInstances) {
  64168. defines.push("#define INSTANCES");
  64169. attribs.push("world0");
  64170. attribs.push("world1");
  64171. attribs.push("world2");
  64172. attribs.push("world3");
  64173. }
  64174. // Get correct effect
  64175. var join = defines.join("\n");
  64176. if (this._cachedDefines !== join) {
  64177. this._cachedDefines = join;
  64178. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64179. }
  64180. return this._effect.isReady();
  64181. };
  64182. DepthRenderer.prototype.getDepthMap = function () {
  64183. return this._depthMap;
  64184. };
  64185. // Methods
  64186. DepthRenderer.prototype.dispose = function () {
  64187. this._depthMap.dispose();
  64188. };
  64189. return DepthRenderer;
  64190. }());
  64191. BABYLON.DepthRenderer = DepthRenderer;
  64192. })(BABYLON || (BABYLON = {}));
  64193. //# sourceMappingURL=babylon.depthRenderer.js.map
  64194. var BABYLON;
  64195. (function (BABYLON) {
  64196. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64197. __extends(SSAORenderingPipeline, _super);
  64198. /**
  64199. * @constructor
  64200. * @param {string} name - The rendering pipeline name
  64201. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64202. * @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 }
  64203. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64204. */
  64205. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64206. var _this = _super.call(this, scene.getEngine(), name) || this;
  64207. // Members
  64208. /**
  64209. * The PassPostProcess id in the pipeline that contains the original scene color
  64210. * @type {string}
  64211. */
  64212. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64213. /**
  64214. * The SSAO PostProcess id in the pipeline
  64215. * @type {string}
  64216. */
  64217. _this.SSAORenderEffect = "SSAORenderEffect";
  64218. /**
  64219. * The horizontal blur PostProcess id in the pipeline
  64220. * @type {string}
  64221. */
  64222. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64223. /**
  64224. * The vertical blur PostProcess id in the pipeline
  64225. * @type {string}
  64226. */
  64227. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64228. /**
  64229. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64230. * @type {string}
  64231. */
  64232. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64233. /**
  64234. * The output strength of the SSAO post-process. Default value is 1.0.
  64235. * @type {number}
  64236. */
  64237. _this.totalStrength = 1.0;
  64238. /**
  64239. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64240. * @type {number}
  64241. */
  64242. _this.radius = 0.0001;
  64243. /**
  64244. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64245. * Must not be equal to fallOff and superior to fallOff.
  64246. * Default value is 0.975
  64247. * @type {number}
  64248. */
  64249. _this.area = 0.0075;
  64250. /**
  64251. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64252. * Must not be equal to area and inferior to area.
  64253. * Default value is 0.0
  64254. * @type {number}
  64255. */
  64256. _this.fallOff = 0.000001;
  64257. /**
  64258. * The base color of the SSAO post-process
  64259. * The final result is "base + ssao" between [0, 1]
  64260. * @type {number}
  64261. */
  64262. _this.base = 0.5;
  64263. _this._firstUpdate = true;
  64264. _this._scene = scene;
  64265. // Set up assets
  64266. _this._createRandomTexture();
  64267. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64268. var ssaoRatio = ratio.ssaoRatio || ratio;
  64269. var combineRatio = ratio.combineRatio || ratio;
  64270. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64271. _this._createSSAOPostProcess(ssaoRatio);
  64272. _this._createBlurPostProcess(ssaoRatio);
  64273. _this._createSSAOCombinePostProcess(combineRatio);
  64274. // Set up pipeline
  64275. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64276. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64277. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64278. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64279. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64280. // Finish
  64281. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64282. if (cameras)
  64283. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64284. return _this;
  64285. }
  64286. // Public Methods
  64287. /**
  64288. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64289. */
  64290. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64291. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64292. for (var i = 0; i < this._scene.cameras.length; i++) {
  64293. var camera = this._scene.cameras[i];
  64294. this._originalColorPostProcess.dispose(camera);
  64295. this._ssaoPostProcess.dispose(camera);
  64296. this._blurHPostProcess.dispose(camera);
  64297. this._blurVPostProcess.dispose(camera);
  64298. this._ssaoCombinePostProcess.dispose(camera);
  64299. }
  64300. this._randomTexture.dispose();
  64301. if (disableDepthRender)
  64302. this._scene.disableDepthRenderer();
  64303. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64304. _super.prototype.dispose.call(this);
  64305. };
  64306. // Private Methods
  64307. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64308. var _this = this;
  64309. var size = 16;
  64310. 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);
  64311. 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);
  64312. this._blurHPostProcess.onActivateObservable.add(function () {
  64313. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64314. _this._blurHPostProcess.kernel = size * dw;
  64315. });
  64316. this._blurVPostProcess.onActivateObservable.add(function () {
  64317. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64318. _this._blurVPostProcess.kernel = size * dw;
  64319. });
  64320. };
  64321. SSAORenderingPipeline.prototype._rebuild = function () {
  64322. this._firstUpdate = true;
  64323. _super.prototype._rebuild.call(this);
  64324. };
  64325. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64326. var _this = this;
  64327. var numSamples = 16;
  64328. var sampleSphere = [
  64329. 0.5381, 0.1856, -0.4319,
  64330. 0.1379, 0.2486, 0.4430,
  64331. 0.3371, 0.5679, -0.0057,
  64332. -0.6999, -0.0451, -0.0019,
  64333. 0.0689, -0.1598, -0.8547,
  64334. 0.0560, 0.0069, -0.1843,
  64335. -0.0146, 0.1402, 0.0762,
  64336. 0.0100, -0.1924, -0.0344,
  64337. -0.3577, -0.5301, -0.4358,
  64338. -0.3169, 0.1063, 0.0158,
  64339. 0.0103, -0.5869, 0.0046,
  64340. -0.0897, -0.4940, 0.3287,
  64341. 0.7119, -0.0154, -0.0918,
  64342. -0.0533, 0.0596, -0.5411,
  64343. 0.0352, -0.0631, 0.5460,
  64344. -0.4776, 0.2847, -0.0271
  64345. ];
  64346. var samplesFactor = 1.0 / numSamples;
  64347. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  64348. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64349. "area", "fallOff", "base", "range", "viewport"
  64350. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64351. this._ssaoPostProcess.onApply = function (effect) {
  64352. if (_this._firstUpdate) {
  64353. effect.setArray3("sampleSphere", sampleSphere);
  64354. effect.setFloat("samplesFactor", samplesFactor);
  64355. effect.setFloat("randTextureTiles", 4.0);
  64356. }
  64357. effect.setFloat("totalStrength", _this.totalStrength);
  64358. effect.setFloat("radius", _this.radius);
  64359. effect.setFloat("area", _this.area);
  64360. effect.setFloat("fallOff", _this.fallOff);
  64361. effect.setFloat("base", _this.base);
  64362. effect.setTexture("textureSampler", _this._depthTexture);
  64363. effect.setTexture("randomSampler", _this._randomTexture);
  64364. };
  64365. };
  64366. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64367. var _this = this;
  64368. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64369. this._ssaoCombinePostProcess.onApply = function (effect) {
  64370. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64371. };
  64372. };
  64373. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  64374. var size = 512;
  64375. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64376. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64377. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64378. var context = this._randomTexture.getContext();
  64379. var rand = function (min, max) {
  64380. return Math.random() * (max - min) + min;
  64381. };
  64382. var randVector = BABYLON.Vector3.Zero();
  64383. for (var x = 0; x < size; x++) {
  64384. for (var y = 0; y < size; y++) {
  64385. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  64386. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  64387. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  64388. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64389. context.fillRect(x, y, 1, 1);
  64390. }
  64391. }
  64392. this._randomTexture.update(false);
  64393. };
  64394. __decorate([
  64395. BABYLON.serialize()
  64396. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  64397. __decorate([
  64398. BABYLON.serialize()
  64399. ], SSAORenderingPipeline.prototype, "radius", void 0);
  64400. __decorate([
  64401. BABYLON.serialize()
  64402. ], SSAORenderingPipeline.prototype, "area", void 0);
  64403. __decorate([
  64404. BABYLON.serialize()
  64405. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  64406. __decorate([
  64407. BABYLON.serialize()
  64408. ], SSAORenderingPipeline.prototype, "base", void 0);
  64409. return SSAORenderingPipeline;
  64410. }(BABYLON.PostProcessRenderPipeline));
  64411. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  64412. })(BABYLON || (BABYLON = {}));
  64413. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  64414. var BABYLON;
  64415. (function (BABYLON) {
  64416. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  64417. __extends(SSAO2RenderingPipeline, _super);
  64418. /**
  64419. * @constructor
  64420. * @param {string} name - The rendering pipeline name
  64421. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64422. * @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 }
  64423. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64424. */
  64425. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  64426. var _this = _super.call(this, scene.getEngine(), name) || this;
  64427. // Members
  64428. /**
  64429. * The PassPostProcess id in the pipeline that contains the original scene color
  64430. * @type {string}
  64431. */
  64432. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64433. /**
  64434. * The SSAO PostProcess id in the pipeline
  64435. * @type {string}
  64436. */
  64437. _this.SSAORenderEffect = "SSAORenderEffect";
  64438. /**
  64439. * The horizontal blur PostProcess id in the pipeline
  64440. * @type {string}
  64441. */
  64442. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64443. /**
  64444. * The vertical blur PostProcess id in the pipeline
  64445. * @type {string}
  64446. */
  64447. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64448. /**
  64449. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64450. * @type {string}
  64451. */
  64452. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64453. /**
  64454. * The output strength of the SSAO post-process. Default value is 1.0.
  64455. * @type {number}
  64456. */
  64457. _this.totalStrength = 1.0;
  64458. /**
  64459. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  64460. * @type {number}
  64461. */
  64462. _this.maxZ = 100.0;
  64463. /**
  64464. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  64465. * @type {number}
  64466. */
  64467. _this.minZAspect = 0.2;
  64468. /**
  64469. * Number of samples used for the SSAO calculations. Default value is 8
  64470. * @type {number}
  64471. */
  64472. _this._samples = 8;
  64473. /**
  64474. * Are we using bilateral blur ?
  64475. * @type {boolean}
  64476. */
  64477. _this._expensiveBlur = true;
  64478. /**
  64479. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  64480. * @type {number}
  64481. */
  64482. _this.radius = 2.0;
  64483. /**
  64484. * The base color of the SSAO post-process
  64485. * The final result is "base + ssao" between [0, 1]
  64486. * @type {number}
  64487. */
  64488. _this.base = 0.1;
  64489. _this._firstUpdate = true;
  64490. _this._scene = scene;
  64491. if (!_this.isSupported) {
  64492. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  64493. return _this;
  64494. }
  64495. var ssaoRatio = ratio.ssaoRatio || ratio;
  64496. var blurRatio = ratio.blurRatio || ratio;
  64497. // Set up assets
  64498. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  64499. _this._createRandomTexture();
  64500. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  64501. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  64502. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64503. _this._createSSAOPostProcess(1.0);
  64504. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  64505. _this._createSSAOCombinePostProcess(blurRatio);
  64506. // Set up pipeline
  64507. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64508. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64509. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64510. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64511. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64512. // Finish
  64513. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64514. if (cameras)
  64515. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64516. return _this;
  64517. }
  64518. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  64519. get: function () {
  64520. return this._samples;
  64521. },
  64522. set: function (n) {
  64523. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  64524. this._samples = n;
  64525. this._sampleSphere = this._generateHemisphere();
  64526. this._firstUpdate = true;
  64527. },
  64528. enumerable: true,
  64529. configurable: true
  64530. });
  64531. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  64532. get: function () {
  64533. return this._expensiveBlur;
  64534. },
  64535. set: function (b) {
  64536. 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"]);
  64537. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  64538. this._expensiveBlur = b;
  64539. this._firstUpdate = true;
  64540. },
  64541. enumerable: true,
  64542. configurable: true
  64543. });
  64544. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  64545. /**
  64546. * Support test.
  64547. * @type {boolean}
  64548. */
  64549. get: function () {
  64550. var engine = BABYLON.Engine.LastCreatedEngine;
  64551. if (!engine) {
  64552. return false;
  64553. }
  64554. return engine.getCaps().drawBuffersExtension;
  64555. },
  64556. enumerable: true,
  64557. configurable: true
  64558. });
  64559. // Public Methods
  64560. /**
  64561. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64562. */
  64563. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  64564. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  64565. for (var i = 0; i < this._scene.cameras.length; i++) {
  64566. var camera = this._scene.cameras[i];
  64567. this._originalColorPostProcess.dispose(camera);
  64568. this._ssaoPostProcess.dispose(camera);
  64569. this._blurHPostProcess.dispose(camera);
  64570. this._blurVPostProcess.dispose(camera);
  64571. this._ssaoCombinePostProcess.dispose(camera);
  64572. }
  64573. this._randomTexture.dispose();
  64574. if (disableGeometryBufferRenderer)
  64575. this._scene.disableGeometryBufferRenderer();
  64576. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64577. _super.prototype.dispose.call(this);
  64578. };
  64579. // Private Methods
  64580. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  64581. var _this = this;
  64582. this._samplerOffsets = [];
  64583. var expensive = this.expensiveBlur;
  64584. for (var i = -8; i < 8; i++) {
  64585. this._samplerOffsets.push(i * 2 + 0.5);
  64586. }
  64587. 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");
  64588. this._blurHPostProcess.onApply = function (effect) {
  64589. if (!_this._scene.activeCamera) {
  64590. return;
  64591. }
  64592. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  64593. effect.setFloat("near", _this._scene.activeCamera.minZ);
  64594. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  64595. effect.setFloat("radius", _this.radius);
  64596. effect.setTexture("depthSampler", _this._depthTexture);
  64597. if (_this._firstUpdate) {
  64598. effect.setArray("samplerOffsets", _this._samplerOffsets);
  64599. }
  64600. };
  64601. 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");
  64602. this._blurVPostProcess.onApply = function (effect) {
  64603. if (!_this._scene.activeCamera) {
  64604. return;
  64605. }
  64606. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  64607. effect.setFloat("near", _this._scene.activeCamera.minZ);
  64608. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  64609. effect.setFloat("radius", _this.radius);
  64610. effect.setTexture("depthSampler", _this._depthTexture);
  64611. if (_this._firstUpdate) {
  64612. effect.setArray("samplerOffsets", _this._samplerOffsets);
  64613. _this._firstUpdate = false;
  64614. }
  64615. };
  64616. };
  64617. SSAO2RenderingPipeline.prototype._rebuild = function () {
  64618. this._firstUpdate = true;
  64619. _super.prototype._rebuild.call(this);
  64620. };
  64621. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  64622. var numSamples = this.samples;
  64623. var result = [];
  64624. var vector, scale;
  64625. var rand = function (min, max) {
  64626. return Math.random() * (max - min) + min;
  64627. };
  64628. var i = 0;
  64629. while (i < numSamples) {
  64630. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  64631. vector.normalize();
  64632. scale = i / numSamples;
  64633. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  64634. vector.scaleInPlace(scale);
  64635. result.push(vector.x, vector.y, vector.z);
  64636. i++;
  64637. }
  64638. return result;
  64639. };
  64640. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64641. var _this = this;
  64642. var numSamples = this.samples;
  64643. this._sampleSphere = this._generateHemisphere();
  64644. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  64645. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64646. "base", "range", "projection", "near", "far", "texelSize",
  64647. "xViewport", "yViewport", "maxZ", "minZAspect"
  64648. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64649. this._ssaoPostProcess.onApply = function (effect) {
  64650. if (_this._firstUpdate) {
  64651. effect.setArray3("sampleSphere", _this._sampleSphere);
  64652. effect.setFloat("randTextureTiles", 4.0);
  64653. }
  64654. if (!_this._scene.activeCamera) {
  64655. return;
  64656. }
  64657. effect.setFloat("samplesFactor", 1 / _this.samples);
  64658. effect.setFloat("totalStrength", _this.totalStrength);
  64659. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  64660. effect.setFloat("radius", _this.radius);
  64661. effect.setFloat("maxZ", _this.maxZ);
  64662. effect.setFloat("minZAspect", _this.minZAspect);
  64663. effect.setFloat("base", _this.base);
  64664. effect.setFloat("near", _this._scene.activeCamera.minZ);
  64665. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  64666. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  64667. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  64668. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  64669. effect.setTexture("textureSampler", _this._depthTexture);
  64670. effect.setTexture("normalSampler", _this._normalTexture);
  64671. effect.setTexture("randomSampler", _this._randomTexture);
  64672. };
  64673. };
  64674. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64675. var _this = this;
  64676. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64677. this._ssaoCombinePostProcess.onApply = function (effect) {
  64678. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64679. };
  64680. };
  64681. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  64682. var size = 512;
  64683. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64684. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64685. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64686. var context = this._randomTexture.getContext();
  64687. var rand = function (min, max) {
  64688. return Math.random() * (max - min) + min;
  64689. };
  64690. var randVector = BABYLON.Vector3.Zero();
  64691. for (var x = 0; x < size; x++) {
  64692. for (var y = 0; y < size; y++) {
  64693. randVector.x = rand(0.0, 1.0);
  64694. randVector.y = rand(0.0, 1.0);
  64695. randVector.z = 0.0;
  64696. randVector.normalize();
  64697. randVector.scaleInPlace(255);
  64698. randVector.x = Math.floor(randVector.x);
  64699. randVector.y = Math.floor(randVector.y);
  64700. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64701. context.fillRect(x, y, 1, 1);
  64702. }
  64703. }
  64704. this._randomTexture.update(false);
  64705. };
  64706. __decorate([
  64707. BABYLON.serialize()
  64708. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  64709. __decorate([
  64710. BABYLON.serialize()
  64711. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  64712. __decorate([
  64713. BABYLON.serialize()
  64714. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  64715. __decorate([
  64716. BABYLON.serialize("samples")
  64717. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  64718. __decorate([
  64719. BABYLON.serialize("expensiveBlur")
  64720. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  64721. __decorate([
  64722. BABYLON.serialize()
  64723. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  64724. __decorate([
  64725. BABYLON.serialize()
  64726. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  64727. return SSAO2RenderingPipeline;
  64728. }(BABYLON.PostProcessRenderPipeline));
  64729. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  64730. })(BABYLON || (BABYLON = {}));
  64731. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  64732. // BABYLON.JS Chromatic Aberration GLSL Shader
  64733. // Author: Olivier Guyot
  64734. // Separates very slightly R, G and B colors on the edges of the screen
  64735. // Inspired by Francois Tarlier & Martins Upitis
  64736. var BABYLON;
  64737. (function (BABYLON) {
  64738. var LensRenderingPipeline = /** @class */ (function (_super) {
  64739. __extends(LensRenderingPipeline, _super);
  64740. /**
  64741. * @constructor
  64742. *
  64743. * Effect parameters are as follow:
  64744. * {
  64745. * chromatic_aberration: number; // from 0 to x (1 for realism)
  64746. * edge_blur: number; // from 0 to x (1 for realism)
  64747. * distortion: number; // from 0 to x (1 for realism)
  64748. * grain_amount: number; // from 0 to 1
  64749. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  64750. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  64751. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  64752. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  64753. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  64754. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  64755. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  64756. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  64757. * }
  64758. * Note: if an effect parameter is unset, effect is disabled
  64759. *
  64760. * @param {string} name - The rendering pipeline name
  64761. * @param {object} parameters - An object containing all parameters (see above)
  64762. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64763. * @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)
  64764. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64765. */
  64766. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  64767. if (ratio === void 0) { ratio = 1.0; }
  64768. var _this = _super.call(this, scene.getEngine(), name) || this;
  64769. // Lens effects can be of the following:
  64770. // - chromatic aberration (slight shift of RGB colors)
  64771. // - blur on the edge of the lens
  64772. // - lens distortion
  64773. // - depth-of-field blur & highlights enhancing
  64774. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  64775. // - grain effect (noise or custom texture)
  64776. // Two additional texture samplers are needed:
  64777. // - depth map (for depth-of-field)
  64778. // - grain texture
  64779. /**
  64780. * The chromatic aberration PostProcess id in the pipeline
  64781. * @type {string}
  64782. */
  64783. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  64784. /**
  64785. * The highlights enhancing PostProcess id in the pipeline
  64786. * @type {string}
  64787. */
  64788. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  64789. /**
  64790. * The depth-of-field PostProcess id in the pipeline
  64791. * @type {string}
  64792. */
  64793. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  64794. _this._scene = scene;
  64795. // Fetch texture samplers
  64796. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64797. if (parameters.grain_texture) {
  64798. _this._grainTexture = parameters.grain_texture;
  64799. }
  64800. else {
  64801. _this._createGrainTexture();
  64802. }
  64803. // save parameters
  64804. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  64805. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  64806. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  64807. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  64808. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  64809. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  64810. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  64811. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  64812. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  64813. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  64814. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  64815. // Create effects
  64816. _this._createChromaticAberrationPostProcess(ratio);
  64817. _this._createHighlightsPostProcess(ratio);
  64818. _this._createDepthOfFieldPostProcess(ratio / 4);
  64819. // Set up pipeline
  64820. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  64821. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  64822. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  64823. if (_this._highlightsGain === -1) {
  64824. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  64825. }
  64826. // Finish
  64827. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64828. if (cameras) {
  64829. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64830. }
  64831. return _this;
  64832. }
  64833. // public methods (self explanatory)
  64834. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  64835. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  64836. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  64837. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  64838. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  64839. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  64840. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  64841. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  64842. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  64843. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  64844. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  64845. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  64846. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  64847. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  64848. };
  64849. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  64850. this._highlightsPostProcess.updateEffect();
  64851. };
  64852. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  64853. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  64854. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  64855. this._highlightsGain = amount;
  64856. };
  64857. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  64858. if (this._highlightsGain === -1) {
  64859. this._highlightsGain = 1.0;
  64860. }
  64861. this._highlightsThreshold = amount;
  64862. };
  64863. LensRenderingPipeline.prototype.disableHighlights = function () {
  64864. this._highlightsGain = -1;
  64865. };
  64866. /**
  64867. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  64868. */
  64869. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64870. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64871. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64872. this._chromaticAberrationPostProcess = null;
  64873. this._highlightsPostProcess = null;
  64874. this._depthOfFieldPostProcess = null;
  64875. this._grainTexture.dispose();
  64876. if (disableDepthRender)
  64877. this._scene.disableDepthRenderer();
  64878. };
  64879. // colors shifting and distortion
  64880. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  64881. var _this = this;
  64882. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  64883. [], // samplers
  64884. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64885. this._chromaticAberrationPostProcess.onApply = function (effect) {
  64886. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  64887. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  64888. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  64889. };
  64890. };
  64891. // highlights enhancing
  64892. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  64893. var _this = this;
  64894. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  64895. [], // samplers
  64896. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  64897. this._highlightsPostProcess.onApply = function (effect) {
  64898. effect.setFloat('gain', _this._highlightsGain);
  64899. effect.setFloat('threshold', _this._highlightsThreshold);
  64900. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  64901. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  64902. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  64903. };
  64904. };
  64905. // colors shifting and distortion
  64906. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  64907. var _this = this;
  64908. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  64909. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  64910. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  64911. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64912. this._depthOfFieldPostProcess.onApply = function (effect) {
  64913. effect.setTexture("depthSampler", _this._depthTexture);
  64914. effect.setTexture("grainSampler", _this._grainTexture);
  64915. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  64916. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  64917. effect.setFloat('grain_amount', _this._grainAmount);
  64918. effect.setBool('blur_noise', _this._blurNoise);
  64919. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  64920. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  64921. effect.setFloat('distortion', _this._distortion);
  64922. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  64923. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  64924. effect.setFloat('aperture', _this._dofAperture);
  64925. effect.setFloat('darken', _this._dofDarken);
  64926. effect.setFloat('edge_blur', _this._edgeBlur);
  64927. effect.setBool('highlights', (_this._highlightsGain !== -1));
  64928. if (_this._scene.activeCamera) {
  64929. effect.setFloat('near', _this._scene.activeCamera.minZ);
  64930. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  64931. }
  64932. };
  64933. };
  64934. // creates a black and white random noise texture, 512x512
  64935. LensRenderingPipeline.prototype._createGrainTexture = function () {
  64936. var size = 512;
  64937. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64938. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64939. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64940. var context = this._grainTexture.getContext();
  64941. var rand = function (min, max) {
  64942. return Math.random() * (max - min) + min;
  64943. };
  64944. var value;
  64945. for (var x = 0; x < size; x++) {
  64946. for (var y = 0; y < size; y++) {
  64947. value = Math.floor(rand(0.42, 0.58) * 255);
  64948. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  64949. context.fillRect(x, y, 1, 1);
  64950. }
  64951. }
  64952. this._grainTexture.update(false);
  64953. };
  64954. return LensRenderingPipeline;
  64955. }(BABYLON.PostProcessRenderPipeline));
  64956. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  64957. })(BABYLON || (BABYLON = {}));
  64958. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  64959. var BABYLON;
  64960. (function (BABYLON) {
  64961. var StandardRenderingPipeline = /** @class */ (function (_super) {
  64962. __extends(StandardRenderingPipeline, _super);
  64963. /**
  64964. * @constructor
  64965. * @param {string} name - The rendering pipeline name
  64966. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64967. * @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)
  64968. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  64969. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64970. */
  64971. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  64972. if (originalPostProcess === void 0) { originalPostProcess = null; }
  64973. var _this = _super.call(this, scene.getEngine(), name) || this;
  64974. _this.downSampleX4PostProcess = null;
  64975. _this.brightPassPostProcess = null;
  64976. _this.blurHPostProcesses = [];
  64977. _this.blurVPostProcesses = [];
  64978. _this.textureAdderPostProcess = null;
  64979. _this.volumetricLightPostProcess = null;
  64980. _this.volumetricLightSmoothXPostProcess = null;
  64981. _this.volumetricLightSmoothYPostProcess = null;
  64982. _this.volumetricLightMergePostProces = null;
  64983. _this.volumetricLightFinalPostProcess = null;
  64984. _this.luminancePostProcess = null;
  64985. _this.luminanceDownSamplePostProcesses = [];
  64986. _this.hdrPostProcess = null;
  64987. _this.textureAdderFinalPostProcess = null;
  64988. _this.lensFlareFinalPostProcess = null;
  64989. _this.hdrFinalPostProcess = null;
  64990. _this.lensFlarePostProcess = null;
  64991. _this.lensFlareComposePostProcess = null;
  64992. _this.motionBlurPostProcess = null;
  64993. _this.depthOfFieldPostProcess = null;
  64994. // Values
  64995. _this.brightThreshold = 1.0;
  64996. _this.blurWidth = 512.0;
  64997. _this.horizontalBlur = false;
  64998. _this.exposure = 1.0;
  64999. _this.lensTexture = null;
  65000. _this.volumetricLightCoefficient = 0.2;
  65001. _this.volumetricLightPower = 4.0;
  65002. _this.volumetricLightBlurScale = 64.0;
  65003. _this.sourceLight = null;
  65004. _this.hdrMinimumLuminance = 1.0;
  65005. _this.hdrDecreaseRate = 0.5;
  65006. _this.hdrIncreaseRate = 0.5;
  65007. _this.lensColorTexture = null;
  65008. _this.lensFlareStrength = 20.0;
  65009. _this.lensFlareGhostDispersal = 1.4;
  65010. _this.lensFlareHaloWidth = 0.7;
  65011. _this.lensFlareDistortionStrength = 16.0;
  65012. _this.lensStarTexture = null;
  65013. _this.lensFlareDirtTexture = null;
  65014. _this.depthOfFieldDistance = 10.0;
  65015. _this.depthOfFieldBlurWidth = 64.0;
  65016. _this.motionStrength = 1.0;
  65017. // IAnimatable
  65018. _this.animations = [];
  65019. _this._currentDepthOfFieldSource = null;
  65020. _this._hdrCurrentLuminance = 1.0;
  65021. // Getters and setters
  65022. _this._bloomEnabled = true;
  65023. _this._depthOfFieldEnabled = false;
  65024. _this._vlsEnabled = false;
  65025. _this._lensFlareEnabled = false;
  65026. _this._hdrEnabled = false;
  65027. _this._motionBlurEnabled = false;
  65028. _this._motionBlurSamples = 64.0;
  65029. _this._volumetricLightStepsCount = 50.0;
  65030. _this._cameras = cameras || [];
  65031. // Initialize
  65032. _this._scene = scene;
  65033. _this._basePostProcess = originalPostProcess;
  65034. _this._ratio = ratio;
  65035. // Misc
  65036. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65037. // Finish
  65038. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65039. _this._buildPipeline();
  65040. return _this;
  65041. }
  65042. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65043. get: function () {
  65044. return this._bloomEnabled;
  65045. },
  65046. set: function (enabled) {
  65047. if (this._bloomEnabled === enabled) {
  65048. return;
  65049. }
  65050. this._bloomEnabled = enabled;
  65051. this._buildPipeline();
  65052. },
  65053. enumerable: true,
  65054. configurable: true
  65055. });
  65056. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65057. get: function () {
  65058. return this._depthOfFieldEnabled;
  65059. },
  65060. set: function (enabled) {
  65061. if (this._depthOfFieldEnabled === enabled) {
  65062. return;
  65063. }
  65064. this._depthOfFieldEnabled = enabled;
  65065. this._buildPipeline();
  65066. },
  65067. enumerable: true,
  65068. configurable: true
  65069. });
  65070. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65071. get: function () {
  65072. return this._lensFlareEnabled;
  65073. },
  65074. set: function (enabled) {
  65075. if (this._lensFlareEnabled === enabled) {
  65076. return;
  65077. }
  65078. this._lensFlareEnabled = enabled;
  65079. this._buildPipeline();
  65080. },
  65081. enumerable: true,
  65082. configurable: true
  65083. });
  65084. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65085. get: function () {
  65086. return this._hdrEnabled;
  65087. },
  65088. set: function (enabled) {
  65089. if (this._hdrEnabled === enabled) {
  65090. return;
  65091. }
  65092. this._hdrEnabled = enabled;
  65093. this._buildPipeline();
  65094. },
  65095. enumerable: true,
  65096. configurable: true
  65097. });
  65098. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65099. get: function () {
  65100. return this._vlsEnabled;
  65101. },
  65102. set: function (enabled) {
  65103. if (this._vlsEnabled === enabled) {
  65104. return;
  65105. }
  65106. if (enabled) {
  65107. var geometry = this._scene.enableGeometryBufferRenderer();
  65108. if (!geometry) {
  65109. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65110. return;
  65111. }
  65112. }
  65113. this._vlsEnabled = enabled;
  65114. this._buildPipeline();
  65115. },
  65116. enumerable: true,
  65117. configurable: true
  65118. });
  65119. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65120. get: function () {
  65121. return this._motionBlurEnabled;
  65122. },
  65123. set: function (enabled) {
  65124. if (this._motionBlurEnabled === enabled) {
  65125. return;
  65126. }
  65127. this._motionBlurEnabled = enabled;
  65128. this._buildPipeline();
  65129. },
  65130. enumerable: true,
  65131. configurable: true
  65132. });
  65133. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65134. get: function () {
  65135. return this._volumetricLightStepsCount;
  65136. },
  65137. set: function (count) {
  65138. if (this.volumetricLightPostProcess) {
  65139. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65140. }
  65141. this._volumetricLightStepsCount = count;
  65142. },
  65143. enumerable: true,
  65144. configurable: true
  65145. });
  65146. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65147. get: function () {
  65148. return this._motionBlurSamples;
  65149. },
  65150. set: function (samples) {
  65151. if (this.motionBlurPostProcess) {
  65152. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65153. }
  65154. this._motionBlurSamples = samples;
  65155. },
  65156. enumerable: true,
  65157. configurable: true
  65158. });
  65159. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65160. var _this = this;
  65161. var ratio = this._ratio;
  65162. var scene = this._scene;
  65163. this._disposePostProcesses();
  65164. this._reset();
  65165. // Create pass post-process
  65166. if (!this._basePostProcess) {
  65167. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65168. this.originalPostProcess.onApply = function (effect) {
  65169. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65170. };
  65171. }
  65172. else {
  65173. this.originalPostProcess = this._basePostProcess;
  65174. }
  65175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65176. this._currentDepthOfFieldSource = this.originalPostProcess;
  65177. if (this._vlsEnabled) {
  65178. // Create volumetric light
  65179. this._createVolumetricLightPostProcess(scene, ratio);
  65180. // Create volumetric light final post-process
  65181. 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);
  65182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65183. }
  65184. if (this._bloomEnabled) {
  65185. // Create down sample X4 post-process
  65186. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65187. // Create bright pass post-process
  65188. this._createBrightPassPostProcess(scene, ratio / 2);
  65189. // Create gaussian blur post-processes (down sampling blurs)
  65190. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65191. // Create texture adder post-process
  65192. this._createTextureAdderPostProcess(scene, ratio);
  65193. // Create depth-of-field source post-process
  65194. 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);
  65195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65196. }
  65197. if (this._lensFlareEnabled) {
  65198. // Create lens flare post-process
  65199. this._createLensFlarePostProcess(scene, ratio);
  65200. // Create depth-of-field source post-process post lens-flare and disable it now
  65201. 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);
  65202. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65203. }
  65204. if (this._hdrEnabled) {
  65205. // Create luminance
  65206. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65207. // Create HDR
  65208. this._createHdrPostProcess(scene, ratio);
  65209. // Create depth-of-field source post-process post hdr and disable it now
  65210. 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);
  65211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65212. }
  65213. if (this._depthOfFieldEnabled) {
  65214. // Create gaussian blur used by depth-of-field
  65215. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65216. // Create depth-of-field post-process
  65217. this._createDepthOfFieldPostProcess(scene, ratio);
  65218. }
  65219. if (this._motionBlurEnabled) {
  65220. // Create motion blur post-process
  65221. this._createMotionBlurPostProcess(scene, ratio);
  65222. }
  65223. if (this._cameras !== null) {
  65224. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65225. }
  65226. };
  65227. // Down Sample X4 Post-Processs
  65228. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65229. var _this = this;
  65230. var downSampleX4Offsets = new Array(32);
  65231. 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);
  65232. this.downSampleX4PostProcess.onApply = function (effect) {
  65233. var id = 0;
  65234. var width = _this.downSampleX4PostProcess.width;
  65235. var height = _this.downSampleX4PostProcess.height;
  65236. for (var i = -2; i < 2; i++) {
  65237. for (var j = -2; j < 2; j++) {
  65238. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65239. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65240. id += 2;
  65241. }
  65242. }
  65243. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65244. };
  65245. // Add to pipeline
  65246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65247. };
  65248. // Brightpass Post-Process
  65249. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65250. var _this = this;
  65251. var brightOffsets = new Array(8);
  65252. 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);
  65253. this.brightPassPostProcess.onApply = function (effect) {
  65254. var sU = (1.0 / _this.brightPassPostProcess.width);
  65255. var sV = (1.0 / _this.brightPassPostProcess.height);
  65256. brightOffsets[0] = -0.5 * sU;
  65257. brightOffsets[1] = 0.5 * sV;
  65258. brightOffsets[2] = 0.5 * sU;
  65259. brightOffsets[3] = 0.5 * sV;
  65260. brightOffsets[4] = -0.5 * sU;
  65261. brightOffsets[5] = -0.5 * sV;
  65262. brightOffsets[6] = 0.5 * sU;
  65263. brightOffsets[7] = -0.5 * sV;
  65264. effect.setArray2("dsOffsets", brightOffsets);
  65265. effect.setFloat("brightThreshold", _this.brightThreshold);
  65266. };
  65267. // Add to pipeline
  65268. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65269. };
  65270. // Create blur H&V post-processes
  65271. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65272. var _this = this;
  65273. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65274. var engine = scene.getEngine();
  65275. 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);
  65276. 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);
  65277. blurX.onActivateObservable.add(function () {
  65278. var dw = blurX.width / engine.getRenderWidth();
  65279. blurX.kernel = _this[blurWidthKey] * dw;
  65280. });
  65281. blurY.onActivateObservable.add(function () {
  65282. var dw = blurY.height / engine.getRenderHeight();
  65283. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65284. });
  65285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65286. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65287. this.blurHPostProcesses.push(blurX);
  65288. this.blurVPostProcesses.push(blurY);
  65289. };
  65290. // Create texture adder post-process
  65291. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65292. var _this = this;
  65293. 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);
  65294. this.textureAdderPostProcess.onApply = function (effect) {
  65295. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65296. effect.setTexture("lensSampler", _this.lensTexture);
  65297. effect.setFloat("exposure", _this.exposure);
  65298. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65299. };
  65300. // Add to pipeline
  65301. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65302. };
  65303. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65304. var _this = this;
  65305. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65306. geometryRenderer.enablePosition = true;
  65307. var geometry = geometryRenderer.getGBuffer();
  65308. // Base post-process
  65309. 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));
  65310. var depthValues = BABYLON.Vector2.Zero();
  65311. this.volumetricLightPostProcess.onApply = function (effect) {
  65312. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65313. var generator = _this.sourceLight.getShadowGenerator();
  65314. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65315. effect.setTexture("positionSampler", geometry.textures[2]);
  65316. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65317. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65318. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65319. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65320. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65321. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65322. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65323. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65324. effect.setVector2("depthValues", depthValues);
  65325. }
  65326. };
  65327. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65328. // Smooth
  65329. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65330. // Merge
  65331. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65332. this.volumetricLightMergePostProces.onApply = function (effect) {
  65333. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65334. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65335. };
  65336. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  65337. };
  65338. // Create luminance
  65339. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  65340. var _this = this;
  65341. // Create luminance
  65342. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  65343. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  65344. var offsets = [];
  65345. this.luminancePostProcess.onApply = function (effect) {
  65346. var sU = (1.0 / _this.luminancePostProcess.width);
  65347. var sV = (1.0 / _this.luminancePostProcess.height);
  65348. offsets[0] = -0.5 * sU;
  65349. offsets[1] = 0.5 * sV;
  65350. offsets[2] = 0.5 * sU;
  65351. offsets[3] = 0.5 * sV;
  65352. offsets[4] = -0.5 * sU;
  65353. offsets[5] = -0.5 * sV;
  65354. offsets[6] = 0.5 * sU;
  65355. offsets[7] = -0.5 * sV;
  65356. effect.setArray2("lumOffsets", offsets);
  65357. };
  65358. // Add to pipeline
  65359. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  65360. // Create down sample luminance
  65361. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  65362. var size = Math.pow(3, i);
  65363. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  65364. if (i === 0) {
  65365. defines += "#define FINAL_DOWN_SAMPLER";
  65366. }
  65367. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  65368. this.luminanceDownSamplePostProcesses.push(postProcess);
  65369. }
  65370. // Create callbacks and add effects
  65371. var lastLuminance = this.luminancePostProcess;
  65372. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  65373. var downSampleOffsets = new Array(18);
  65374. pp.onApply = function (effect) {
  65375. if (!lastLuminance) {
  65376. return;
  65377. }
  65378. var id = 0;
  65379. for (var x = -1; x < 2; x++) {
  65380. for (var y = -1; y < 2; y++) {
  65381. downSampleOffsets[id] = x / lastLuminance.width;
  65382. downSampleOffsets[id + 1] = y / lastLuminance.height;
  65383. id += 2;
  65384. }
  65385. }
  65386. effect.setArray2("dsOffsets", downSampleOffsets);
  65387. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  65388. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65389. lastLuminance = _this.luminancePostProcess;
  65390. }
  65391. else {
  65392. lastLuminance = pp;
  65393. }
  65394. };
  65395. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65396. pp.onAfterRender = function (effect) {
  65397. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  65398. 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);
  65399. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  65400. };
  65401. }
  65402. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  65403. });
  65404. };
  65405. // Create HDR post-process
  65406. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  65407. var _this = this;
  65408. 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);
  65409. var outputLiminance = 1;
  65410. var time = 0;
  65411. var lastTime = 0;
  65412. this.hdrPostProcess.onApply = function (effect) {
  65413. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  65414. time += scene.getEngine().getDeltaTime();
  65415. if (outputLiminance < 0) {
  65416. outputLiminance = _this._hdrCurrentLuminance;
  65417. }
  65418. else {
  65419. var dt = (lastTime - time) / 1000.0;
  65420. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  65421. outputLiminance += _this.hdrDecreaseRate * dt;
  65422. }
  65423. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  65424. outputLiminance -= _this.hdrIncreaseRate * dt;
  65425. }
  65426. else {
  65427. outputLiminance = _this._hdrCurrentLuminance;
  65428. }
  65429. }
  65430. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  65431. effect.setFloat("averageLuminance", outputLiminance);
  65432. lastTime = time;
  65433. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  65434. };
  65435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  65436. };
  65437. // Create lens flare post-process
  65438. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  65439. var _this = this;
  65440. 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);
  65441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  65442. this._createBlurPostProcesses(scene, ratio / 4, 2);
  65443. 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);
  65444. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  65445. var resolution = new BABYLON.Vector2(0, 0);
  65446. // Lens flare
  65447. this.lensFlarePostProcess.onApply = function (effect) {
  65448. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  65449. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  65450. effect.setFloat("strength", _this.lensFlareStrength);
  65451. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  65452. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  65453. // Shift
  65454. resolution.x = _this.lensFlarePostProcess.width;
  65455. resolution.y = _this.lensFlarePostProcess.height;
  65456. effect.setVector2("resolution", resolution);
  65457. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  65458. };
  65459. // Compose
  65460. 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);
  65461. 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);
  65462. this.lensFlareComposePostProcess.onApply = function (effect) {
  65463. if (!_this._scene.activeCamera) {
  65464. return;
  65465. }
  65466. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65467. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  65468. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  65469. // Lens start rotation matrix
  65470. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  65471. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  65472. 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));
  65473. camRot *= 4.0;
  65474. 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);
  65475. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  65476. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  65477. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  65478. };
  65479. };
  65480. // Create depth-of-field post-process
  65481. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  65482. var _this = this;
  65483. 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);
  65484. this.depthOfFieldPostProcess.onApply = function (effect) {
  65485. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65486. effect.setTexture("depthSampler", _this._getDepthTexture());
  65487. effect.setFloat("distance", _this.depthOfFieldDistance);
  65488. };
  65489. // Add to pipeline
  65490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  65491. };
  65492. // Create motion blur post-process
  65493. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  65494. var _this = this;
  65495. 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);
  65496. var motionScale = 0;
  65497. var prevViewProjection = BABYLON.Matrix.Identity();
  65498. var invViewProjection = BABYLON.Matrix.Identity();
  65499. var viewProjection = BABYLON.Matrix.Identity();
  65500. var screenSize = BABYLON.Vector2.Zero();
  65501. this.motionBlurPostProcess.onApply = function (effect) {
  65502. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  65503. viewProjection.invertToRef(invViewProjection);
  65504. effect.setMatrix("inverseViewProjection", invViewProjection);
  65505. effect.setMatrix("prevViewProjection", prevViewProjection);
  65506. prevViewProjection = viewProjection;
  65507. screenSize.x = _this.motionBlurPostProcess.width;
  65508. screenSize.y = _this.motionBlurPostProcess.height;
  65509. effect.setVector2("screenSize", screenSize);
  65510. motionScale = scene.getEngine().getFps() / 60.0;
  65511. effect.setFloat("motionScale", motionScale);
  65512. effect.setFloat("motionStrength", _this.motionStrength);
  65513. effect.setTexture("depthSampler", _this._getDepthTexture());
  65514. };
  65515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  65516. };
  65517. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  65518. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  65519. var renderer = this._scene.enableGeometryBufferRenderer();
  65520. return renderer.getGBuffer().textures[0];
  65521. }
  65522. return this._scene.enableDepthRenderer().getDepthMap();
  65523. };
  65524. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  65525. for (var i = 0; i < this._cameras.length; i++) {
  65526. var camera = this._cameras[i];
  65527. if (this.originalPostProcess) {
  65528. this.originalPostProcess.dispose(camera);
  65529. }
  65530. if (this.downSampleX4PostProcess) {
  65531. this.downSampleX4PostProcess.dispose(camera);
  65532. }
  65533. if (this.brightPassPostProcess) {
  65534. this.brightPassPostProcess.dispose(camera);
  65535. }
  65536. if (this.textureAdderPostProcess) {
  65537. this.textureAdderPostProcess.dispose(camera);
  65538. }
  65539. if (this.textureAdderFinalPostProcess) {
  65540. this.textureAdderFinalPostProcess.dispose(camera);
  65541. }
  65542. if (this.volumetricLightPostProcess) {
  65543. this.volumetricLightPostProcess.dispose(camera);
  65544. }
  65545. if (this.volumetricLightSmoothXPostProcess) {
  65546. this.volumetricLightSmoothXPostProcess.dispose(camera);
  65547. }
  65548. if (this.volumetricLightSmoothYPostProcess) {
  65549. this.volumetricLightSmoothYPostProcess.dispose(camera);
  65550. }
  65551. if (this.volumetricLightMergePostProces) {
  65552. this.volumetricLightMergePostProces.dispose(camera);
  65553. }
  65554. if (this.volumetricLightFinalPostProcess) {
  65555. this.volumetricLightFinalPostProcess.dispose(camera);
  65556. }
  65557. if (this.lensFlarePostProcess) {
  65558. this.lensFlarePostProcess.dispose(camera);
  65559. }
  65560. if (this.lensFlareComposePostProcess) {
  65561. this.lensFlareComposePostProcess.dispose(camera);
  65562. }
  65563. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  65564. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  65565. }
  65566. if (this.luminancePostProcess) {
  65567. this.luminancePostProcess.dispose(camera);
  65568. }
  65569. if (this.hdrPostProcess) {
  65570. this.hdrPostProcess.dispose(camera);
  65571. }
  65572. if (this.hdrFinalPostProcess) {
  65573. this.hdrFinalPostProcess.dispose(camera);
  65574. }
  65575. if (this.depthOfFieldPostProcess) {
  65576. this.depthOfFieldPostProcess.dispose(camera);
  65577. }
  65578. if (this.motionBlurPostProcess) {
  65579. this.motionBlurPostProcess.dispose(camera);
  65580. }
  65581. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  65582. this.blurHPostProcesses[j].dispose(camera);
  65583. }
  65584. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  65585. this.blurVPostProcesses[j].dispose(camera);
  65586. }
  65587. }
  65588. this.originalPostProcess = null;
  65589. this.downSampleX4PostProcess = null;
  65590. this.brightPassPostProcess = null;
  65591. this.textureAdderPostProcess = null;
  65592. this.textureAdderFinalPostProcess = null;
  65593. this.volumetricLightPostProcess = null;
  65594. this.volumetricLightSmoothXPostProcess = null;
  65595. this.volumetricLightSmoothYPostProcess = null;
  65596. this.volumetricLightMergePostProces = null;
  65597. this.volumetricLightFinalPostProcess = null;
  65598. this.lensFlarePostProcess = null;
  65599. this.lensFlareComposePostProcess = null;
  65600. this.luminancePostProcess = null;
  65601. this.hdrPostProcess = null;
  65602. this.hdrFinalPostProcess = null;
  65603. this.depthOfFieldPostProcess = null;
  65604. this.motionBlurPostProcess = null;
  65605. this.luminanceDownSamplePostProcesses = [];
  65606. this.blurHPostProcesses = [];
  65607. this.blurVPostProcesses = [];
  65608. };
  65609. // Dispose
  65610. StandardRenderingPipeline.prototype.dispose = function () {
  65611. this._disposePostProcesses();
  65612. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  65613. _super.prototype.dispose.call(this);
  65614. };
  65615. // Serialize rendering pipeline
  65616. StandardRenderingPipeline.prototype.serialize = function () {
  65617. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  65618. serializationObject.customType = "StandardRenderingPipeline";
  65619. return serializationObject;
  65620. };
  65621. /**
  65622. * Static members
  65623. */
  65624. // Parse serialized pipeline
  65625. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  65626. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  65627. };
  65628. // Luminance steps
  65629. StandardRenderingPipeline.LuminanceSteps = 6;
  65630. __decorate([
  65631. BABYLON.serialize()
  65632. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  65633. __decorate([
  65634. BABYLON.serialize()
  65635. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  65636. __decorate([
  65637. BABYLON.serialize()
  65638. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  65639. __decorate([
  65640. BABYLON.serialize()
  65641. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  65642. __decorate([
  65643. BABYLON.serializeAsTexture("lensTexture")
  65644. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  65645. __decorate([
  65646. BABYLON.serialize()
  65647. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  65648. __decorate([
  65649. BABYLON.serialize()
  65650. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  65651. __decorate([
  65652. BABYLON.serialize()
  65653. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  65654. __decorate([
  65655. BABYLON.serialize()
  65656. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  65657. __decorate([
  65658. BABYLON.serialize()
  65659. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  65660. __decorate([
  65661. BABYLON.serialize()
  65662. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  65663. __decorate([
  65664. BABYLON.serializeAsTexture("lensColorTexture")
  65665. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  65666. __decorate([
  65667. BABYLON.serialize()
  65668. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  65669. __decorate([
  65670. BABYLON.serialize()
  65671. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  65672. __decorate([
  65673. BABYLON.serialize()
  65674. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  65675. __decorate([
  65676. BABYLON.serialize()
  65677. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  65678. __decorate([
  65679. BABYLON.serializeAsTexture("lensStarTexture")
  65680. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  65681. __decorate([
  65682. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  65683. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  65684. __decorate([
  65685. BABYLON.serialize()
  65686. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  65687. __decorate([
  65688. BABYLON.serialize()
  65689. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  65690. __decorate([
  65691. BABYLON.serialize()
  65692. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  65693. __decorate([
  65694. BABYLON.serialize()
  65695. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  65696. __decorate([
  65697. BABYLON.serialize()
  65698. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  65699. __decorate([
  65700. BABYLON.serialize()
  65701. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  65702. __decorate([
  65703. BABYLON.serialize()
  65704. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  65705. __decorate([
  65706. BABYLON.serialize()
  65707. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  65708. __decorate([
  65709. BABYLON.serialize()
  65710. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  65711. __decorate([
  65712. BABYLON.serialize()
  65713. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  65714. __decorate([
  65715. BABYLON.serialize()
  65716. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  65717. __decorate([
  65718. BABYLON.serialize()
  65719. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  65720. return StandardRenderingPipeline;
  65721. }(BABYLON.PostProcessRenderPipeline));
  65722. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  65723. })(BABYLON || (BABYLON = {}));
  65724. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  65725. var BABYLON;
  65726. (function (BABYLON) {
  65727. var FxaaPostProcess = /** @class */ (function (_super) {
  65728. __extends(FxaaPostProcess, _super);
  65729. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  65730. if (camera === void 0) { camera = null; }
  65731. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65732. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  65733. _this.onApplyObservable.add(function (effect) {
  65734. var texelSize = _this.texelSize;
  65735. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  65736. });
  65737. return _this;
  65738. }
  65739. return FxaaPostProcess;
  65740. }(BABYLON.PostProcess));
  65741. BABYLON.FxaaPostProcess = FxaaPostProcess;
  65742. })(BABYLON || (BABYLON = {}));
  65743. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  65744. var BABYLON;
  65745. (function (BABYLON) {
  65746. /**
  65747. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  65748. */
  65749. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  65750. __extends(CircleOfConfusionPostProcess, _super);
  65751. /**
  65752. * Creates a new instance of @see CircleOfConfusionPostProcess
  65753. * @param name The name of the effect.
  65754. * @param scene The scene the effect belongs to.
  65755. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  65756. * @param options The required width/height ratio to downsize to before computing the render pass.
  65757. * @param camera The camera to apply the render pass to.
  65758. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65759. * @param engine The engine which the post process will be applied. (default: current engine)
  65760. * @param reusable If the post process can be reused on the same frame. (default: false)
  65761. * @param textureType Type of textures used when performing the post process. (default: 0)
  65762. */
  65763. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  65764. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65765. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65766. /**
  65767. * 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.
  65768. */
  65769. _this.lensSize = 50;
  65770. /**
  65771. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  65772. */
  65773. _this.fStop = 1.4;
  65774. /**
  65775. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  65776. */
  65777. _this.focusDistance = 2000;
  65778. /**
  65779. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  65780. */
  65781. _this.focalLength = 50;
  65782. _this.onApplyObservable.add(function (effect) {
  65783. effect.setTexture("depthSampler", depthTexture);
  65784. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  65785. var aperture = _this.lensSize / _this.fStop;
  65786. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  65787. effect.setFloat('focusDistance', _this.focusDistance);
  65788. effect.setFloat('cocPrecalculation', cocPrecalculation);
  65789. if (scene.activeCamera) {
  65790. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  65791. }
  65792. });
  65793. return _this;
  65794. }
  65795. return CircleOfConfusionPostProcess;
  65796. }(BABYLON.PostProcess));
  65797. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  65798. })(BABYLON || (BABYLON = {}));
  65799. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  65800. var BABYLON;
  65801. (function (BABYLON) {
  65802. /**
  65803. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  65804. */
  65805. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  65806. __extends(DepthOfFieldMergePostProcess, _super);
  65807. /**
  65808. * Creates a new instance of @see CircleOfConfusionPostProcess
  65809. * @param name The name of the effect.
  65810. * @param original The non-blurred image to be modified
  65811. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  65812. * @param options The required width/height ratio to downsize to before computing the render pass.
  65813. * @param camera The camera to apply the render pass to.
  65814. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65815. * @param engine The engine which the post process will be applied. (default: current engine)
  65816. * @param reusable If the post process can be reused on the same frame. (default: false)
  65817. * @param textureType Type of textures used when performing the post process. (default: 0)
  65818. */
  65819. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  65820. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65821. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65822. _this.onApplyObservable.add(function (effect) {
  65823. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  65824. effect.setTextureFromPostProcess("originalSampler", original);
  65825. });
  65826. return _this;
  65827. }
  65828. return DepthOfFieldMergePostProcess;
  65829. }(BABYLON.PostProcess));
  65830. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  65831. })(BABYLON || (BABYLON = {}));
  65832. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  65833. var BABYLON;
  65834. (function (BABYLON) {
  65835. /**
  65836. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  65837. */
  65838. var DepthOfFieldEffect = /** @class */ (function (_super) {
  65839. __extends(DepthOfFieldEffect, _super);
  65840. /**
  65841. * Creates a new instance of @see DepthOfFieldEffect
  65842. * @param scene The scene the effect belongs to.
  65843. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  65844. */
  65845. function DepthOfFieldEffect(scene, pipelineTextureType) {
  65846. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  65847. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY, _this._depthOfFieldBlurX, _this._depthOfFieldMerge]; }, true) || this;
  65848. // Enable and get current depth map
  65849. var depthMap = scene.enableDepthRenderer().getDepthMap();
  65850. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  65851. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65852. // Capture circle of confusion texture
  65853. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65854. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  65855. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  65856. _this._depthOfFieldBlurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), 15, 1.0, null, depthMap, _this._circleOfConfusion, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65857. _this._depthOfFieldBlurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), 15, 1.0, null, depthMap, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65858. // Merge blurred images with original image based on circleOfConfusion
  65859. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65860. return _this;
  65861. }
  65862. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  65863. get: function () {
  65864. return this._depthOfFieldBlurX.kernel;
  65865. },
  65866. /**
  65867. * The size of the kernel to be used for the blur
  65868. */
  65869. set: function (value) {
  65870. this._depthOfFieldBlurX.kernel = value;
  65871. this._depthOfFieldBlurY.kernel = value;
  65872. },
  65873. enumerable: true,
  65874. configurable: true
  65875. });
  65876. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  65877. get: function () {
  65878. return this._circleOfConfusion.focalLength;
  65879. },
  65880. /**
  65881. * The focal the length of the camera used in the effect
  65882. */
  65883. set: function (value) {
  65884. this._circleOfConfusion.focalLength = value;
  65885. },
  65886. enumerable: true,
  65887. configurable: true
  65888. });
  65889. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  65890. get: function () {
  65891. return this._circleOfConfusion.fStop;
  65892. },
  65893. /**
  65894. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  65895. */
  65896. set: function (value) {
  65897. this._circleOfConfusion.fStop = value;
  65898. },
  65899. enumerable: true,
  65900. configurable: true
  65901. });
  65902. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  65903. get: function () {
  65904. return this._circleOfConfusion.focusDistance;
  65905. },
  65906. /**
  65907. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  65908. */
  65909. set: function (value) {
  65910. this._circleOfConfusion.focusDistance = value;
  65911. },
  65912. enumerable: true,
  65913. configurable: true
  65914. });
  65915. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  65916. get: function () {
  65917. return this._circleOfConfusion.lensSize;
  65918. },
  65919. /**
  65920. * 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.
  65921. */
  65922. set: function (value) {
  65923. this._circleOfConfusion.lensSize = value;
  65924. },
  65925. enumerable: true,
  65926. configurable: true
  65927. });
  65928. /**
  65929. * Disposes each of the internal effects for a given camera.
  65930. * @param camera The camera to dispose the effect on.
  65931. */
  65932. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  65933. this._depthOfFieldPass.dispose(camera);
  65934. this._circleOfConfusion.dispose(camera);
  65935. this._depthOfFieldBlurX.dispose(camera);
  65936. this._depthOfFieldBlurY.dispose(camera);
  65937. this._depthOfFieldMerge.dispose(camera);
  65938. };
  65939. return DepthOfFieldEffect;
  65940. }(BABYLON.PostProcessRenderEffect));
  65941. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  65942. })(BABYLON || (BABYLON = {}));
  65943. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  65944. var BABYLON;
  65945. (function (BABYLON) {
  65946. /**
  65947. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  65948. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  65949. */
  65950. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  65951. __extends(DefaultRenderingPipeline, _super);
  65952. /**
  65953. * @constructor
  65954. * @param {string} name - The rendering pipeline name
  65955. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65956. * @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)
  65957. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65958. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  65959. */
  65960. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  65961. if (automaticBuild === void 0) { automaticBuild = true; }
  65962. var _this = _super.call(this, scene.getEngine(), name) || this;
  65963. /**
  65964. * ID of the pass post process used for bloom,
  65965. */
  65966. _this.PassPostProcessId = "PassPostProcessEffect";
  65967. /**
  65968. * ID of the highlight post process used for bloom,
  65969. */
  65970. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  65971. /**
  65972. * ID of the blurX post process used for bloom,
  65973. */
  65974. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  65975. /**
  65976. * ID of the blurY post process used for bloom,
  65977. */
  65978. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  65979. /**
  65980. * ID of the copy back post process used for bloom,
  65981. */
  65982. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  65983. /**
  65984. * ID of the image processing post process;
  65985. */
  65986. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  65987. /**
  65988. * ID of the Fast Approximate Anti-Aliasing post process;
  65989. */
  65990. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  65991. /**
  65992. * ID of the final merge post process;
  65993. */
  65994. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  65995. /**
  65996. * Animations which can be used to tweak settings over a period of time
  65997. */
  65998. _this.animations = [];
  65999. // Values
  66000. _this._bloomEnabled = false;
  66001. _this._depthOfFieldEnabled = false;
  66002. _this._fxaaEnabled = false;
  66003. _this._imageProcessingEnabled = true;
  66004. _this._bloomScale = 0.6;
  66005. _this._buildAllowed = true;
  66006. /**
  66007. * Specifies the size of the bloom blur kernel, relative to the final output size
  66008. */
  66009. _this.bloomKernel = 64;
  66010. /**
  66011. * Specifies the weight of the bloom in the final rendering
  66012. */
  66013. _this._bloomWeight = 0.15;
  66014. _this._cameras = cameras || [];
  66015. _this._buildAllowed = automaticBuild;
  66016. // Initialize
  66017. _this._scene = scene;
  66018. var caps = _this._scene.getEngine().getCaps();
  66019. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66020. // Misc
  66021. if (_this._hdr) {
  66022. if (caps.textureHalfFloatRender) {
  66023. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66024. }
  66025. else if (caps.textureFloatRender) {
  66026. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66027. }
  66028. }
  66029. else {
  66030. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66031. }
  66032. // Attach
  66033. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66034. _this._buildPipeline();
  66035. return _this;
  66036. }
  66037. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66038. get: function () {
  66039. return this._bloomWeight;
  66040. },
  66041. /**
  66042. * The strength of the bloom.
  66043. */
  66044. set: function (value) {
  66045. if (this._bloomWeight === value) {
  66046. return;
  66047. }
  66048. this._bloomWeight = value;
  66049. if (this._hdr && this.copyBack) {
  66050. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66051. }
  66052. },
  66053. enumerable: true,
  66054. configurable: true
  66055. });
  66056. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66057. get: function () {
  66058. return this._bloomScale;
  66059. },
  66060. /**
  66061. * The scale of the bloom, lower value will provide better performance.
  66062. */
  66063. set: function (value) {
  66064. if (this._bloomScale === value) {
  66065. return;
  66066. }
  66067. this._bloomScale = value;
  66068. this._buildPipeline();
  66069. },
  66070. enumerable: true,
  66071. configurable: true
  66072. });
  66073. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66074. get: function () {
  66075. return this._bloomEnabled;
  66076. },
  66077. /**
  66078. * Enable or disable the bloom from the pipeline
  66079. */
  66080. set: function (enabled) {
  66081. if (this._bloomEnabled === enabled) {
  66082. return;
  66083. }
  66084. this._bloomEnabled = enabled;
  66085. this._buildPipeline();
  66086. },
  66087. enumerable: true,
  66088. configurable: true
  66089. });
  66090. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66091. /**
  66092. * If the depth of field is enabled.
  66093. */
  66094. get: function () {
  66095. return this._depthOfFieldEnabled;
  66096. },
  66097. set: function (enabled) {
  66098. if (this._depthOfFieldEnabled === enabled) {
  66099. return;
  66100. }
  66101. this._depthOfFieldEnabled = enabled;
  66102. this._buildPipeline();
  66103. },
  66104. enumerable: true,
  66105. configurable: true
  66106. });
  66107. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66108. get: function () {
  66109. return this._fxaaEnabled;
  66110. },
  66111. /**
  66112. * If the anti aliasing is enabled.
  66113. */
  66114. set: function (enabled) {
  66115. if (this._fxaaEnabled === enabled) {
  66116. return;
  66117. }
  66118. this._fxaaEnabled = enabled;
  66119. this._buildPipeline();
  66120. },
  66121. enumerable: true,
  66122. configurable: true
  66123. });
  66124. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66125. get: function () {
  66126. return this._imageProcessingEnabled;
  66127. },
  66128. /**
  66129. * If image processing is enabled.
  66130. */
  66131. set: function (enabled) {
  66132. if (this._imageProcessingEnabled === enabled) {
  66133. return;
  66134. }
  66135. this._imageProcessingEnabled = enabled;
  66136. this._buildPipeline();
  66137. },
  66138. enumerable: true,
  66139. configurable: true
  66140. });
  66141. /**
  66142. * Force the compilation of the entire pipeline.
  66143. */
  66144. DefaultRenderingPipeline.prototype.prepare = function () {
  66145. var previousState = this._buildAllowed;
  66146. this._buildAllowed = true;
  66147. this._buildPipeline();
  66148. this._buildAllowed = previousState;
  66149. };
  66150. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66151. var _this = this;
  66152. if (!this._buildAllowed) {
  66153. return;
  66154. }
  66155. var engine = this._scene.getEngine();
  66156. this._disposePostProcesses();
  66157. this._reset();
  66158. if (this.bloomEnabled) {
  66159. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66160. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66161. if (!this._hdr) {
  66162. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66163. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66164. this.highlights.autoClear = false;
  66165. this.highlights.alwaysForcePOT = true;
  66166. }
  66167. 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);
  66168. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66169. this.blurX.alwaysForcePOT = true;
  66170. this.blurX.autoClear = false;
  66171. this.blurX.onActivateObservable.add(function () {
  66172. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66173. _this.blurX.kernel = _this.bloomKernel * dw;
  66174. });
  66175. 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);
  66176. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66177. this.blurY.alwaysForcePOT = true;
  66178. this.blurY.autoClear = false;
  66179. this.blurY.onActivateObservable.add(function () {
  66180. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66181. _this.blurY.kernel = _this.bloomKernel * dh;
  66182. });
  66183. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66184. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66185. this.copyBack.alwaysForcePOT = true;
  66186. if (this._hdr) {
  66187. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66188. var w = this.bloomWeight;
  66189. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66190. }
  66191. else {
  66192. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66193. }
  66194. this.copyBack.autoClear = false;
  66195. }
  66196. if (this.depthOfFieldEnabled) {
  66197. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  66198. this.addEffect(this.depthOfField);
  66199. }
  66200. if (this._imageProcessingEnabled) {
  66201. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66202. if (this._hdr) {
  66203. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66204. }
  66205. else {
  66206. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66207. }
  66208. }
  66209. if (this.fxaaEnabled) {
  66210. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66211. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66212. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66213. }
  66214. else if (this._hdr && this.imageProcessing) {
  66215. this.finalMerge = this.imageProcessing;
  66216. }
  66217. else {
  66218. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66219. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66220. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66221. }
  66222. if (this.bloomEnabled) {
  66223. if (this._hdr) {
  66224. this.copyBack.shareOutputWith(this.blurX);
  66225. if (this.imageProcessing) {
  66226. this.imageProcessing.shareOutputWith(this.pass);
  66227. this.imageProcessing.autoClear = false;
  66228. }
  66229. else if (this.fxaa) {
  66230. this.fxaa.shareOutputWith(this.pass);
  66231. }
  66232. else {
  66233. this.finalMerge.shareOutputWith(this.pass);
  66234. }
  66235. }
  66236. else {
  66237. if (this.fxaa) {
  66238. this.fxaa.shareOutputWith(this.pass);
  66239. }
  66240. else {
  66241. this.finalMerge.shareOutputWith(this.pass);
  66242. }
  66243. }
  66244. }
  66245. if (this._cameras !== null) {
  66246. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66247. }
  66248. };
  66249. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66250. for (var i = 0; i < this._cameras.length; i++) {
  66251. var camera = this._cameras[i];
  66252. if (this.pass) {
  66253. this.pass.dispose(camera);
  66254. }
  66255. if (this.highlights) {
  66256. this.highlights.dispose(camera);
  66257. }
  66258. if (this.blurX) {
  66259. this.blurX.dispose(camera);
  66260. }
  66261. if (this.blurY) {
  66262. this.blurY.dispose(camera);
  66263. }
  66264. if (this.copyBack) {
  66265. this.copyBack.dispose(camera);
  66266. }
  66267. if (this.imageProcessing) {
  66268. this.imageProcessing.dispose(camera);
  66269. }
  66270. if (this.fxaa) {
  66271. this.fxaa.dispose(camera);
  66272. }
  66273. if (this.finalMerge) {
  66274. this.finalMerge.dispose(camera);
  66275. }
  66276. if (this.depthOfField) {
  66277. this.depthOfField.disposeEffects(camera);
  66278. }
  66279. }
  66280. this.pass = null;
  66281. this.highlights = null;
  66282. this.blurX = null;
  66283. this.blurY = null;
  66284. this.copyBack = null;
  66285. this.imageProcessing = null;
  66286. this.fxaa = null;
  66287. this.finalMerge = null;
  66288. this.depthOfField = null;
  66289. };
  66290. /**
  66291. * Dispose of the pipeline and stop all post processes
  66292. */
  66293. DefaultRenderingPipeline.prototype.dispose = function () {
  66294. this._disposePostProcesses();
  66295. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66296. _super.prototype.dispose.call(this);
  66297. };
  66298. /**
  66299. * Serialize the rendering pipeline (Used when exporting)
  66300. * @returns the serialized object
  66301. */
  66302. DefaultRenderingPipeline.prototype.serialize = function () {
  66303. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66304. serializationObject.customType = "DefaultRenderingPipeline";
  66305. return serializationObject;
  66306. };
  66307. /**
  66308. * Parse the serialized pipeline
  66309. * @param source Source pipeline.
  66310. * @param scene The scene to load the pipeline to.
  66311. * @param rootUrl The URL of the serialized pipeline.
  66312. * @returns An instantiated pipeline from the serialized object.
  66313. */
  66314. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66315. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  66316. };
  66317. __decorate([
  66318. BABYLON.serialize()
  66319. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  66320. __decorate([
  66321. BABYLON.serialize()
  66322. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  66323. __decorate([
  66324. BABYLON.serialize()
  66325. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  66326. __decorate([
  66327. BABYLON.serialize()
  66328. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  66329. __decorate([
  66330. BABYLON.serialize()
  66331. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  66332. __decorate([
  66333. BABYLON.serialize()
  66334. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  66335. __decorate([
  66336. BABYLON.serialize()
  66337. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  66338. __decorate([
  66339. BABYLON.serialize()
  66340. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  66341. __decorate([
  66342. BABYLON.serialize()
  66343. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  66344. return DefaultRenderingPipeline;
  66345. }(BABYLON.PostProcessRenderPipeline));
  66346. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  66347. })(BABYLON || (BABYLON = {}));
  66348. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  66349. var BABYLON;
  66350. (function (BABYLON) {
  66351. /**
  66352. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  66353. */
  66354. var GeometryBufferRenderer = /** @class */ (function () {
  66355. /**
  66356. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  66357. * @param scene The scene the buffer belongs to
  66358. * @param ratio How big is the buffer related to the main canvas.
  66359. */
  66360. function GeometryBufferRenderer(scene, ratio) {
  66361. if (ratio === void 0) { ratio = 1; }
  66362. this._enablePosition = false;
  66363. this._scene = scene;
  66364. this._ratio = ratio;
  66365. // Render target
  66366. this._createRenderTargets();
  66367. }
  66368. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  66369. /**
  66370. * Set the render list (meshes to be rendered) used in the G buffer.
  66371. */
  66372. set: function (meshes) {
  66373. this._multiRenderTarget.renderList = meshes;
  66374. },
  66375. enumerable: true,
  66376. configurable: true
  66377. });
  66378. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  66379. /**
  66380. * Gets wether or not G buffer are supported by the running hardware.
  66381. * This requires draw buffer supports
  66382. */
  66383. get: function () {
  66384. return this._multiRenderTarget.isSupported;
  66385. },
  66386. enumerable: true,
  66387. configurable: true
  66388. });
  66389. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  66390. /**
  66391. * Gets wether or not position are enabled for the G buffer.
  66392. */
  66393. get: function () {
  66394. return this._enablePosition;
  66395. },
  66396. /**
  66397. * Sets wether or not position are enabled for the G buffer.
  66398. */
  66399. set: function (enable) {
  66400. this._enablePosition = enable;
  66401. this.dispose();
  66402. this._createRenderTargets();
  66403. },
  66404. enumerable: true,
  66405. configurable: true
  66406. });
  66407. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  66408. /**
  66409. * Gets the scene associated with the buffer.
  66410. */
  66411. get: function () {
  66412. return this._scene;
  66413. },
  66414. enumerable: true,
  66415. configurable: true
  66416. });
  66417. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  66418. /**
  66419. * Gets the ratio used by the buffer during its creation.
  66420. * How big is the buffer related to the main canvas.
  66421. */
  66422. get: function () {
  66423. return this._ratio;
  66424. },
  66425. enumerable: true,
  66426. configurable: true
  66427. });
  66428. /**
  66429. * Checks wether everything is ready to render a submesh to the G buffer.
  66430. * @param subMesh the submesh to check readiness for
  66431. * @param useInstances is the mesh drawn using instance or not
  66432. * @returns true if ready otherwise false
  66433. */
  66434. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  66435. var material = subMesh.getMaterial();
  66436. if (material && material.disableDepthWrite) {
  66437. return false;
  66438. }
  66439. var defines = [];
  66440. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  66441. var mesh = subMesh.getMesh();
  66442. // Alpha test
  66443. if (material && material.needAlphaTesting()) {
  66444. defines.push("#define ALPHATEST");
  66445. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66446. attribs.push(BABYLON.VertexBuffer.UVKind);
  66447. defines.push("#define UV1");
  66448. }
  66449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66450. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66451. defines.push("#define UV2");
  66452. }
  66453. }
  66454. // Buffers
  66455. if (this._enablePosition) {
  66456. defines.push("#define POSITION");
  66457. }
  66458. // Bones
  66459. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66462. if (mesh.numBoneInfluencers > 4) {
  66463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66465. }
  66466. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66467. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66468. }
  66469. else {
  66470. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66471. }
  66472. // Instances
  66473. if (useInstances) {
  66474. defines.push("#define INSTANCES");
  66475. attribs.push("world0");
  66476. attribs.push("world1");
  66477. attribs.push("world2");
  66478. attribs.push("world3");
  66479. }
  66480. // Get correct effect
  66481. var join = defines.join("\n");
  66482. if (this._cachedDefines !== join) {
  66483. this._cachedDefines = join;
  66484. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  66485. }
  66486. return this._effect.isReady();
  66487. };
  66488. /**
  66489. * Gets the current underlying G Buffer.
  66490. * @returns the buffer
  66491. */
  66492. GeometryBufferRenderer.prototype.getGBuffer = function () {
  66493. return this._multiRenderTarget;
  66494. };
  66495. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  66496. /**
  66497. * Gets the number of samples used to render the buffer (anti aliasing).
  66498. */
  66499. get: function () {
  66500. return this._multiRenderTarget.samples;
  66501. },
  66502. /**
  66503. * Sets the number of samples used to render the buffer (anti aliasing).
  66504. */
  66505. set: function (value) {
  66506. this._multiRenderTarget.samples = value;
  66507. },
  66508. enumerable: true,
  66509. configurable: true
  66510. });
  66511. /**
  66512. * Disposes the renderer and frees up associated resources.
  66513. */
  66514. GeometryBufferRenderer.prototype.dispose = function () {
  66515. this.getGBuffer().dispose();
  66516. };
  66517. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  66518. var _this = this;
  66519. var engine = this._scene.getEngine();
  66520. var count = this._enablePosition ? 3 : 2;
  66521. 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 });
  66522. if (!this.isSupported) {
  66523. return;
  66524. }
  66525. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66526. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66527. this._multiRenderTarget.refreshRate = 1;
  66528. this._multiRenderTarget.renderParticles = false;
  66529. this._multiRenderTarget.renderList = null;
  66530. // set default depth value to 1.0 (far away)
  66531. this._multiRenderTarget.onClearObservable.add(function (engine) {
  66532. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  66533. });
  66534. // Custom render function
  66535. var renderSubMesh = function (subMesh) {
  66536. var mesh = subMesh.getRenderingMesh();
  66537. var scene = _this._scene;
  66538. var engine = scene.getEngine();
  66539. var material = subMesh.getMaterial();
  66540. if (!material) {
  66541. return;
  66542. }
  66543. // Culling
  66544. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66545. // Managing instances
  66546. var batch = mesh._getInstancesRenderList(subMesh._id);
  66547. if (batch.mustReturn) {
  66548. return;
  66549. }
  66550. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66551. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  66552. engine.enableEffect(_this._effect);
  66553. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66554. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66555. _this._effect.setMatrix("view", scene.getViewMatrix());
  66556. // Alpha test
  66557. if (material && material.needAlphaTesting()) {
  66558. var alphaTexture = material.getAlphaTestTexture();
  66559. if (alphaTexture) {
  66560. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66561. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66562. }
  66563. }
  66564. // Bones
  66565. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66566. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66567. }
  66568. // Draw
  66569. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66570. }
  66571. };
  66572. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66573. var index;
  66574. if (depthOnlySubMeshes.length) {
  66575. engine.setColorWrite(false);
  66576. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66577. renderSubMesh(depthOnlySubMeshes.data[index]);
  66578. }
  66579. engine.setColorWrite(true);
  66580. }
  66581. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66582. renderSubMesh(opaqueSubMeshes.data[index]);
  66583. }
  66584. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66585. renderSubMesh(alphaTestSubMeshes.data[index]);
  66586. }
  66587. };
  66588. };
  66589. return GeometryBufferRenderer;
  66590. }());
  66591. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  66592. })(BABYLON || (BABYLON = {}));
  66593. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  66594. var BABYLON;
  66595. (function (BABYLON) {
  66596. var RefractionPostProcess = /** @class */ (function (_super) {
  66597. __extends(RefractionPostProcess, _super);
  66598. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  66599. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  66600. _this.color = color;
  66601. _this.depth = depth;
  66602. _this.colorLevel = colorLevel;
  66603. _this.onActivateObservable.add(function (cam) {
  66604. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  66605. });
  66606. _this.onApplyObservable.add(function (effect) {
  66607. effect.setColor3("baseColor", _this.color);
  66608. effect.setFloat("depth", _this.depth);
  66609. effect.setFloat("colorLevel", _this.colorLevel);
  66610. effect.setTexture("refractionSampler", _this._refRexture);
  66611. });
  66612. return _this;
  66613. }
  66614. // Methods
  66615. RefractionPostProcess.prototype.dispose = function (camera) {
  66616. if (this._refRexture) {
  66617. this._refRexture.dispose();
  66618. }
  66619. _super.prototype.dispose.call(this, camera);
  66620. };
  66621. return RefractionPostProcess;
  66622. }(BABYLON.PostProcess));
  66623. BABYLON.RefractionPostProcess = RefractionPostProcess;
  66624. })(BABYLON || (BABYLON = {}));
  66625. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  66626. var BABYLON;
  66627. (function (BABYLON) {
  66628. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  66629. __extends(BlackAndWhitePostProcess, _super);
  66630. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  66631. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  66632. _this.degree = 1;
  66633. _this.onApplyObservable.add(function (effect) {
  66634. effect.setFloat("degree", _this.degree);
  66635. });
  66636. return _this;
  66637. }
  66638. return BlackAndWhitePostProcess;
  66639. }(BABYLON.PostProcess));
  66640. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  66641. })(BABYLON || (BABYLON = {}));
  66642. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  66643. var BABYLON;
  66644. (function (BABYLON) {
  66645. var ConvolutionPostProcess = /** @class */ (function (_super) {
  66646. __extends(ConvolutionPostProcess, _super);
  66647. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  66648. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  66649. _this.kernel = kernel;
  66650. _this.onApply = function (effect) {
  66651. effect.setFloat2("screenSize", _this.width, _this.height);
  66652. effect.setArray("kernel", _this.kernel);
  66653. };
  66654. return _this;
  66655. }
  66656. // Statics
  66657. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  66658. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  66659. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  66660. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  66661. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  66662. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  66663. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  66664. return ConvolutionPostProcess;
  66665. }(BABYLON.PostProcess));
  66666. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  66667. })(BABYLON || (BABYLON = {}));
  66668. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  66669. var BABYLON;
  66670. (function (BABYLON) {
  66671. var FilterPostProcess = /** @class */ (function (_super) {
  66672. __extends(FilterPostProcess, _super);
  66673. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  66674. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  66675. _this.kernelMatrix = kernelMatrix;
  66676. _this.onApply = function (effect) {
  66677. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  66678. };
  66679. return _this;
  66680. }
  66681. return FilterPostProcess;
  66682. }(BABYLON.PostProcess));
  66683. BABYLON.FilterPostProcess = FilterPostProcess;
  66684. })(BABYLON || (BABYLON = {}));
  66685. //# sourceMappingURL=babylon.filterPostProcess.js.map
  66686. var BABYLON;
  66687. (function (BABYLON) {
  66688. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  66689. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  66690. __extends(VolumetricLightScatteringPostProcess, _super);
  66691. /**
  66692. * @constructor
  66693. * @param {string} name - The post-process name
  66694. * @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)
  66695. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  66696. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  66697. * @param {number} samples - The post-process quality, default 100
  66698. * @param {number} samplingMode - The post-process filtering mode
  66699. * @param {BABYLON.Engine} engine - The babylon engine
  66700. * @param {boolean} reusable - If the post-process is reusable
  66701. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  66702. */
  66703. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  66704. if (samples === void 0) { samples = 100; }
  66705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66706. 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;
  66707. _this._screenCoordinates = BABYLON.Vector2.Zero();
  66708. /**
  66709. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  66710. * @type {Vector3}
  66711. */
  66712. _this.customMeshPosition = BABYLON.Vector3.Zero();
  66713. /**
  66714. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  66715. * @type {boolean}
  66716. */
  66717. _this.useCustomMeshPosition = false;
  66718. /**
  66719. * If the post-process should inverse the light scattering direction
  66720. * @type {boolean}
  66721. */
  66722. _this.invert = true;
  66723. /**
  66724. * Array containing the excluded meshes not rendered in the internal pass
  66725. */
  66726. _this.excludedMeshes = new Array();
  66727. /**
  66728. * Controls the overall intensity of the post-process
  66729. * @type {number}
  66730. */
  66731. _this.exposure = 0.3;
  66732. /**
  66733. * Dissipates each sample's contribution in range [0, 1]
  66734. * @type {number}
  66735. */
  66736. _this.decay = 0.96815;
  66737. /**
  66738. * Controls the overall intensity of each sample
  66739. * @type {number}
  66740. */
  66741. _this.weight = 0.58767;
  66742. /**
  66743. * Controls the density of each sample
  66744. * @type {number}
  66745. */
  66746. _this.density = 0.926;
  66747. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  66748. engine = scene.getEngine();
  66749. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  66750. // Configure mesh
  66751. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  66752. // Configure
  66753. _this._createPass(scene, ratio.passRatio || ratio);
  66754. _this.onActivate = function (camera) {
  66755. if (!_this.isSupported) {
  66756. _this.dispose(camera);
  66757. }
  66758. _this.onActivate = null;
  66759. };
  66760. _this.onApplyObservable.add(function (effect) {
  66761. _this._updateMeshScreenCoordinates(scene);
  66762. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  66763. effect.setFloat("exposure", _this.exposure);
  66764. effect.setFloat("decay", _this.decay);
  66765. effect.setFloat("weight", _this.weight);
  66766. effect.setFloat("density", _this.density);
  66767. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  66768. });
  66769. return _this;
  66770. }
  66771. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  66772. get: function () {
  66773. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  66774. return false;
  66775. },
  66776. set: function (useDiffuseColor) {
  66777. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  66778. },
  66779. enumerable: true,
  66780. configurable: true
  66781. });
  66782. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  66783. return "VolumetricLightScatteringPostProcess";
  66784. };
  66785. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  66786. var mesh = subMesh.getMesh();
  66787. // Render this.mesh as default
  66788. if (mesh === this.mesh && mesh.material) {
  66789. return mesh.material.isReady(mesh);
  66790. }
  66791. var defines = [];
  66792. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66793. var material = subMesh.getMaterial();
  66794. // Alpha test
  66795. if (material) {
  66796. if (material.needAlphaTesting()) {
  66797. defines.push("#define ALPHATEST");
  66798. }
  66799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66800. attribs.push(BABYLON.VertexBuffer.UVKind);
  66801. defines.push("#define UV1");
  66802. }
  66803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66804. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66805. defines.push("#define UV2");
  66806. }
  66807. }
  66808. // Bones
  66809. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66810. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66811. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66812. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66813. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  66814. }
  66815. else {
  66816. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66817. }
  66818. // Instances
  66819. if (useInstances) {
  66820. defines.push("#define INSTANCES");
  66821. attribs.push("world0");
  66822. attribs.push("world1");
  66823. attribs.push("world2");
  66824. attribs.push("world3");
  66825. }
  66826. // Get correct effect
  66827. var join = defines.join("\n");
  66828. if (this._cachedDefines !== join) {
  66829. this._cachedDefines = join;
  66830. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  66831. }
  66832. return this._volumetricLightScatteringPass.isReady();
  66833. };
  66834. /**
  66835. * Sets the new light position for light scattering effect
  66836. * @param {BABYLON.Vector3} The new custom light position
  66837. */
  66838. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  66839. this.customMeshPosition = position;
  66840. };
  66841. /**
  66842. * Returns the light position for light scattering effect
  66843. * @return {BABYLON.Vector3} The custom light position
  66844. */
  66845. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  66846. return this.customMeshPosition;
  66847. };
  66848. /**
  66849. * Disposes the internal assets and detaches the post-process from the camera
  66850. */
  66851. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  66852. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  66853. if (rttIndex !== -1) {
  66854. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  66855. }
  66856. this._volumetricLightScatteringRTT.dispose();
  66857. _super.prototype.dispose.call(this, camera);
  66858. };
  66859. /**
  66860. * Returns the render target texture used by the post-process
  66861. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  66862. */
  66863. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  66864. return this._volumetricLightScatteringRTT;
  66865. };
  66866. // Private methods
  66867. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  66868. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  66869. return true;
  66870. }
  66871. return false;
  66872. };
  66873. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  66874. var _this = this;
  66875. var engine = scene.getEngine();
  66876. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66877. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66878. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66879. this._volumetricLightScatteringRTT.renderList = null;
  66880. this._volumetricLightScatteringRTT.renderParticles = false;
  66881. var camera = this.getCamera();
  66882. if (camera) {
  66883. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  66884. }
  66885. else {
  66886. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  66887. }
  66888. // Custom render function for submeshes
  66889. var renderSubMesh = function (subMesh) {
  66890. var mesh = subMesh.getRenderingMesh();
  66891. if (_this._meshExcluded(mesh)) {
  66892. return;
  66893. }
  66894. var material = subMesh.getMaterial();
  66895. if (!material) {
  66896. return;
  66897. }
  66898. var scene = mesh.getScene();
  66899. var engine = scene.getEngine();
  66900. // Culling
  66901. engine.setState(material.backFaceCulling);
  66902. // Managing instances
  66903. var batch = mesh._getInstancesRenderList(subMesh._id);
  66904. if (batch.mustReturn) {
  66905. return;
  66906. }
  66907. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66908. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  66909. var effect = _this._volumetricLightScatteringPass;
  66910. if (mesh === _this.mesh) {
  66911. if (subMesh.effect) {
  66912. effect = subMesh.effect;
  66913. }
  66914. else {
  66915. effect = material.getEffect();
  66916. }
  66917. }
  66918. engine.enableEffect(effect);
  66919. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  66920. if (mesh === _this.mesh) {
  66921. material.bind(mesh.getWorldMatrix(), mesh);
  66922. }
  66923. else {
  66924. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  66925. // Alpha test
  66926. if (material && material.needAlphaTesting()) {
  66927. var alphaTexture = material.getAlphaTestTexture();
  66928. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  66929. if (alphaTexture) {
  66930. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66931. }
  66932. }
  66933. // Bones
  66934. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66935. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66936. }
  66937. }
  66938. // Draw
  66939. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  66940. }
  66941. };
  66942. // Render target texture callbacks
  66943. var savedSceneClearColor;
  66944. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  66945. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  66946. savedSceneClearColor = scene.clearColor;
  66947. scene.clearColor = sceneClearColor;
  66948. });
  66949. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  66950. scene.clearColor = savedSceneClearColor;
  66951. });
  66952. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66953. var engine = scene.getEngine();
  66954. var index;
  66955. if (depthOnlySubMeshes.length) {
  66956. engine.setColorWrite(false);
  66957. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66958. renderSubMesh(depthOnlySubMeshes.data[index]);
  66959. }
  66960. engine.setColorWrite(true);
  66961. }
  66962. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66963. renderSubMesh(opaqueSubMeshes.data[index]);
  66964. }
  66965. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66966. renderSubMesh(alphaTestSubMeshes.data[index]);
  66967. }
  66968. if (transparentSubMeshes.length) {
  66969. // Sort sub meshes
  66970. for (index = 0; index < transparentSubMeshes.length; index++) {
  66971. var submesh = transparentSubMeshes.data[index];
  66972. var boundingInfo = submesh.getBoundingInfo();
  66973. if (boundingInfo && scene.activeCamera) {
  66974. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  66975. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  66976. }
  66977. }
  66978. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  66979. sortedArray.sort(function (a, b) {
  66980. // Alpha index first
  66981. if (a._alphaIndex > b._alphaIndex) {
  66982. return 1;
  66983. }
  66984. if (a._alphaIndex < b._alphaIndex) {
  66985. return -1;
  66986. }
  66987. // Then distance to camera
  66988. if (a._distanceToCamera < b._distanceToCamera) {
  66989. return 1;
  66990. }
  66991. if (a._distanceToCamera > b._distanceToCamera) {
  66992. return -1;
  66993. }
  66994. return 0;
  66995. });
  66996. // Render sub meshes
  66997. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  66998. for (index = 0; index < sortedArray.length; index++) {
  66999. renderSubMesh(sortedArray[index]);
  67000. }
  67001. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67002. }
  67003. };
  67004. };
  67005. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67006. var transform = scene.getTransformMatrix();
  67007. var meshPosition;
  67008. if (this.useCustomMeshPosition) {
  67009. meshPosition = this.customMeshPosition;
  67010. }
  67011. else if (this.attachedNode) {
  67012. meshPosition = this.attachedNode.position;
  67013. }
  67014. else {
  67015. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67016. }
  67017. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67018. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67019. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67020. if (this.invert)
  67021. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67022. };
  67023. // Static methods
  67024. /**
  67025. * Creates a default mesh for the Volumeric Light Scattering post-process
  67026. * @param {string} The mesh name
  67027. * @param {BABYLON.Scene} The scene where to create the mesh
  67028. * @return {BABYLON.Mesh} the default mesh
  67029. */
  67030. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67031. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67032. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67033. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67034. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67035. mesh.material = material;
  67036. return mesh;
  67037. };
  67038. __decorate([
  67039. BABYLON.serializeAsVector3()
  67040. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67041. __decorate([
  67042. BABYLON.serialize()
  67043. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67044. __decorate([
  67045. BABYLON.serialize()
  67046. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67047. __decorate([
  67048. BABYLON.serializeAsMeshReference()
  67049. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67050. __decorate([
  67051. BABYLON.serialize()
  67052. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67053. __decorate([
  67054. BABYLON.serialize()
  67055. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67056. __decorate([
  67057. BABYLON.serialize()
  67058. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67059. __decorate([
  67060. BABYLON.serialize()
  67061. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67062. __decorate([
  67063. BABYLON.serialize()
  67064. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67065. return VolumetricLightScatteringPostProcess;
  67066. }(BABYLON.PostProcess));
  67067. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67068. })(BABYLON || (BABYLON = {}));
  67069. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67070. //
  67071. // This post-process allows the modification of rendered colors by using
  67072. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67073. //
  67074. // The object needs to be provided an url to a texture containing the color
  67075. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67076. // Use an image editing software to tweak the LUT to match your needs.
  67077. //
  67078. // For an example of a color LUT, see here:
  67079. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67080. // For explanations on color grading, see here:
  67081. // http://udn.epicgames.com/Three/ColorGrading.html
  67082. //
  67083. var BABYLON;
  67084. (function (BABYLON) {
  67085. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67086. __extends(ColorCorrectionPostProcess, _super);
  67087. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67088. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67089. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67090. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67091. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67092. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67093. _this.onApply = function (effect) {
  67094. effect.setTexture("colorTable", _this._colorTableTexture);
  67095. };
  67096. return _this;
  67097. }
  67098. return ColorCorrectionPostProcess;
  67099. }(BABYLON.PostProcess));
  67100. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67101. })(BABYLON || (BABYLON = {}));
  67102. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67103. var BABYLON;
  67104. (function (BABYLON) {
  67105. var TonemappingOperator;
  67106. (function (TonemappingOperator) {
  67107. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67108. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67109. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67110. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67111. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67112. ;
  67113. var TonemapPostProcess = /** @class */ (function (_super) {
  67114. __extends(TonemapPostProcess, _super);
  67115. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67117. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67118. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67119. _this._operator = _operator;
  67120. _this.exposureAdjustment = exposureAdjustment;
  67121. var defines = "#define ";
  67122. if (_this._operator === TonemappingOperator.Hable)
  67123. defines += "HABLE_TONEMAPPING";
  67124. else if (_this._operator === TonemappingOperator.Reinhard)
  67125. defines += "REINHARD_TONEMAPPING";
  67126. else if (_this._operator === TonemappingOperator.HejiDawson)
  67127. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67128. else if (_this._operator === TonemappingOperator.Photographic)
  67129. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67130. //sadly a second call to create the effect.
  67131. _this.updateEffect(defines);
  67132. _this.onApply = function (effect) {
  67133. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67134. };
  67135. return _this;
  67136. }
  67137. return TonemapPostProcess;
  67138. }(BABYLON.PostProcess));
  67139. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67140. })(BABYLON || (BABYLON = {}));
  67141. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67142. var BABYLON;
  67143. (function (BABYLON) {
  67144. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67145. __extends(DisplayPassPostProcess, _super);
  67146. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67147. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67148. }
  67149. return DisplayPassPostProcess;
  67150. }(BABYLON.PostProcess));
  67151. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67152. })(BABYLON || (BABYLON = {}));
  67153. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67154. var BABYLON;
  67155. (function (BABYLON) {
  67156. var HighlightsPostProcess = /** @class */ (function (_super) {
  67157. __extends(HighlightsPostProcess, _super);
  67158. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67159. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67160. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67161. }
  67162. return HighlightsPostProcess;
  67163. }(BABYLON.PostProcess));
  67164. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67165. })(BABYLON || (BABYLON = {}));
  67166. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67167. var BABYLON;
  67168. (function (BABYLON) {
  67169. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67170. __extends(ImageProcessingPostProcess, _super);
  67171. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67172. if (camera === void 0) { camera = null; }
  67173. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67174. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67175. _this._fromLinearSpace = true;
  67176. /**
  67177. * Defines cache preventing GC.
  67178. */
  67179. _this._defines = {
  67180. IMAGEPROCESSING: false,
  67181. VIGNETTE: false,
  67182. VIGNETTEBLENDMODEMULTIPLY: false,
  67183. VIGNETTEBLENDMODEOPAQUE: false,
  67184. TONEMAPPING: false,
  67185. CONTRAST: false,
  67186. COLORCURVES: false,
  67187. COLORGRADING: false,
  67188. COLORGRADING3D: false,
  67189. FROMLINEARSPACE: false,
  67190. SAMPLER3DGREENDEPTH: false,
  67191. SAMPLER3DBGRMAP: false,
  67192. IMAGEPROCESSINGPOSTPROCESS: false,
  67193. EXPOSURE: false,
  67194. };
  67195. // Setup the configuration as forced by the constructor. This would then not force the
  67196. // scene materials output in linear space and let untouched the default forward pass.
  67197. if (imageProcessingConfiguration) {
  67198. imageProcessingConfiguration.applyByPostProcess = true;
  67199. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67200. // This will cause the shader to be compiled
  67201. _this.fromLinearSpace = false;
  67202. }
  67203. else {
  67204. _this._attachImageProcessingConfiguration(null, true);
  67205. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67206. }
  67207. _this.onApply = function (effect) {
  67208. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67209. };
  67210. return _this;
  67211. }
  67212. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67213. /**
  67214. * Gets the image processing configuration used either in this material.
  67215. */
  67216. get: function () {
  67217. return this._imageProcessingConfiguration;
  67218. },
  67219. /**
  67220. * Sets the Default image processing configuration used either in the this material.
  67221. *
  67222. * If sets to null, the scene one is in use.
  67223. */
  67224. set: function (value) {
  67225. this._attachImageProcessingConfiguration(value);
  67226. },
  67227. enumerable: true,
  67228. configurable: true
  67229. });
  67230. /**
  67231. * Attaches a new image processing configuration to the PBR Material.
  67232. * @param configuration
  67233. */
  67234. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67235. var _this = this;
  67236. if (doNotBuild === void 0) { doNotBuild = false; }
  67237. if (configuration === this._imageProcessingConfiguration) {
  67238. return;
  67239. }
  67240. // Detaches observer.
  67241. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67242. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67243. }
  67244. // Pick the scene configuration if needed.
  67245. if (!configuration) {
  67246. var scene = null;
  67247. var engine = this.getEngine();
  67248. var camera = this.getCamera();
  67249. if (camera) {
  67250. scene = camera.getScene();
  67251. }
  67252. else if (engine && engine.scenes) {
  67253. var scenes = engine.scenes;
  67254. scene = scenes[scenes.length - 1];
  67255. }
  67256. else {
  67257. scene = BABYLON.Engine.LastCreatedScene;
  67258. }
  67259. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67260. }
  67261. else {
  67262. this._imageProcessingConfiguration = configuration;
  67263. }
  67264. // Attaches observer.
  67265. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  67266. _this._updateParameters();
  67267. });
  67268. // Ensure the effect will be rebuilt.
  67269. if (!doNotBuild) {
  67270. this._updateParameters();
  67271. }
  67272. };
  67273. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  67274. /**
  67275. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67276. */
  67277. get: function () {
  67278. return this.imageProcessingConfiguration.colorCurves;
  67279. },
  67280. /**
  67281. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67282. */
  67283. set: function (value) {
  67284. this.imageProcessingConfiguration.colorCurves = value;
  67285. },
  67286. enumerable: true,
  67287. configurable: true
  67288. });
  67289. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  67290. /**
  67291. * Gets wether the color curves effect is enabled.
  67292. */
  67293. get: function () {
  67294. return this.imageProcessingConfiguration.colorCurvesEnabled;
  67295. },
  67296. /**
  67297. * Sets wether the color curves effect is enabled.
  67298. */
  67299. set: function (value) {
  67300. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  67301. },
  67302. enumerable: true,
  67303. configurable: true
  67304. });
  67305. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  67306. /**
  67307. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67308. */
  67309. get: function () {
  67310. return this.imageProcessingConfiguration.colorGradingTexture;
  67311. },
  67312. /**
  67313. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67314. */
  67315. set: function (value) {
  67316. this.imageProcessingConfiguration.colorGradingTexture = value;
  67317. },
  67318. enumerable: true,
  67319. configurable: true
  67320. });
  67321. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  67322. /**
  67323. * Gets wether the color grading effect is enabled.
  67324. */
  67325. get: function () {
  67326. return this.imageProcessingConfiguration.colorGradingEnabled;
  67327. },
  67328. /**
  67329. * Gets wether the color grading effect is enabled.
  67330. */
  67331. set: function (value) {
  67332. this.imageProcessingConfiguration.colorGradingEnabled = value;
  67333. },
  67334. enumerable: true,
  67335. configurable: true
  67336. });
  67337. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  67338. /**
  67339. * Gets exposure used in the effect.
  67340. */
  67341. get: function () {
  67342. return this.imageProcessingConfiguration.exposure;
  67343. },
  67344. /**
  67345. * Sets exposure used in the effect.
  67346. */
  67347. set: function (value) {
  67348. this.imageProcessingConfiguration.exposure = value;
  67349. },
  67350. enumerable: true,
  67351. configurable: true
  67352. });
  67353. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  67354. /**
  67355. * Gets wether tonemapping is enabled or not.
  67356. */
  67357. get: function () {
  67358. return this._imageProcessingConfiguration.toneMappingEnabled;
  67359. },
  67360. /**
  67361. * Sets wether tonemapping is enabled or not
  67362. */
  67363. set: function (value) {
  67364. this._imageProcessingConfiguration.toneMappingEnabled = value;
  67365. },
  67366. enumerable: true,
  67367. configurable: true
  67368. });
  67369. ;
  67370. ;
  67371. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  67372. /**
  67373. * Gets contrast used in the effect.
  67374. */
  67375. get: function () {
  67376. return this.imageProcessingConfiguration.contrast;
  67377. },
  67378. /**
  67379. * Sets contrast used in the effect.
  67380. */
  67381. set: function (value) {
  67382. this.imageProcessingConfiguration.contrast = value;
  67383. },
  67384. enumerable: true,
  67385. configurable: true
  67386. });
  67387. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  67388. /**
  67389. * Gets Vignette stretch size.
  67390. */
  67391. get: function () {
  67392. return this.imageProcessingConfiguration.vignetteStretch;
  67393. },
  67394. /**
  67395. * Sets Vignette stretch size.
  67396. */
  67397. set: function (value) {
  67398. this.imageProcessingConfiguration.vignetteStretch = value;
  67399. },
  67400. enumerable: true,
  67401. configurable: true
  67402. });
  67403. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  67404. /**
  67405. * Gets Vignette centre X Offset.
  67406. */
  67407. get: function () {
  67408. return this.imageProcessingConfiguration.vignetteCentreX;
  67409. },
  67410. /**
  67411. * Sets Vignette centre X Offset.
  67412. */
  67413. set: function (value) {
  67414. this.imageProcessingConfiguration.vignetteCentreX = value;
  67415. },
  67416. enumerable: true,
  67417. configurable: true
  67418. });
  67419. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  67420. /**
  67421. * Gets Vignette centre Y Offset.
  67422. */
  67423. get: function () {
  67424. return this.imageProcessingConfiguration.vignetteCentreY;
  67425. },
  67426. /**
  67427. * Sets Vignette centre Y Offset.
  67428. */
  67429. set: function (value) {
  67430. this.imageProcessingConfiguration.vignetteCentreY = value;
  67431. },
  67432. enumerable: true,
  67433. configurable: true
  67434. });
  67435. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  67436. /**
  67437. * Gets Vignette weight or intensity of the vignette effect.
  67438. */
  67439. get: function () {
  67440. return this.imageProcessingConfiguration.vignetteWeight;
  67441. },
  67442. /**
  67443. * Sets Vignette weight or intensity of the vignette effect.
  67444. */
  67445. set: function (value) {
  67446. this.imageProcessingConfiguration.vignetteWeight = value;
  67447. },
  67448. enumerable: true,
  67449. configurable: true
  67450. });
  67451. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  67452. /**
  67453. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67454. * if vignetteEnabled is set to true.
  67455. */
  67456. get: function () {
  67457. return this.imageProcessingConfiguration.vignetteColor;
  67458. },
  67459. /**
  67460. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67461. * if vignetteEnabled is set to true.
  67462. */
  67463. set: function (value) {
  67464. this.imageProcessingConfiguration.vignetteColor = value;
  67465. },
  67466. enumerable: true,
  67467. configurable: true
  67468. });
  67469. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  67470. /**
  67471. * Gets Camera field of view used by the Vignette effect.
  67472. */
  67473. get: function () {
  67474. return this.imageProcessingConfiguration.vignetteCameraFov;
  67475. },
  67476. /**
  67477. * Sets Camera field of view used by the Vignette effect.
  67478. */
  67479. set: function (value) {
  67480. this.imageProcessingConfiguration.vignetteCameraFov = value;
  67481. },
  67482. enumerable: true,
  67483. configurable: true
  67484. });
  67485. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  67486. /**
  67487. * Gets the vignette blend mode allowing different kind of effect.
  67488. */
  67489. get: function () {
  67490. return this.imageProcessingConfiguration.vignetteBlendMode;
  67491. },
  67492. /**
  67493. * Sets the vignette blend mode allowing different kind of effect.
  67494. */
  67495. set: function (value) {
  67496. this.imageProcessingConfiguration.vignetteBlendMode = value;
  67497. },
  67498. enumerable: true,
  67499. configurable: true
  67500. });
  67501. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  67502. /**
  67503. * Gets wether the vignette effect is enabled.
  67504. */
  67505. get: function () {
  67506. return this.imageProcessingConfiguration.vignetteEnabled;
  67507. },
  67508. /**
  67509. * Sets wether the vignette effect is enabled.
  67510. */
  67511. set: function (value) {
  67512. this.imageProcessingConfiguration.vignetteEnabled = value;
  67513. },
  67514. enumerable: true,
  67515. configurable: true
  67516. });
  67517. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  67518. /**
  67519. * Gets wether the input of the processing is in Gamma or Linear Space.
  67520. */
  67521. get: function () {
  67522. return this._fromLinearSpace;
  67523. },
  67524. /**
  67525. * Sets wether the input of the processing is in Gamma or Linear Space.
  67526. */
  67527. set: function (value) {
  67528. if (this._fromLinearSpace === value) {
  67529. return;
  67530. }
  67531. this._fromLinearSpace = value;
  67532. this._updateParameters();
  67533. },
  67534. enumerable: true,
  67535. configurable: true
  67536. });
  67537. ImageProcessingPostProcess.prototype.getClassName = function () {
  67538. return "ImageProcessingPostProcess";
  67539. };
  67540. ImageProcessingPostProcess.prototype._updateParameters = function () {
  67541. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  67542. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  67543. var defines = "";
  67544. for (var define in this._defines) {
  67545. if (this._defines[define]) {
  67546. defines += "#define " + define + ";\r\n";
  67547. }
  67548. }
  67549. var samplers = ["textureSampler"];
  67550. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  67551. var uniforms = ["scale"];
  67552. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  67553. this.updateEffect(defines, uniforms, samplers);
  67554. };
  67555. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  67556. _super.prototype.dispose.call(this, camera);
  67557. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67558. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67559. }
  67560. this.imageProcessingConfiguration.applyByPostProcess = false;
  67561. };
  67562. __decorate([
  67563. BABYLON.serialize()
  67564. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  67565. return ImageProcessingPostProcess;
  67566. }(BABYLON.PostProcess));
  67567. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  67568. })(BABYLON || (BABYLON = {}));
  67569. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  67570. var BABYLON;
  67571. (function (BABYLON) {
  67572. /**
  67573. * The Blur Post Process which blurs an image based on a kernel and direction.
  67574. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  67575. */
  67576. var BlurPostProcess = /** @class */ (function (_super) {
  67577. __extends(BlurPostProcess, _super);
  67578. /**
  67579. * Creates a new instance of @see BlurPostProcess
  67580. * @param name The name of the effect.
  67581. * @param direction The direction in which to blur the image.
  67582. * @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.
  67583. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  67584. * @param camera The camera to apply the render pass to.
  67585. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67586. * @param engine The engine which the post process will be applied. (default: current engine)
  67587. * @param reusable If the post process can be reused on the same frame. (default: false)
  67588. * @param textureType Type of textures used when performing the post process. (default: 0)
  67589. */
  67590. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  67591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67592. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67593. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  67594. _this.direction = direction;
  67595. _this._packedFloat = false;
  67596. _this._staticDefines = "";
  67597. _this.onApplyObservable.add(function (effect) {
  67598. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  67599. });
  67600. _this.kernel = kernel;
  67601. return _this;
  67602. }
  67603. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  67604. /**
  67605. * Gets the length in pixels of the blur sample region
  67606. */
  67607. get: function () {
  67608. return this._idealKernel;
  67609. },
  67610. /**
  67611. * Sets the length in pixels of the blur sample region
  67612. */
  67613. set: function (v) {
  67614. if (this._idealKernel === v) {
  67615. return;
  67616. }
  67617. v = Math.max(v, 1);
  67618. this._idealKernel = v;
  67619. this._kernel = this._nearestBestKernel(v);
  67620. this._updateParameters();
  67621. },
  67622. enumerable: true,
  67623. configurable: true
  67624. });
  67625. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  67626. /**
  67627. * Gets wether or not the blur is unpacking/repacking floats
  67628. */
  67629. get: function () {
  67630. return this._packedFloat;
  67631. },
  67632. /**
  67633. * Sets wether or not the blur needs to unpack/repack floats
  67634. */
  67635. set: function (v) {
  67636. if (this._packedFloat === v) {
  67637. return;
  67638. }
  67639. this._packedFloat = v;
  67640. this._updateParameters();
  67641. },
  67642. enumerable: true,
  67643. configurable: true
  67644. });
  67645. BlurPostProcess.prototype._updateParameters = function () {
  67646. // Generate sampling offsets and weights
  67647. var N = this._kernel;
  67648. var centerIndex = (N - 1) / 2;
  67649. // Generate Gaussian sampling weights over kernel
  67650. var offsets = [];
  67651. var weights = [];
  67652. var totalWeight = 0;
  67653. for (var i = 0; i < N; i++) {
  67654. var u = i / (N - 1);
  67655. var w = this._gaussianWeight(u * 2.0 - 1);
  67656. offsets[i] = (i - centerIndex);
  67657. weights[i] = w;
  67658. totalWeight += w;
  67659. }
  67660. // Normalize weights
  67661. for (var i = 0; i < weights.length; i++) {
  67662. weights[i] /= totalWeight;
  67663. }
  67664. // Optimize: combine samples to take advantage of hardware linear sampling
  67665. // Walk from left to center, combining pairs (symmetrically)
  67666. var linearSamplingWeights = [];
  67667. var linearSamplingOffsets = [];
  67668. var linearSamplingMap = [];
  67669. for (var i = 0; i <= centerIndex; i += 2) {
  67670. var j = Math.min(i + 1, Math.floor(centerIndex));
  67671. var singleCenterSample = i === j;
  67672. if (singleCenterSample) {
  67673. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  67674. }
  67675. else {
  67676. var sharedCell = j === centerIndex;
  67677. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  67678. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  67679. if (offsetLinear === 0) {
  67680. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  67681. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  67682. }
  67683. else {
  67684. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  67685. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  67686. }
  67687. }
  67688. }
  67689. for (var i = 0; i < linearSamplingMap.length; i++) {
  67690. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  67691. linearSamplingWeights[i] = linearSamplingMap[i].w;
  67692. }
  67693. // Replace with optimized
  67694. offsets = linearSamplingOffsets;
  67695. weights = linearSamplingWeights;
  67696. // Generate shaders
  67697. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  67698. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  67699. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  67700. var defines = "";
  67701. defines += this._staticDefines;
  67702. for (var i = 0; i < varyingCount; i++) {
  67703. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  67704. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  67705. }
  67706. var depCount = 0;
  67707. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  67708. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  67709. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  67710. depCount++;
  67711. }
  67712. if (this.packedFloat) {
  67713. defines += "#define PACKEDFLOAT 1";
  67714. }
  67715. this.updateEffect(defines, null, null, {
  67716. varyingCount: varyingCount,
  67717. depCount: depCount
  67718. });
  67719. };
  67720. /**
  67721. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  67722. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  67723. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  67724. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  67725. * The gaps between physical kernels are compensated for in the weighting of the samples
  67726. * @param idealKernel Ideal blur kernel.
  67727. * @return Nearest best kernel.
  67728. */
  67729. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  67730. var v = Math.round(idealKernel);
  67731. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  67732. var k = _a[_i];
  67733. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  67734. return Math.max(k, 3);
  67735. }
  67736. }
  67737. return Math.max(v, 3);
  67738. };
  67739. /**
  67740. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  67741. * @param x The point on the Gaussian distribution to sample.
  67742. * @return the value of the Gaussian function at x.
  67743. */
  67744. BlurPostProcess.prototype._gaussianWeight = function (x) {
  67745. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  67746. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  67747. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  67748. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  67749. // truncated at around 1.3% of peak strength.
  67750. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  67751. var sigma = (1 / 3);
  67752. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  67753. var exponent = -((x * x) / (2.0 * sigma * sigma));
  67754. var weight = (1.0 / denominator) * Math.exp(exponent);
  67755. return weight;
  67756. };
  67757. /**
  67758. * Generates a string that can be used as a floating point number in GLSL.
  67759. * @param x Value to print.
  67760. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  67761. * @return GLSL float string.
  67762. */
  67763. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  67764. if (decimalFigures === void 0) { decimalFigures = 8; }
  67765. return x.toFixed(decimalFigures).replace(/0+$/, '');
  67766. };
  67767. return BlurPostProcess;
  67768. }(BABYLON.PostProcess));
  67769. BABYLON.BlurPostProcess = BlurPostProcess;
  67770. })(BABYLON || (BABYLON = {}));
  67771. //# sourceMappingURL=babylon.blurPostProcess.js.map
  67772. var BABYLON;
  67773. (function (BABYLON) {
  67774. var Bone = /** @class */ (function (_super) {
  67775. __extends(Bone, _super);
  67776. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  67777. if (parentBone === void 0) { parentBone = null; }
  67778. if (localMatrix === void 0) { localMatrix = null; }
  67779. if (restPose === void 0) { restPose = null; }
  67780. if (baseMatrix === void 0) { baseMatrix = null; }
  67781. if (index === void 0) { index = null; }
  67782. var _this = _super.call(this, name, skeleton.getScene()) || this;
  67783. _this.name = name;
  67784. _this.children = new Array();
  67785. _this.animations = new Array();
  67786. // Set this value to map this bone to a different index in the transform matrices.
  67787. // Set this value to -1 to exclude the bone from the transform matrices.
  67788. _this._index = null;
  67789. _this._worldTransform = new BABYLON.Matrix();
  67790. _this._absoluteTransform = new BABYLON.Matrix();
  67791. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  67792. _this._scaleMatrix = BABYLON.Matrix.Identity();
  67793. _this._scaleVector = BABYLON.Vector3.One();
  67794. _this._negateScaleChildren = BABYLON.Vector3.One();
  67795. _this._scalingDeterminant = 1;
  67796. _this._skeleton = skeleton;
  67797. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  67798. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  67799. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  67800. _this._index = index;
  67801. skeleton.bones.push(_this);
  67802. _this.setParent(parentBone, false);
  67803. _this._updateDifferenceMatrix();
  67804. return _this;
  67805. }
  67806. Object.defineProperty(Bone.prototype, "_matrix", {
  67807. get: function () {
  67808. return this._localMatrix;
  67809. },
  67810. set: function (val) {
  67811. if (this._localMatrix) {
  67812. this._localMatrix.copyFrom(val);
  67813. }
  67814. else {
  67815. this._localMatrix = val;
  67816. }
  67817. },
  67818. enumerable: true,
  67819. configurable: true
  67820. });
  67821. // Members
  67822. Bone.prototype.getSkeleton = function () {
  67823. return this._skeleton;
  67824. };
  67825. Bone.prototype.getParent = function () {
  67826. return this._parent;
  67827. };
  67828. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  67829. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  67830. if (this._parent === parent) {
  67831. return;
  67832. }
  67833. if (this._parent) {
  67834. var index = this._parent.children.indexOf(this);
  67835. if (index !== -1) {
  67836. this._parent.children.splice(index, 1);
  67837. }
  67838. }
  67839. this._parent = parent;
  67840. if (this._parent) {
  67841. this._parent.children.push(this);
  67842. }
  67843. if (updateDifferenceMatrix) {
  67844. this._updateDifferenceMatrix();
  67845. }
  67846. };
  67847. Bone.prototype.getLocalMatrix = function () {
  67848. return this._localMatrix;
  67849. };
  67850. Bone.prototype.getBaseMatrix = function () {
  67851. return this._baseMatrix;
  67852. };
  67853. Bone.prototype.getRestPose = function () {
  67854. return this._restPose;
  67855. };
  67856. Bone.prototype.returnToRest = function () {
  67857. this.updateMatrix(this._restPose.clone());
  67858. };
  67859. Bone.prototype.getWorldMatrix = function () {
  67860. return this._worldTransform;
  67861. };
  67862. Bone.prototype.getInvertedAbsoluteTransform = function () {
  67863. return this._invertedAbsoluteTransform;
  67864. };
  67865. Bone.prototype.getAbsoluteTransform = function () {
  67866. return this._absoluteTransform;
  67867. };
  67868. Object.defineProperty(Bone.prototype, "position", {
  67869. // Properties (matches AbstractMesh properties)
  67870. get: function () {
  67871. return this.getPosition();
  67872. },
  67873. set: function (newPosition) {
  67874. this.setPosition(newPosition);
  67875. },
  67876. enumerable: true,
  67877. configurable: true
  67878. });
  67879. Object.defineProperty(Bone.prototype, "rotation", {
  67880. get: function () {
  67881. return this.getRotation();
  67882. },
  67883. set: function (newRotation) {
  67884. this.setRotation(newRotation);
  67885. },
  67886. enumerable: true,
  67887. configurable: true
  67888. });
  67889. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  67890. get: function () {
  67891. return this.getRotationQuaternion();
  67892. },
  67893. set: function (newRotation) {
  67894. this.setRotationQuaternion(newRotation);
  67895. },
  67896. enumerable: true,
  67897. configurable: true
  67898. });
  67899. Object.defineProperty(Bone.prototype, "scaling", {
  67900. get: function () {
  67901. return this.getScale();
  67902. },
  67903. set: function (newScaling) {
  67904. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  67905. },
  67906. enumerable: true,
  67907. configurable: true
  67908. });
  67909. // Methods
  67910. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  67911. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  67912. this._baseMatrix = matrix.clone();
  67913. this._localMatrix = matrix.clone();
  67914. this._skeleton._markAsDirty();
  67915. if (updateDifferenceMatrix) {
  67916. this._updateDifferenceMatrix();
  67917. }
  67918. };
  67919. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  67920. if (!rootMatrix) {
  67921. rootMatrix = this._baseMatrix;
  67922. }
  67923. if (this._parent) {
  67924. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  67925. }
  67926. else {
  67927. this._absoluteTransform.copyFrom(rootMatrix);
  67928. }
  67929. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  67930. for (var index = 0; index < this.children.length; index++) {
  67931. this.children[index]._updateDifferenceMatrix();
  67932. }
  67933. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  67934. };
  67935. Bone.prototype.markAsDirty = function () {
  67936. this._currentRenderId++;
  67937. this._skeleton._markAsDirty();
  67938. };
  67939. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  67940. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  67941. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  67942. // all animation may be coming from a library skeleton, so may need to create animation
  67943. if (this.animations.length === 0) {
  67944. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  67945. this.animations[0].setKeys([]);
  67946. }
  67947. // get animation info / verify there is such a range from the source bone
  67948. var sourceRange = source.animations[0].getRange(rangeName);
  67949. if (!sourceRange) {
  67950. return false;
  67951. }
  67952. var from = sourceRange.from;
  67953. var to = sourceRange.to;
  67954. var sourceKeys = source.animations[0].getKeys();
  67955. // rescaling prep
  67956. var sourceBoneLength = source.length;
  67957. var sourceParent = source.getParent();
  67958. var parent = this.getParent();
  67959. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  67960. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  67961. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  67962. var destKeys = this.animations[0].getKeys();
  67963. // loop vars declaration
  67964. var orig;
  67965. var origTranslation;
  67966. var mat;
  67967. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  67968. orig = sourceKeys[key];
  67969. if (orig.frame >= from && orig.frame <= to) {
  67970. if (rescaleAsRequired) {
  67971. mat = orig.value.clone();
  67972. // scale based on parent ratio, when bone has parent
  67973. if (parentScalingReqd) {
  67974. origTranslation = mat.getTranslation();
  67975. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  67976. // scale based on skeleton dimension ratio when root bone, and value is passed
  67977. }
  67978. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  67979. origTranslation = mat.getTranslation();
  67980. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  67981. // use original when root bone, and no data for skelDimensionsRatio
  67982. }
  67983. else {
  67984. mat = orig.value;
  67985. }
  67986. }
  67987. else {
  67988. mat = orig.value;
  67989. }
  67990. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  67991. }
  67992. }
  67993. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  67994. return true;
  67995. };
  67996. /**
  67997. * Translate the bone in local or world space.
  67998. * @param vec The amount to translate the bone.
  67999. * @param space The space that the translation is in.
  68000. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68001. */
  68002. Bone.prototype.translate = function (vec, space, mesh) {
  68003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68004. var lm = this.getLocalMatrix();
  68005. if (space == BABYLON.Space.LOCAL) {
  68006. lm.m[12] += vec.x;
  68007. lm.m[13] += vec.y;
  68008. lm.m[14] += vec.z;
  68009. }
  68010. else {
  68011. var wm = null;
  68012. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68013. if (mesh) {
  68014. wm = mesh.getWorldMatrix();
  68015. }
  68016. this._skeleton.computeAbsoluteTransforms();
  68017. var tmat = Bone._tmpMats[0];
  68018. var tvec = Bone._tmpVecs[0];
  68019. if (this._parent) {
  68020. if (mesh && wm) {
  68021. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68022. tmat.multiplyToRef(wm, tmat);
  68023. }
  68024. else {
  68025. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68026. }
  68027. }
  68028. tmat.m[12] = 0;
  68029. tmat.m[13] = 0;
  68030. tmat.m[14] = 0;
  68031. tmat.invert();
  68032. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68033. lm.m[12] += tvec.x;
  68034. lm.m[13] += tvec.y;
  68035. lm.m[14] += tvec.z;
  68036. }
  68037. this.markAsDirty();
  68038. };
  68039. /**
  68040. * Set the postion of the bone in local or world space.
  68041. * @param position The position to set the bone.
  68042. * @param space The space that the position is in.
  68043. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68044. */
  68045. Bone.prototype.setPosition = function (position, space, mesh) {
  68046. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68047. var lm = this.getLocalMatrix();
  68048. if (space == BABYLON.Space.LOCAL) {
  68049. lm.m[12] = position.x;
  68050. lm.m[13] = position.y;
  68051. lm.m[14] = position.z;
  68052. }
  68053. else {
  68054. var wm = null;
  68055. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68056. if (mesh) {
  68057. wm = mesh.getWorldMatrix();
  68058. }
  68059. this._skeleton.computeAbsoluteTransforms();
  68060. var tmat = Bone._tmpMats[0];
  68061. var vec = Bone._tmpVecs[0];
  68062. if (this._parent) {
  68063. if (mesh && wm) {
  68064. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68065. tmat.multiplyToRef(wm, tmat);
  68066. }
  68067. else {
  68068. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68069. }
  68070. }
  68071. tmat.invert();
  68072. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68073. lm.m[12] = vec.x;
  68074. lm.m[13] = vec.y;
  68075. lm.m[14] = vec.z;
  68076. }
  68077. this.markAsDirty();
  68078. };
  68079. /**
  68080. * Set the absolute postion of the bone (world space).
  68081. * @param position The position to set the bone.
  68082. * @param mesh The mesh that this bone is attached to.
  68083. */
  68084. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68085. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68086. };
  68087. /**
  68088. * Set the scale of the bone on the x, y and z axes.
  68089. * @param x The scale of the bone on the x axis.
  68090. * @param x The scale of the bone on the y axis.
  68091. * @param z The scale of the bone on the z axis.
  68092. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68093. */
  68094. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68095. if (scaleChildren === void 0) { scaleChildren = false; }
  68096. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68097. if (!scaleChildren) {
  68098. this._negateScaleChildren.x = 1 / x;
  68099. this._negateScaleChildren.y = 1 / y;
  68100. this._negateScaleChildren.z = 1 / z;
  68101. }
  68102. this._syncScaleVector();
  68103. }
  68104. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68105. };
  68106. /**
  68107. * Scale the bone on the x, y and z axes.
  68108. * @param x The amount to scale the bone on the x axis.
  68109. * @param x The amount to scale the bone on the y axis.
  68110. * @param z The amount to scale the bone on the z axis.
  68111. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68112. */
  68113. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68114. if (scaleChildren === void 0) { scaleChildren = false; }
  68115. var locMat = this.getLocalMatrix();
  68116. var origLocMat = Bone._tmpMats[0];
  68117. origLocMat.copyFrom(locMat);
  68118. var origLocMatInv = Bone._tmpMats[1];
  68119. origLocMatInv.copyFrom(origLocMat);
  68120. origLocMatInv.invert();
  68121. var scaleMat = Bone._tmpMats[2];
  68122. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68123. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68124. this._scaleVector.x *= x;
  68125. this._scaleVector.y *= y;
  68126. this._scaleVector.z *= z;
  68127. locMat.multiplyToRef(origLocMatInv, locMat);
  68128. locMat.multiplyToRef(scaleMat, locMat);
  68129. locMat.multiplyToRef(origLocMat, locMat);
  68130. var parent = this.getParent();
  68131. if (parent) {
  68132. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68133. }
  68134. else {
  68135. this.getAbsoluteTransform().copyFrom(locMat);
  68136. }
  68137. var len = this.children.length;
  68138. scaleMat.invert();
  68139. for (var i = 0; i < len; i++) {
  68140. var child = this.children[i];
  68141. var cm = child.getLocalMatrix();
  68142. cm.multiplyToRef(scaleMat, cm);
  68143. var lm = child.getLocalMatrix();
  68144. lm.m[12] *= x;
  68145. lm.m[13] *= y;
  68146. lm.m[14] *= z;
  68147. }
  68148. this.computeAbsoluteTransforms();
  68149. if (scaleChildren) {
  68150. for (var i = 0; i < len; i++) {
  68151. this.children[i].scale(x, y, z, scaleChildren);
  68152. }
  68153. }
  68154. this.markAsDirty();
  68155. };
  68156. /**
  68157. * Set the yaw, pitch, and roll of the bone in local or world space.
  68158. * @param yaw The rotation of the bone on the y axis.
  68159. * @param pitch The rotation of the bone on the x axis.
  68160. * @param roll The rotation of the bone on the z axis.
  68161. * @param space The space that the axes of rotation are in.
  68162. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68163. */
  68164. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68165. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68166. var rotMat = Bone._tmpMats[0];
  68167. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68168. var rotMatInv = Bone._tmpMats[1];
  68169. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68170. rotMatInv.multiplyToRef(rotMat, rotMat);
  68171. this._rotateWithMatrix(rotMat, space, mesh);
  68172. };
  68173. /**
  68174. * Rotate the bone on an axis in local or world space.
  68175. * @param axis The axis to rotate the bone on.
  68176. * @param amount The amount to rotate the bone.
  68177. * @param space The space that the axis is in.
  68178. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68179. */
  68180. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68181. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68182. var rmat = Bone._tmpMats[0];
  68183. rmat.m[12] = 0;
  68184. rmat.m[13] = 0;
  68185. rmat.m[14] = 0;
  68186. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68187. this._rotateWithMatrix(rmat, space, mesh);
  68188. };
  68189. /**
  68190. * Set the rotation of the bone to a particular axis angle in local or world space.
  68191. * @param axis The axis to rotate the bone on.
  68192. * @param angle The angle that the bone should be rotated to.
  68193. * @param space The space that the axis is in.
  68194. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68195. */
  68196. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68197. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68198. var rotMat = Bone._tmpMats[0];
  68199. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68200. var rotMatInv = Bone._tmpMats[1];
  68201. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68202. rotMatInv.multiplyToRef(rotMat, rotMat);
  68203. this._rotateWithMatrix(rotMat, space, mesh);
  68204. };
  68205. /**
  68206. * Set the euler rotation of the bone in local of world space.
  68207. * @param rotation The euler rotation that the bone should be set to.
  68208. * @param space The space that the rotation is in.
  68209. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68210. */
  68211. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68212. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68213. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68214. };
  68215. /**
  68216. * Set the quaternion rotation of the bone in local of world space.
  68217. * @param quat The quaternion rotation that the bone should be set to.
  68218. * @param space The space that the rotation is in.
  68219. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68220. */
  68221. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68222. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68223. var rotMatInv = Bone._tmpMats[0];
  68224. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68225. var rotMat = Bone._tmpMats[1];
  68226. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68227. rotMatInv.multiplyToRef(rotMat, rotMat);
  68228. this._rotateWithMatrix(rotMat, space, mesh);
  68229. };
  68230. /**
  68231. * Set the rotation matrix of the bone in local of world space.
  68232. * @param rotMat The rotation matrix that the bone should be set to.
  68233. * @param space The space that the rotation is in.
  68234. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68235. */
  68236. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  68237. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68238. var rotMatInv = Bone._tmpMats[0];
  68239. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68240. var rotMat2 = Bone._tmpMats[1];
  68241. rotMat2.copyFrom(rotMat);
  68242. rotMatInv.multiplyToRef(rotMat, rotMat2);
  68243. this._rotateWithMatrix(rotMat2, space, mesh);
  68244. };
  68245. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  68246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68247. var lmat = this.getLocalMatrix();
  68248. var lx = lmat.m[12];
  68249. var ly = lmat.m[13];
  68250. var lz = lmat.m[14];
  68251. var parent = this.getParent();
  68252. var parentScale = Bone._tmpMats[3];
  68253. var parentScaleInv = Bone._tmpMats[4];
  68254. if (parent) {
  68255. if (space == BABYLON.Space.WORLD) {
  68256. if (mesh) {
  68257. parentScale.copyFrom(mesh.getWorldMatrix());
  68258. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  68259. }
  68260. else {
  68261. parentScale.copyFrom(parent.getAbsoluteTransform());
  68262. }
  68263. }
  68264. else {
  68265. parentScale = parent._scaleMatrix;
  68266. }
  68267. parentScaleInv.copyFrom(parentScale);
  68268. parentScaleInv.invert();
  68269. lmat.multiplyToRef(parentScale, lmat);
  68270. lmat.multiplyToRef(rmat, lmat);
  68271. lmat.multiplyToRef(parentScaleInv, lmat);
  68272. }
  68273. else {
  68274. if (space == BABYLON.Space.WORLD && mesh) {
  68275. parentScale.copyFrom(mesh.getWorldMatrix());
  68276. parentScaleInv.copyFrom(parentScale);
  68277. parentScaleInv.invert();
  68278. lmat.multiplyToRef(parentScale, lmat);
  68279. lmat.multiplyToRef(rmat, lmat);
  68280. lmat.multiplyToRef(parentScaleInv, lmat);
  68281. }
  68282. else {
  68283. lmat.multiplyToRef(rmat, lmat);
  68284. }
  68285. }
  68286. lmat.m[12] = lx;
  68287. lmat.m[13] = ly;
  68288. lmat.m[14] = lz;
  68289. this.computeAbsoluteTransforms();
  68290. this.markAsDirty();
  68291. };
  68292. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  68293. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68294. if (space == BABYLON.Space.WORLD) {
  68295. var scaleMatrix = Bone._tmpMats[2];
  68296. scaleMatrix.copyFrom(this._scaleMatrix);
  68297. rotMatInv.copyFrom(this.getAbsoluteTransform());
  68298. if (mesh) {
  68299. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  68300. var meshScale = Bone._tmpMats[3];
  68301. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  68302. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  68303. }
  68304. rotMatInv.invert();
  68305. scaleMatrix.m[0] *= this._scalingDeterminant;
  68306. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68307. }
  68308. else {
  68309. rotMatInv.copyFrom(this.getLocalMatrix());
  68310. rotMatInv.invert();
  68311. var scaleMatrix = Bone._tmpMats[2];
  68312. scaleMatrix.copyFrom(this._scaleMatrix);
  68313. if (this._parent) {
  68314. var pscaleMatrix = Bone._tmpMats[3];
  68315. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  68316. pscaleMatrix.invert();
  68317. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  68318. }
  68319. else {
  68320. scaleMatrix.m[0] *= this._scalingDeterminant;
  68321. }
  68322. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68323. }
  68324. };
  68325. /**
  68326. * Get the scale of the bone
  68327. * @returns the scale of the bone
  68328. */
  68329. Bone.prototype.getScale = function () {
  68330. return this._scaleVector.clone();
  68331. };
  68332. /**
  68333. * Copy the scale of the bone to a vector3.
  68334. * @param result The vector3 to copy the scale to
  68335. */
  68336. Bone.prototype.getScaleToRef = function (result) {
  68337. result.copyFrom(this._scaleVector);
  68338. };
  68339. /**
  68340. * Get the position of the bone in local or world space.
  68341. * @param space The space that the returned position is in.
  68342. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68343. * @returns The position of the bone
  68344. */
  68345. Bone.prototype.getPosition = function (space, mesh) {
  68346. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68347. if (mesh === void 0) { mesh = null; }
  68348. var pos = BABYLON.Vector3.Zero();
  68349. this.getPositionToRef(space, mesh, pos);
  68350. return pos;
  68351. };
  68352. /**
  68353. * Copy the position of the bone to a vector3 in local or world space.
  68354. * @param space The space that the returned position is in.
  68355. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68356. * @param result The vector3 to copy the position to.
  68357. */
  68358. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  68359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68360. if (space == BABYLON.Space.LOCAL) {
  68361. var lm = this.getLocalMatrix();
  68362. result.x = lm.m[12];
  68363. result.y = lm.m[13];
  68364. result.z = lm.m[14];
  68365. }
  68366. else {
  68367. var wm = null;
  68368. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68369. if (mesh) {
  68370. wm = mesh.getWorldMatrix();
  68371. }
  68372. this._skeleton.computeAbsoluteTransforms();
  68373. var tmat = Bone._tmpMats[0];
  68374. if (mesh && wm) {
  68375. tmat.copyFrom(this.getAbsoluteTransform());
  68376. tmat.multiplyToRef(wm, tmat);
  68377. }
  68378. else {
  68379. tmat = this.getAbsoluteTransform();
  68380. }
  68381. result.x = tmat.m[12];
  68382. result.y = tmat.m[13];
  68383. result.z = tmat.m[14];
  68384. }
  68385. };
  68386. /**
  68387. * Get the absolute position of the bone (world space).
  68388. * @param mesh The mesh that this bone is attached to.
  68389. * @returns The absolute position of the bone
  68390. */
  68391. Bone.prototype.getAbsolutePosition = function (mesh) {
  68392. if (mesh === void 0) { mesh = null; }
  68393. var pos = BABYLON.Vector3.Zero();
  68394. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  68395. return pos;
  68396. };
  68397. /**
  68398. * Copy the absolute position of the bone (world space) to the result param.
  68399. * @param mesh The mesh that this bone is attached to.
  68400. * @param result The vector3 to copy the absolute position to.
  68401. */
  68402. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  68403. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  68404. };
  68405. /**
  68406. * Compute the absolute transforms of this bone and its children.
  68407. */
  68408. Bone.prototype.computeAbsoluteTransforms = function () {
  68409. if (this._parent) {
  68410. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68411. }
  68412. else {
  68413. this._absoluteTransform.copyFrom(this._localMatrix);
  68414. var poseMatrix = this._skeleton.getPoseMatrix();
  68415. if (poseMatrix) {
  68416. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  68417. }
  68418. }
  68419. var children = this.children;
  68420. var len = children.length;
  68421. for (var i = 0; i < len; i++) {
  68422. children[i].computeAbsoluteTransforms();
  68423. }
  68424. };
  68425. Bone.prototype._syncScaleVector = function () {
  68426. var lm = this.getLocalMatrix();
  68427. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  68428. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  68429. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  68430. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  68431. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  68432. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  68433. this._scaleVector.x = xs * Math.sqrt(xsq);
  68434. this._scaleVector.y = ys * Math.sqrt(ysq);
  68435. this._scaleVector.z = zs * Math.sqrt(zsq);
  68436. if (this._parent) {
  68437. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  68438. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  68439. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  68440. }
  68441. 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);
  68442. };
  68443. /**
  68444. * Get the world direction from an axis that is in the local space of the bone.
  68445. * @param localAxis The local direction that is used to compute the world direction.
  68446. * @param mesh The mesh that this bone is attached to.
  68447. * @returns The world direction
  68448. */
  68449. Bone.prototype.getDirection = function (localAxis, mesh) {
  68450. if (mesh === void 0) { mesh = null; }
  68451. var result = BABYLON.Vector3.Zero();
  68452. this.getDirectionToRef(localAxis, mesh, result);
  68453. return result;
  68454. };
  68455. /**
  68456. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  68457. * @param localAxis The local direction that is used to compute the world direction.
  68458. * @param mesh The mesh that this bone is attached to.
  68459. * @param result The vector3 that the world direction will be copied to.
  68460. */
  68461. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  68462. if (mesh === void 0) { mesh = null; }
  68463. var wm = null;
  68464. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68465. if (mesh) {
  68466. wm = mesh.getWorldMatrix();
  68467. }
  68468. this._skeleton.computeAbsoluteTransforms();
  68469. var mat = Bone._tmpMats[0];
  68470. mat.copyFrom(this.getAbsoluteTransform());
  68471. if (mesh && wm) {
  68472. mat.multiplyToRef(wm, mat);
  68473. }
  68474. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  68475. result.normalize();
  68476. };
  68477. /**
  68478. * Get the euler rotation of the bone in local or world space.
  68479. * @param space The space that the rotation should be in.
  68480. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68481. * @returns The euler rotation
  68482. */
  68483. Bone.prototype.getRotation = function (space, mesh) {
  68484. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68485. if (mesh === void 0) { mesh = null; }
  68486. var result = BABYLON.Vector3.Zero();
  68487. this.getRotationToRef(space, mesh, result);
  68488. return result;
  68489. };
  68490. /**
  68491. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  68492. * @param space The space that the rotation should be in.
  68493. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68494. * @param result The vector3 that the rotation should be copied to.
  68495. */
  68496. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  68497. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68498. if (mesh === void 0) { mesh = null; }
  68499. var quat = Bone._tmpQuat;
  68500. this.getRotationQuaternionToRef(space, mesh, quat);
  68501. quat.toEulerAnglesToRef(result);
  68502. };
  68503. /**
  68504. * Get the quaternion rotation of the bone in either local or world space.
  68505. * @param space The space that the rotation should be in.
  68506. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68507. * @returns The quaternion rotation
  68508. */
  68509. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  68510. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68511. if (mesh === void 0) { mesh = null; }
  68512. var result = BABYLON.Quaternion.Identity();
  68513. this.getRotationQuaternionToRef(space, mesh, result);
  68514. return result;
  68515. };
  68516. /**
  68517. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  68518. * @param space The space that the rotation should be in.
  68519. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68520. * @param result The quaternion that the rotation should be copied to.
  68521. */
  68522. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  68523. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68524. if (mesh === void 0) { mesh = null; }
  68525. if (space == BABYLON.Space.LOCAL) {
  68526. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  68527. }
  68528. else {
  68529. var mat = Bone._tmpMats[0];
  68530. var amat = this.getAbsoluteTransform();
  68531. if (mesh) {
  68532. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  68533. }
  68534. else {
  68535. mat.copyFrom(amat);
  68536. }
  68537. mat.m[0] *= this._scalingDeterminant;
  68538. mat.m[1] *= this._scalingDeterminant;
  68539. mat.m[2] *= this._scalingDeterminant;
  68540. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  68541. }
  68542. };
  68543. /**
  68544. * Get the rotation matrix of the bone in local or world space.
  68545. * @param space The space that the rotation should be in.
  68546. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68547. * @returns The rotation matrix
  68548. */
  68549. Bone.prototype.getRotationMatrix = function (space, mesh) {
  68550. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68551. var result = BABYLON.Matrix.Identity();
  68552. this.getRotationMatrixToRef(space, mesh, result);
  68553. return result;
  68554. };
  68555. /**
  68556. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  68557. * @param space The space that the rotation should be in.
  68558. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68559. * @param result The quaternion that the rotation should be copied to.
  68560. */
  68561. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  68562. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68563. if (space == BABYLON.Space.LOCAL) {
  68564. this.getLocalMatrix().getRotationMatrixToRef(result);
  68565. }
  68566. else {
  68567. var mat = Bone._tmpMats[0];
  68568. var amat = this.getAbsoluteTransform();
  68569. if (mesh) {
  68570. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  68571. }
  68572. else {
  68573. mat.copyFrom(amat);
  68574. }
  68575. mat.m[0] *= this._scalingDeterminant;
  68576. mat.m[1] *= this._scalingDeterminant;
  68577. mat.m[2] *= this._scalingDeterminant;
  68578. mat.getRotationMatrixToRef(result);
  68579. }
  68580. };
  68581. /**
  68582. * Get the world position of a point that is in the local space of the bone.
  68583. * @param position The local position
  68584. * @param mesh The mesh that this bone is attached to.
  68585. * @returns The world position
  68586. */
  68587. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  68588. if (mesh === void 0) { mesh = null; }
  68589. var result = BABYLON.Vector3.Zero();
  68590. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  68591. return result;
  68592. };
  68593. /**
  68594. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  68595. * @param position The local position
  68596. * @param mesh The mesh that this bone is attached to.
  68597. * @param result The vector3 that the world position should be copied to.
  68598. */
  68599. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  68600. if (mesh === void 0) { mesh = null; }
  68601. var wm = null;
  68602. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68603. if (mesh) {
  68604. wm = mesh.getWorldMatrix();
  68605. }
  68606. this._skeleton.computeAbsoluteTransforms();
  68607. var tmat = Bone._tmpMats[0];
  68608. if (mesh && wm) {
  68609. tmat.copyFrom(this.getAbsoluteTransform());
  68610. tmat.multiplyToRef(wm, tmat);
  68611. }
  68612. else {
  68613. tmat = this.getAbsoluteTransform();
  68614. }
  68615. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  68616. };
  68617. /**
  68618. * Get the local position of a point that is in world space.
  68619. * @param position The world position
  68620. * @param mesh The mesh that this bone is attached to.
  68621. * @returns The local position
  68622. */
  68623. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  68624. if (mesh === void 0) { mesh = null; }
  68625. var result = BABYLON.Vector3.Zero();
  68626. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  68627. return result;
  68628. };
  68629. /**
  68630. * Get the local position of a point that is in world space and copy it to the result param.
  68631. * @param position The world position
  68632. * @param mesh The mesh that this bone is attached to.
  68633. * @param result The vector3 that the local position should be copied to.
  68634. */
  68635. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  68636. if (mesh === void 0) { mesh = null; }
  68637. var wm = null;
  68638. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68639. if (mesh) {
  68640. wm = mesh.getWorldMatrix();
  68641. }
  68642. this._skeleton.computeAbsoluteTransforms();
  68643. var tmat = Bone._tmpMats[0];
  68644. tmat.copyFrom(this.getAbsoluteTransform());
  68645. if (mesh && wm) {
  68646. tmat.multiplyToRef(wm, tmat);
  68647. }
  68648. tmat.invert();
  68649. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  68650. };
  68651. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68652. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  68653. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  68654. return Bone;
  68655. }(BABYLON.Node));
  68656. BABYLON.Bone = Bone;
  68657. })(BABYLON || (BABYLON = {}));
  68658. //# sourceMappingURL=babylon.bone.js.map
  68659. var BABYLON;
  68660. (function (BABYLON) {
  68661. var BoneIKController = /** @class */ (function () {
  68662. function BoneIKController(mesh, bone, options) {
  68663. this.targetPosition = BABYLON.Vector3.Zero();
  68664. this.poleTargetPosition = BABYLON.Vector3.Zero();
  68665. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  68666. this.poleAngle = 0;
  68667. this.slerpAmount = 1;
  68668. this._bone1Quat = BABYLON.Quaternion.Identity();
  68669. this._bone1Mat = BABYLON.Matrix.Identity();
  68670. this._bone2Ang = Math.PI;
  68671. this._maxAngle = Math.PI;
  68672. this._rightHandedSystem = false;
  68673. this._bendAxis = BABYLON.Vector3.Right();
  68674. this._slerping = false;
  68675. this._adjustRoll = 0;
  68676. this._bone2 = bone;
  68677. this._bone1 = bone.getParent();
  68678. if (!this._bone1) {
  68679. return;
  68680. }
  68681. this.mesh = mesh;
  68682. var bonePos = bone.getPosition();
  68683. if (bone.getAbsoluteTransform().determinant() > 0) {
  68684. this._rightHandedSystem = true;
  68685. this._bendAxis.x = 0;
  68686. this._bendAxis.y = 0;
  68687. this._bendAxis.z = -1;
  68688. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  68689. this._adjustRoll = Math.PI * .5;
  68690. this._bendAxis.z = 1;
  68691. }
  68692. }
  68693. if (this._bone1.length) {
  68694. var boneScale1 = this._bone1.getScale();
  68695. var boneScale2 = this._bone2.getScale();
  68696. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  68697. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  68698. }
  68699. else if (this._bone1.children[0]) {
  68700. mesh.computeWorldMatrix(true);
  68701. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  68702. var pos2 = this._bone2.getAbsolutePosition(mesh);
  68703. var pos3 = this._bone1.getAbsolutePosition(mesh);
  68704. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  68705. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  68706. }
  68707. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  68708. this.maxAngle = Math.PI;
  68709. if (options) {
  68710. if (options.targetMesh) {
  68711. this.targetMesh = options.targetMesh;
  68712. this.targetMesh.computeWorldMatrix(true);
  68713. }
  68714. if (options.poleTargetMesh) {
  68715. this.poleTargetMesh = options.poleTargetMesh;
  68716. this.poleTargetMesh.computeWorldMatrix(true);
  68717. }
  68718. else if (options.poleTargetBone) {
  68719. this.poleTargetBone = options.poleTargetBone;
  68720. }
  68721. else if (this._bone1.getParent()) {
  68722. this.poleTargetBone = this._bone1.getParent();
  68723. }
  68724. if (options.poleTargetLocalOffset) {
  68725. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  68726. }
  68727. if (options.poleAngle) {
  68728. this.poleAngle = options.poleAngle;
  68729. }
  68730. if (options.bendAxis) {
  68731. this._bendAxis.copyFrom(options.bendAxis);
  68732. }
  68733. if (options.maxAngle) {
  68734. this.maxAngle = options.maxAngle;
  68735. }
  68736. if (options.slerpAmount) {
  68737. this.slerpAmount = options.slerpAmount;
  68738. }
  68739. }
  68740. }
  68741. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  68742. get: function () {
  68743. return this._maxAngle;
  68744. },
  68745. set: function (value) {
  68746. this._setMaxAngle(value);
  68747. },
  68748. enumerable: true,
  68749. configurable: true
  68750. });
  68751. BoneIKController.prototype._setMaxAngle = function (ang) {
  68752. if (ang < 0) {
  68753. ang = 0;
  68754. }
  68755. if (ang > Math.PI || ang == undefined) {
  68756. ang = Math.PI;
  68757. }
  68758. this._maxAngle = ang;
  68759. var a = this._bone1Length;
  68760. var b = this._bone2Length;
  68761. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  68762. };
  68763. BoneIKController.prototype.update = function () {
  68764. var bone1 = this._bone1;
  68765. if (!bone1) {
  68766. return;
  68767. }
  68768. var target = this.targetPosition;
  68769. var poleTarget = this.poleTargetPosition;
  68770. var mat1 = BoneIKController._tmpMats[0];
  68771. var mat2 = BoneIKController._tmpMats[1];
  68772. if (this.targetMesh) {
  68773. target.copyFrom(this.targetMesh.getAbsolutePosition());
  68774. }
  68775. if (this.poleTargetBone) {
  68776. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  68777. }
  68778. else if (this.poleTargetMesh) {
  68779. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  68780. }
  68781. var bonePos = BoneIKController._tmpVecs[0];
  68782. var zaxis = BoneIKController._tmpVecs[1];
  68783. var xaxis = BoneIKController._tmpVecs[2];
  68784. var yaxis = BoneIKController._tmpVecs[3];
  68785. var upAxis = BoneIKController._tmpVecs[4];
  68786. var _tmpQuat = BoneIKController._tmpQuat;
  68787. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  68788. poleTarget.subtractToRef(bonePos, upAxis);
  68789. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  68790. upAxis.y = 1;
  68791. }
  68792. else {
  68793. upAxis.normalize();
  68794. }
  68795. target.subtractToRef(bonePos, yaxis);
  68796. yaxis.normalize();
  68797. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  68798. zaxis.normalize();
  68799. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  68800. xaxis.normalize();
  68801. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  68802. var a = this._bone1Length;
  68803. var b = this._bone2Length;
  68804. var c = BABYLON.Vector3.Distance(bonePos, target);
  68805. if (this._maxReach > 0) {
  68806. c = Math.min(this._maxReach, c);
  68807. }
  68808. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  68809. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  68810. if (acosa > 1) {
  68811. acosa = 1;
  68812. }
  68813. if (acosb > 1) {
  68814. acosb = 1;
  68815. }
  68816. if (acosa < -1) {
  68817. acosa = -1;
  68818. }
  68819. if (acosb < -1) {
  68820. acosb = -1;
  68821. }
  68822. var angA = Math.acos(acosa);
  68823. var angB = Math.acos(acosb);
  68824. var angC = -angA - angB;
  68825. if (this._rightHandedSystem) {
  68826. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  68827. mat2.multiplyToRef(mat1, mat1);
  68828. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  68829. mat2.multiplyToRef(mat1, mat1);
  68830. }
  68831. else {
  68832. var _tmpVec = BoneIKController._tmpVecs[5];
  68833. _tmpVec.copyFrom(this._bendAxis);
  68834. _tmpVec.x *= -1;
  68835. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  68836. mat2.multiplyToRef(mat1, mat1);
  68837. }
  68838. if (this.poleAngle) {
  68839. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  68840. mat1.multiplyToRef(mat2, mat1);
  68841. }
  68842. if (this._bone1) {
  68843. if (this.slerpAmount < 1) {
  68844. if (!this._slerping) {
  68845. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  68846. }
  68847. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  68848. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  68849. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  68850. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  68851. this._slerping = true;
  68852. }
  68853. else {
  68854. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  68855. this._bone1Mat.copyFrom(mat1);
  68856. this._slerping = false;
  68857. }
  68858. }
  68859. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  68860. this._bone2Ang = angC;
  68861. };
  68862. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68863. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  68864. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  68865. return BoneIKController;
  68866. }());
  68867. BABYLON.BoneIKController = BoneIKController;
  68868. })(BABYLON || (BABYLON = {}));
  68869. //# sourceMappingURL=babylon.boneIKController.js.map
  68870. var BABYLON;
  68871. (function (BABYLON) {
  68872. var BoneLookController = /** @class */ (function () {
  68873. /**
  68874. * Create a BoneLookController
  68875. * @param mesh the mesh that the bone belongs to
  68876. * @param bone the bone that will be looking to the target
  68877. * @param target the target Vector3 to look at
  68878. * @param settings optional settings:
  68879. * - maxYaw: the maximum angle the bone will yaw to
  68880. * - minYaw: the minimum angle the bone will yaw to
  68881. * - maxPitch: the maximum angle the bone will pitch to
  68882. * - minPitch: the minimum angle the bone will yaw to
  68883. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  68884. * - upAxis: the up axis of the coordinate system
  68885. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  68886. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  68887. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  68888. * - adjustYaw: used to make an adjustment to the yaw of the bone
  68889. * - adjustPitch: used to make an adjustment to the pitch of the bone
  68890. * - adjustRoll: used to make an adjustment to the roll of the bone
  68891. **/
  68892. function BoneLookController(mesh, bone, target, options) {
  68893. /**
  68894. * The up axis of the coordinate system that is used when the bone is rotated.
  68895. */
  68896. this.upAxis = BABYLON.Vector3.Up();
  68897. /**
  68898. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  68899. */
  68900. this.upAxisSpace = BABYLON.Space.LOCAL;
  68901. /**
  68902. * Used to make an adjustment to the yaw of the bone.
  68903. */
  68904. this.adjustYaw = 0;
  68905. /**
  68906. * Used to make an adjustment to the pitch of the bone.
  68907. */
  68908. this.adjustPitch = 0;
  68909. /**
  68910. * Used to make an adjustment to the roll of the bone.
  68911. */
  68912. this.adjustRoll = 0;
  68913. /**
  68914. * 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).
  68915. */
  68916. this.slerpAmount = 1;
  68917. this._boneQuat = BABYLON.Quaternion.Identity();
  68918. this._slerping = false;
  68919. this._firstFrameSkipped = false;
  68920. this._fowardAxis = BABYLON.Vector3.Forward();
  68921. this.mesh = mesh;
  68922. this.bone = bone;
  68923. this.target = target;
  68924. if (options) {
  68925. if (options.adjustYaw) {
  68926. this.adjustYaw = options.adjustYaw;
  68927. }
  68928. if (options.adjustPitch) {
  68929. this.adjustPitch = options.adjustPitch;
  68930. }
  68931. if (options.adjustRoll) {
  68932. this.adjustRoll = options.adjustRoll;
  68933. }
  68934. if (options.maxYaw != null) {
  68935. this.maxYaw = options.maxYaw;
  68936. }
  68937. else {
  68938. this.maxYaw = Math.PI;
  68939. }
  68940. if (options.minYaw != null) {
  68941. this.minYaw = options.minYaw;
  68942. }
  68943. else {
  68944. this.minYaw = -Math.PI;
  68945. }
  68946. if (options.maxPitch != null) {
  68947. this.maxPitch = options.maxPitch;
  68948. }
  68949. else {
  68950. this.maxPitch = Math.PI;
  68951. }
  68952. if (options.minPitch != null) {
  68953. this.minPitch = options.minPitch;
  68954. }
  68955. else {
  68956. this.minPitch = -Math.PI;
  68957. }
  68958. if (options.slerpAmount != null) {
  68959. this.slerpAmount = options.slerpAmount;
  68960. }
  68961. if (options.upAxis != null) {
  68962. this.upAxis = options.upAxis;
  68963. }
  68964. if (options.upAxisSpace != null) {
  68965. this.upAxisSpace = options.upAxisSpace;
  68966. }
  68967. if (options.yawAxis != null || options.pitchAxis != null) {
  68968. var newYawAxis = BABYLON.Axis.Y;
  68969. var newPitchAxis = BABYLON.Axis.X;
  68970. if (options.yawAxis != null) {
  68971. newYawAxis = options.yawAxis.clone();
  68972. newYawAxis.normalize();
  68973. }
  68974. if (options.pitchAxis != null) {
  68975. newPitchAxis = options.pitchAxis.clone();
  68976. newPitchAxis.normalize();
  68977. }
  68978. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  68979. this._transformYawPitch = BABYLON.Matrix.Identity();
  68980. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  68981. this._transformYawPitchInv = this._transformYawPitch.clone();
  68982. this._transformYawPitch.invert();
  68983. }
  68984. }
  68985. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  68986. this.upAxisSpace = BABYLON.Space.LOCAL;
  68987. }
  68988. }
  68989. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  68990. /**
  68991. * Get/set the minimum yaw angle that the bone can look to.
  68992. */
  68993. get: function () {
  68994. return this._minYaw;
  68995. },
  68996. set: function (value) {
  68997. this._minYaw = value;
  68998. this._minYawSin = Math.sin(value);
  68999. this._minYawCos = Math.cos(value);
  69000. if (this._maxYaw != null) {
  69001. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69002. this._yawRange = this._maxYaw - this._minYaw;
  69003. }
  69004. },
  69005. enumerable: true,
  69006. configurable: true
  69007. });
  69008. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69009. /**
  69010. * Get/set the maximum yaw angle that the bone can look to.
  69011. */
  69012. get: function () {
  69013. return this._maxYaw;
  69014. },
  69015. set: function (value) {
  69016. this._maxYaw = value;
  69017. this._maxYawSin = Math.sin(value);
  69018. this._maxYawCos = Math.cos(value);
  69019. if (this._minYaw != null) {
  69020. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69021. this._yawRange = this._maxYaw - this._minYaw;
  69022. }
  69023. },
  69024. enumerable: true,
  69025. configurable: true
  69026. });
  69027. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69028. /**
  69029. * Get/set the minimum pitch angle that the bone can look to.
  69030. */
  69031. get: function () {
  69032. return this._minPitch;
  69033. },
  69034. set: function (value) {
  69035. this._minPitch = value;
  69036. this._minPitchTan = Math.tan(value);
  69037. },
  69038. enumerable: true,
  69039. configurable: true
  69040. });
  69041. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69042. /**
  69043. * Get/set the maximum pitch angle that the bone can look to.
  69044. */
  69045. get: function () {
  69046. return this._maxPitch;
  69047. },
  69048. set: function (value) {
  69049. this._maxPitch = value;
  69050. this._maxPitchTan = Math.tan(value);
  69051. },
  69052. enumerable: true,
  69053. configurable: true
  69054. });
  69055. /**
  69056. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69057. */
  69058. BoneLookController.prototype.update = function () {
  69059. //skip the first frame when slerping so that the mesh rotation is correct
  69060. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69061. this._firstFrameSkipped = true;
  69062. return;
  69063. }
  69064. var bone = this.bone;
  69065. var bonePos = BoneLookController._tmpVecs[0];
  69066. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69067. var target = this.target;
  69068. var _tmpMat1 = BoneLookController._tmpMats[0];
  69069. var _tmpMat2 = BoneLookController._tmpMats[1];
  69070. var mesh = this.mesh;
  69071. var parentBone = bone.getParent();
  69072. var upAxis = BoneLookController._tmpVecs[1];
  69073. upAxis.copyFrom(this.upAxis);
  69074. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69075. if (this._transformYawPitch) {
  69076. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69077. }
  69078. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69079. }
  69080. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69081. mesh.getDirectionToRef(upAxis, upAxis);
  69082. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69083. upAxis.normalize();
  69084. }
  69085. }
  69086. var checkYaw = false;
  69087. var checkPitch = false;
  69088. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69089. checkYaw = true;
  69090. }
  69091. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69092. checkPitch = true;
  69093. }
  69094. if (checkYaw || checkPitch) {
  69095. var spaceMat = BoneLookController._tmpMats[2];
  69096. var spaceMatInv = BoneLookController._tmpMats[3];
  69097. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69098. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69099. }
  69100. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69101. spaceMat.copyFrom(mesh.getWorldMatrix());
  69102. }
  69103. else {
  69104. var forwardAxis = BoneLookController._tmpVecs[2];
  69105. forwardAxis.copyFrom(this._fowardAxis);
  69106. if (this._transformYawPitch) {
  69107. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69108. }
  69109. if (parentBone) {
  69110. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69111. }
  69112. else {
  69113. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69114. }
  69115. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69116. rightAxis.normalize();
  69117. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69118. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69119. }
  69120. spaceMat.invertToRef(spaceMatInv);
  69121. var xzlen = null;
  69122. if (checkPitch) {
  69123. var localTarget = BoneLookController._tmpVecs[3];
  69124. target.subtractToRef(bonePos, localTarget);
  69125. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69126. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69127. var pitch = Math.atan2(localTarget.y, xzlen);
  69128. var newPitch = pitch;
  69129. if (pitch > this._maxPitch) {
  69130. localTarget.y = this._maxPitchTan * xzlen;
  69131. newPitch = this._maxPitch;
  69132. }
  69133. else if (pitch < this._minPitch) {
  69134. localTarget.y = this._minPitchTan * xzlen;
  69135. newPitch = this._minPitch;
  69136. }
  69137. if (pitch != newPitch) {
  69138. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69139. localTarget.addInPlace(bonePos);
  69140. target = localTarget;
  69141. }
  69142. }
  69143. if (checkYaw) {
  69144. var localTarget = BoneLookController._tmpVecs[4];
  69145. target.subtractToRef(bonePos, localTarget);
  69146. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69147. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69148. var newYaw = yaw;
  69149. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69150. if (xzlen == null) {
  69151. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69152. }
  69153. if (this._yawRange > Math.PI) {
  69154. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69155. localTarget.z = this._maxYawCos * xzlen;
  69156. localTarget.x = this._maxYawSin * xzlen;
  69157. newYaw = this._maxYaw;
  69158. }
  69159. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69160. localTarget.z = this._minYawCos * xzlen;
  69161. localTarget.x = this._minYawSin * xzlen;
  69162. newYaw = this._minYaw;
  69163. }
  69164. }
  69165. else {
  69166. if (yaw > this._maxYaw) {
  69167. localTarget.z = this._maxYawCos * xzlen;
  69168. localTarget.x = this._maxYawSin * xzlen;
  69169. newYaw = this._maxYaw;
  69170. }
  69171. else if (yaw < this._minYaw) {
  69172. localTarget.z = this._minYawCos * xzlen;
  69173. localTarget.x = this._minYawSin * xzlen;
  69174. newYaw = this._minYaw;
  69175. }
  69176. }
  69177. }
  69178. if (this._slerping && this._yawRange > Math.PI) {
  69179. //are we going to be crossing into the min/max region?
  69180. var boneFwd = BoneLookController._tmpVecs[8];
  69181. boneFwd.copyFrom(BABYLON.Axis.Z);
  69182. if (this._transformYawPitch) {
  69183. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69184. }
  69185. var boneRotMat = BoneLookController._tmpMats[4];
  69186. this._boneQuat.toRotationMatrix(boneRotMat);
  69187. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69188. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69189. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69190. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69191. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69192. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69193. if (angBtwTar > angBtwMidYaw) {
  69194. if (xzlen == null) {
  69195. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69196. }
  69197. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69198. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69199. if (angBtwMin < angBtwMax) {
  69200. newYaw = boneYaw + Math.PI * .75;
  69201. localTarget.z = Math.cos(newYaw) * xzlen;
  69202. localTarget.x = Math.sin(newYaw) * xzlen;
  69203. }
  69204. else {
  69205. newYaw = boneYaw - Math.PI * .75;
  69206. localTarget.z = Math.cos(newYaw) * xzlen;
  69207. localTarget.x = Math.sin(newYaw) * xzlen;
  69208. }
  69209. }
  69210. }
  69211. if (yaw != newYaw) {
  69212. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69213. localTarget.addInPlace(bonePos);
  69214. target = localTarget;
  69215. }
  69216. }
  69217. }
  69218. var zaxis = BoneLookController._tmpVecs[5];
  69219. var xaxis = BoneLookController._tmpVecs[6];
  69220. var yaxis = BoneLookController._tmpVecs[7];
  69221. var _tmpQuat = BoneLookController._tmpQuat;
  69222. target.subtractToRef(bonePos, zaxis);
  69223. zaxis.normalize();
  69224. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69225. xaxis.normalize();
  69226. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69227. yaxis.normalize();
  69228. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69229. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69230. return;
  69231. }
  69232. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  69233. return;
  69234. }
  69235. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  69236. return;
  69237. }
  69238. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  69239. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  69240. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  69241. }
  69242. if (this.slerpAmount < 1) {
  69243. if (!this._slerping) {
  69244. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  69245. }
  69246. if (this._transformYawPitch) {
  69247. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69248. }
  69249. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  69250. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  69251. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  69252. this._slerping = true;
  69253. }
  69254. else {
  69255. if (this._transformYawPitch) {
  69256. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69257. }
  69258. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  69259. this._slerping = false;
  69260. }
  69261. };
  69262. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  69263. var angDiff = ang2 - ang1;
  69264. angDiff %= Math.PI * 2;
  69265. if (angDiff > Math.PI) {
  69266. angDiff -= Math.PI * 2;
  69267. }
  69268. else if (angDiff < -Math.PI) {
  69269. angDiff += Math.PI * 2;
  69270. }
  69271. return angDiff;
  69272. };
  69273. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  69274. ang1 %= (2 * Math.PI);
  69275. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69276. ang2 %= (2 * Math.PI);
  69277. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69278. var ab = 0;
  69279. if (ang1 < ang2) {
  69280. ab = ang2 - ang1;
  69281. }
  69282. else {
  69283. ab = ang1 - ang2;
  69284. }
  69285. if (ab > Math.PI) {
  69286. ab = Math.PI * 2 - ab;
  69287. }
  69288. return ab;
  69289. };
  69290. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  69291. ang %= (2 * Math.PI);
  69292. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  69293. ang1 %= (2 * Math.PI);
  69294. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69295. ang2 %= (2 * Math.PI);
  69296. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69297. if (ang1 < ang2) {
  69298. if (ang > ang1 && ang < ang2) {
  69299. return true;
  69300. }
  69301. }
  69302. else {
  69303. if (ang > ang2 && ang < ang1) {
  69304. return true;
  69305. }
  69306. }
  69307. return false;
  69308. };
  69309. 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()];
  69310. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  69311. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69312. return BoneLookController;
  69313. }());
  69314. BABYLON.BoneLookController = BoneLookController;
  69315. })(BABYLON || (BABYLON = {}));
  69316. //# sourceMappingURL=babylon.boneLookController.js.map
  69317. var BABYLON;
  69318. (function (BABYLON) {
  69319. var Skeleton = /** @class */ (function () {
  69320. function Skeleton(name, id, scene) {
  69321. this.name = name;
  69322. this.id = id;
  69323. this.bones = new Array();
  69324. this.needInitialSkinMatrix = false;
  69325. this._isDirty = true;
  69326. this._meshesWithPoseMatrix = new Array();
  69327. this._identity = BABYLON.Matrix.Identity();
  69328. this._ranges = {};
  69329. this._lastAbsoluteTransformsUpdateId = -1;
  69330. // Events
  69331. /**
  69332. * An event triggered before computing the skeleton's matrices
  69333. * @type {BABYLON.Observable}
  69334. */
  69335. this.onBeforeComputeObservable = new BABYLON.Observable();
  69336. this.bones = [];
  69337. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69338. scene.skeletons.push(this);
  69339. //make sure it will recalculate the matrix next time prepare is called.
  69340. this._isDirty = true;
  69341. }
  69342. // Members
  69343. Skeleton.prototype.getTransformMatrices = function (mesh) {
  69344. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  69345. return mesh._bonesTransformMatrices;
  69346. }
  69347. if (!this._transformMatrices) {
  69348. this.prepare();
  69349. }
  69350. return this._transformMatrices;
  69351. };
  69352. Skeleton.prototype.getScene = function () {
  69353. return this._scene;
  69354. };
  69355. // Methods
  69356. /**
  69357. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  69358. */
  69359. Skeleton.prototype.toString = function (fullDetails) {
  69360. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  69361. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  69362. if (fullDetails) {
  69363. ret += ", Ranges: {";
  69364. var first = true;
  69365. for (var name_1 in this._ranges) {
  69366. if (first) {
  69367. ret += ", ";
  69368. first = false;
  69369. }
  69370. ret += name_1;
  69371. }
  69372. ret += "}";
  69373. }
  69374. return ret;
  69375. };
  69376. /**
  69377. * Get bone's index searching by name
  69378. * @param {string} name is bone's name to search for
  69379. * @return {number} Indice of the bone. Returns -1 if not found
  69380. */
  69381. Skeleton.prototype.getBoneIndexByName = function (name) {
  69382. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  69383. if (this.bones[boneIndex].name === name) {
  69384. return boneIndex;
  69385. }
  69386. }
  69387. return -1;
  69388. };
  69389. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  69390. // check name not already in use
  69391. if (!this._ranges[name]) {
  69392. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  69393. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69394. if (this.bones[i].animations[0]) {
  69395. this.bones[i].animations[0].createRange(name, from, to);
  69396. }
  69397. }
  69398. }
  69399. };
  69400. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  69401. if (deleteFrames === void 0) { deleteFrames = true; }
  69402. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69403. if (this.bones[i].animations[0]) {
  69404. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  69405. }
  69406. }
  69407. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  69408. };
  69409. Skeleton.prototype.getAnimationRange = function (name) {
  69410. return this._ranges[name];
  69411. };
  69412. /**
  69413. * Returns as an Array, all AnimationRanges defined on this skeleton
  69414. */
  69415. Skeleton.prototype.getAnimationRanges = function () {
  69416. var animationRanges = [];
  69417. var name;
  69418. var i = 0;
  69419. for (name in this._ranges) {
  69420. animationRanges[i] = this._ranges[name];
  69421. i++;
  69422. }
  69423. return animationRanges;
  69424. };
  69425. /**
  69426. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  69427. */
  69428. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  69429. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69430. if (this._ranges[name] || !source.getAnimationRange(name)) {
  69431. return false;
  69432. }
  69433. var ret = true;
  69434. var frameOffset = this._getHighestAnimationFrame() + 1;
  69435. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  69436. var boneDict = {};
  69437. var sourceBones = source.bones;
  69438. var nBones;
  69439. var i;
  69440. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  69441. boneDict[sourceBones[i].name] = sourceBones[i];
  69442. }
  69443. if (this.bones.length !== sourceBones.length) {
  69444. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  69445. ret = false;
  69446. }
  69447. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  69448. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  69449. var boneName = this.bones[i].name;
  69450. var sourceBone = boneDict[boneName];
  69451. if (sourceBone) {
  69452. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  69453. }
  69454. else {
  69455. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  69456. ret = false;
  69457. }
  69458. }
  69459. // do not call createAnimationRange(), since it also is done to bones, which was already done
  69460. var range = source.getAnimationRange(name);
  69461. if (range) {
  69462. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  69463. }
  69464. return ret;
  69465. };
  69466. Skeleton.prototype.returnToRest = function () {
  69467. for (var index = 0; index < this.bones.length; index++) {
  69468. this.bones[index].returnToRest();
  69469. }
  69470. };
  69471. Skeleton.prototype._getHighestAnimationFrame = function () {
  69472. var ret = 0;
  69473. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69474. if (this.bones[i].animations[0]) {
  69475. var highest = this.bones[i].animations[0].getHighestFrame();
  69476. if (ret < highest) {
  69477. ret = highest;
  69478. }
  69479. }
  69480. }
  69481. return ret;
  69482. };
  69483. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  69484. var range = this.getAnimationRange(name);
  69485. if (!range) {
  69486. return null;
  69487. }
  69488. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  69489. };
  69490. Skeleton.prototype._markAsDirty = function () {
  69491. this._isDirty = true;
  69492. };
  69493. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  69494. this._meshesWithPoseMatrix.push(mesh);
  69495. };
  69496. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  69497. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  69498. if (index > -1) {
  69499. this._meshesWithPoseMatrix.splice(index, 1);
  69500. }
  69501. };
  69502. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  69503. this.onBeforeComputeObservable.notifyObservers(this);
  69504. for (var index = 0; index < this.bones.length; index++) {
  69505. var bone = this.bones[index];
  69506. var parentBone = bone.getParent();
  69507. if (parentBone) {
  69508. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  69509. }
  69510. else {
  69511. if (initialSkinMatrix) {
  69512. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  69513. }
  69514. else {
  69515. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  69516. }
  69517. }
  69518. if (bone._index !== -1) {
  69519. var mappedIndex = bone._index === null ? index : bone._index;
  69520. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  69521. }
  69522. }
  69523. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  69524. };
  69525. Skeleton.prototype.prepare = function () {
  69526. if (!this._isDirty) {
  69527. return;
  69528. }
  69529. if (this.needInitialSkinMatrix) {
  69530. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  69531. var mesh = this._meshesWithPoseMatrix[index];
  69532. var poseMatrix = mesh.getPoseMatrix();
  69533. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  69534. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  69535. }
  69536. if (this._synchronizedWithMesh !== mesh) {
  69537. this._synchronizedWithMesh = mesh;
  69538. // Prepare bones
  69539. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  69540. var bone = this.bones[boneIndex];
  69541. if (!bone.getParent()) {
  69542. var matrix = bone.getBaseMatrix();
  69543. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  69544. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  69545. }
  69546. }
  69547. }
  69548. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  69549. }
  69550. }
  69551. else {
  69552. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  69553. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  69554. }
  69555. this._computeTransformMatrices(this._transformMatrices, null);
  69556. }
  69557. this._isDirty = false;
  69558. this._scene._activeBones.addCount(this.bones.length, false);
  69559. };
  69560. Skeleton.prototype.getAnimatables = function () {
  69561. if (!this._animatables || this._animatables.length !== this.bones.length) {
  69562. this._animatables = [];
  69563. for (var index = 0; index < this.bones.length; index++) {
  69564. this._animatables.push(this.bones[index]);
  69565. }
  69566. }
  69567. return this._animatables;
  69568. };
  69569. Skeleton.prototype.clone = function (name, id) {
  69570. var result = new Skeleton(name, id || name, this._scene);
  69571. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  69572. for (var index = 0; index < this.bones.length; index++) {
  69573. var source = this.bones[index];
  69574. var parentBone = null;
  69575. var parent_1 = source.getParent();
  69576. if (parent_1) {
  69577. var parentIndex = this.bones.indexOf(parent_1);
  69578. parentBone = result.bones[parentIndex];
  69579. }
  69580. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  69581. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  69582. }
  69583. if (this._ranges) {
  69584. result._ranges = {};
  69585. for (var rangeName in this._ranges) {
  69586. var range = this._ranges[rangeName];
  69587. if (range) {
  69588. result._ranges[rangeName] = range.clone();
  69589. }
  69590. }
  69591. }
  69592. this._isDirty = true;
  69593. return result;
  69594. };
  69595. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  69596. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  69597. this.bones.forEach(function (bone) {
  69598. bone.animations.forEach(function (animation) {
  69599. animation.enableBlending = true;
  69600. animation.blendingSpeed = blendingSpeed;
  69601. });
  69602. });
  69603. };
  69604. Skeleton.prototype.dispose = function () {
  69605. this._meshesWithPoseMatrix = [];
  69606. // Animations
  69607. this.getScene().stopAnimation(this);
  69608. // Remove from scene
  69609. this.getScene().removeSkeleton(this);
  69610. };
  69611. Skeleton.prototype.serialize = function () {
  69612. var serializationObject = {};
  69613. serializationObject.name = this.name;
  69614. serializationObject.id = this.id;
  69615. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  69616. serializationObject.bones = [];
  69617. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  69618. for (var index = 0; index < this.bones.length; index++) {
  69619. var bone = this.bones[index];
  69620. var parent_2 = bone.getParent();
  69621. var serializedBone = {
  69622. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  69623. name: bone.name,
  69624. matrix: bone.getBaseMatrix().toArray(),
  69625. rest: bone.getRestPose().toArray()
  69626. };
  69627. serializationObject.bones.push(serializedBone);
  69628. if (bone.length) {
  69629. serializedBone.length = bone.length;
  69630. }
  69631. if (bone.animations && bone.animations.length > 0) {
  69632. serializedBone.animation = bone.animations[0].serialize();
  69633. }
  69634. serializationObject.ranges = [];
  69635. for (var name in this._ranges) {
  69636. var source = this._ranges[name];
  69637. if (!source) {
  69638. continue;
  69639. }
  69640. var range = {};
  69641. range.name = name;
  69642. range.from = source.from;
  69643. range.to = source.to;
  69644. serializationObject.ranges.push(range);
  69645. }
  69646. }
  69647. return serializationObject;
  69648. };
  69649. Skeleton.Parse = function (parsedSkeleton, scene) {
  69650. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  69651. if (parsedSkeleton.dimensionsAtRest) {
  69652. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  69653. }
  69654. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  69655. var index;
  69656. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  69657. var parsedBone = parsedSkeleton.bones[index];
  69658. var parentBone = null;
  69659. if (parsedBone.parentBoneIndex > -1) {
  69660. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  69661. }
  69662. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  69663. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  69664. if (parsedBone.length) {
  69665. bone.length = parsedBone.length;
  69666. }
  69667. if (parsedBone.animation) {
  69668. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  69669. }
  69670. }
  69671. // placed after bones, so createAnimationRange can cascade down
  69672. if (parsedSkeleton.ranges) {
  69673. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  69674. var data = parsedSkeleton.ranges[index];
  69675. skeleton.createAnimationRange(data.name, data.from, data.to);
  69676. }
  69677. }
  69678. return skeleton;
  69679. };
  69680. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  69681. if (forceUpdate === void 0) { forceUpdate = false; }
  69682. var renderId = this._scene.getRenderId();
  69683. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  69684. this.bones[0].computeAbsoluteTransforms();
  69685. this._lastAbsoluteTransformsUpdateId = renderId;
  69686. }
  69687. };
  69688. Skeleton.prototype.getPoseMatrix = function () {
  69689. var poseMatrix = null;
  69690. if (this._meshesWithPoseMatrix.length > 0) {
  69691. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  69692. }
  69693. return poseMatrix;
  69694. };
  69695. Skeleton.prototype.sortBones = function () {
  69696. var bones = new Array();
  69697. var visited = new Array(this.bones.length);
  69698. for (var index = 0; index < this.bones.length; index++) {
  69699. this._sortBones(index, bones, visited);
  69700. }
  69701. this.bones = bones;
  69702. };
  69703. Skeleton.prototype._sortBones = function (index, bones, visited) {
  69704. if (visited[index]) {
  69705. return;
  69706. }
  69707. visited[index] = true;
  69708. var bone = this.bones[index];
  69709. if (bone._index === undefined) {
  69710. bone._index = index;
  69711. }
  69712. var parentBone = bone.getParent();
  69713. if (parentBone) {
  69714. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  69715. }
  69716. bones.push(bone);
  69717. };
  69718. return Skeleton;
  69719. }());
  69720. BABYLON.Skeleton = Skeleton;
  69721. })(BABYLON || (BABYLON = {}));
  69722. //# sourceMappingURL=babylon.skeleton.js.map
  69723. var BABYLON;
  69724. (function (BABYLON) {
  69725. var SphericalPolynomial = /** @class */ (function () {
  69726. function SphericalPolynomial() {
  69727. this.x = BABYLON.Vector3.Zero();
  69728. this.y = BABYLON.Vector3.Zero();
  69729. this.z = BABYLON.Vector3.Zero();
  69730. this.xx = BABYLON.Vector3.Zero();
  69731. this.yy = BABYLON.Vector3.Zero();
  69732. this.zz = BABYLON.Vector3.Zero();
  69733. this.xy = BABYLON.Vector3.Zero();
  69734. this.yz = BABYLON.Vector3.Zero();
  69735. this.zx = BABYLON.Vector3.Zero();
  69736. }
  69737. SphericalPolynomial.prototype.addAmbient = function (color) {
  69738. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  69739. this.xx = this.xx.add(colorVector);
  69740. this.yy = this.yy.add(colorVector);
  69741. this.zz = this.zz.add(colorVector);
  69742. };
  69743. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  69744. var result = new SphericalPolynomial();
  69745. result.x = harmonics.L11.scale(1.02333);
  69746. result.y = harmonics.L1_1.scale(1.02333);
  69747. result.z = harmonics.L10.scale(1.02333);
  69748. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  69749. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  69750. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  69751. result.yz = harmonics.L2_1.scale(0.858086);
  69752. result.zx = harmonics.L21.scale(0.858086);
  69753. result.xy = harmonics.L2_2.scale(0.858086);
  69754. result.scale(1.0 / Math.PI);
  69755. return result;
  69756. };
  69757. SphericalPolynomial.prototype.scale = function (scale) {
  69758. this.x = this.x.scale(scale);
  69759. this.y = this.y.scale(scale);
  69760. this.z = this.z.scale(scale);
  69761. this.xx = this.xx.scale(scale);
  69762. this.yy = this.yy.scale(scale);
  69763. this.zz = this.zz.scale(scale);
  69764. this.yz = this.yz.scale(scale);
  69765. this.zx = this.zx.scale(scale);
  69766. this.xy = this.xy.scale(scale);
  69767. };
  69768. return SphericalPolynomial;
  69769. }());
  69770. BABYLON.SphericalPolynomial = SphericalPolynomial;
  69771. var SphericalHarmonics = /** @class */ (function () {
  69772. function SphericalHarmonics() {
  69773. this.L00 = BABYLON.Vector3.Zero();
  69774. this.L1_1 = BABYLON.Vector3.Zero();
  69775. this.L10 = BABYLON.Vector3.Zero();
  69776. this.L11 = BABYLON.Vector3.Zero();
  69777. this.L2_2 = BABYLON.Vector3.Zero();
  69778. this.L2_1 = BABYLON.Vector3.Zero();
  69779. this.L20 = BABYLON.Vector3.Zero();
  69780. this.L21 = BABYLON.Vector3.Zero();
  69781. this.L22 = BABYLON.Vector3.Zero();
  69782. }
  69783. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  69784. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  69785. var c = colorVector.scale(deltaSolidAngle);
  69786. this.L00 = this.L00.add(c.scale(0.282095));
  69787. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  69788. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  69789. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  69790. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  69791. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  69792. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  69793. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  69794. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  69795. };
  69796. SphericalHarmonics.prototype.scale = function (scale) {
  69797. this.L00 = this.L00.scale(scale);
  69798. this.L1_1 = this.L1_1.scale(scale);
  69799. this.L10 = this.L10.scale(scale);
  69800. this.L11 = this.L11.scale(scale);
  69801. this.L2_2 = this.L2_2.scale(scale);
  69802. this.L2_1 = this.L2_1.scale(scale);
  69803. this.L20 = this.L20.scale(scale);
  69804. this.L21 = this.L21.scale(scale);
  69805. this.L22 = this.L22.scale(scale);
  69806. };
  69807. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  69808. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  69809. //
  69810. // E_lm = A_l * L_lm
  69811. //
  69812. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  69813. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  69814. // the scaling factors are given in equation 9.
  69815. // Constant (Band 0)
  69816. this.L00 = this.L00.scale(3.141593);
  69817. // Linear (Band 1)
  69818. this.L1_1 = this.L1_1.scale(2.094395);
  69819. this.L10 = this.L10.scale(2.094395);
  69820. this.L11 = this.L11.scale(2.094395);
  69821. // Quadratic (Band 2)
  69822. this.L2_2 = this.L2_2.scale(0.785398);
  69823. this.L2_1 = this.L2_1.scale(0.785398);
  69824. this.L20 = this.L20.scale(0.785398);
  69825. this.L21 = this.L21.scale(0.785398);
  69826. this.L22 = this.L22.scale(0.785398);
  69827. };
  69828. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  69829. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  69830. // L = (1/pi) * E * rho
  69831. //
  69832. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  69833. this.scale(1.0 / Math.PI);
  69834. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  69835. // (The pixel shader must apply albedo after texture fetches, etc).
  69836. };
  69837. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  69838. var result = new SphericalHarmonics();
  69839. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  69840. result.L1_1 = polynomial.y.scale(0.977204);
  69841. result.L10 = polynomial.z.scale(0.977204);
  69842. result.L11 = polynomial.x.scale(0.977204);
  69843. result.L2_2 = polynomial.xy.scale(1.16538);
  69844. result.L2_1 = polynomial.yz.scale(1.16538);
  69845. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  69846. result.L21 = polynomial.zx.scale(1.16538);
  69847. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  69848. result.scale(Math.PI);
  69849. return result;
  69850. };
  69851. return SphericalHarmonics;
  69852. }());
  69853. BABYLON.SphericalHarmonics = SphericalHarmonics;
  69854. })(BABYLON || (BABYLON = {}));
  69855. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  69856. var BABYLON;
  69857. (function (BABYLON) {
  69858. var FileFaceOrientation = /** @class */ (function () {
  69859. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  69860. this.name = name;
  69861. this.worldAxisForNormal = worldAxisForNormal;
  69862. this.worldAxisForFileX = worldAxisForFileX;
  69863. this.worldAxisForFileY = worldAxisForFileY;
  69864. }
  69865. return FileFaceOrientation;
  69866. }());
  69867. ;
  69868. /**
  69869. * Helper class dealing with the extraction of spherical polynomial dataArray
  69870. * from a cube map.
  69871. */
  69872. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  69873. function CubeMapToSphericalPolynomialTools() {
  69874. }
  69875. /**
  69876. * Converts a texture to the according Spherical Polynomial data.
  69877. * This extracts the first 3 orders only as they are the only one used in the lighting.
  69878. *
  69879. * @param texture The texture to extract the information from.
  69880. * @return The Spherical Polynomial data.
  69881. */
  69882. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  69883. if (!texture.isCube) {
  69884. // Only supports cube Textures currently.
  69885. return null;
  69886. }
  69887. var size = texture.getSize().width;
  69888. var right = texture.readPixels(0);
  69889. var left = texture.readPixels(1);
  69890. var up;
  69891. var down;
  69892. if (texture.isRenderTarget) {
  69893. up = texture.readPixels(3);
  69894. down = texture.readPixels(2);
  69895. }
  69896. else {
  69897. up = texture.readPixels(2);
  69898. down = texture.readPixels(3);
  69899. }
  69900. var front = texture.readPixels(4);
  69901. var back = texture.readPixels(5);
  69902. var gammaSpace = texture.gammaSpace;
  69903. // Always read as RGBA.
  69904. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  69905. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69906. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69907. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69908. }
  69909. var cubeInfo = {
  69910. size: size,
  69911. right: right,
  69912. left: left,
  69913. up: up,
  69914. down: down,
  69915. front: front,
  69916. back: back,
  69917. format: format,
  69918. type: type,
  69919. gammaSpace: gammaSpace,
  69920. };
  69921. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  69922. };
  69923. /**
  69924. * Converts a cubemap to the according Spherical Polynomial data.
  69925. * This extracts the first 3 orders only as they are the only one used in the lighting.
  69926. *
  69927. * @param cubeInfo The Cube map to extract the information from.
  69928. * @return The Spherical Polynomial data.
  69929. */
  69930. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  69931. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  69932. var totalSolidAngle = 0.0;
  69933. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  69934. var du = 2.0 / cubeInfo.size;
  69935. var dv = du;
  69936. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  69937. var minUV = du * 0.5 - 1.0;
  69938. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69939. var fileFace = this.FileFaces[faceIndex];
  69940. var dataArray = cubeInfo[fileFace.name];
  69941. var v = minUV;
  69942. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  69943. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  69944. // Because SP is still linear, so summation is fine in that basis.
  69945. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  69946. for (var y = 0; y < cubeInfo.size; y++) {
  69947. var u = minUV;
  69948. for (var x = 0; x < cubeInfo.size; x++) {
  69949. // World direction (not normalised)
  69950. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  69951. worldDirection.normalize();
  69952. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  69953. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  69954. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  69955. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  69956. // Handle Integer types.
  69957. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69958. r /= 255;
  69959. g /= 255;
  69960. b /= 255;
  69961. }
  69962. // Handle Gamma space textures.
  69963. if (cubeInfo.gammaSpace) {
  69964. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  69965. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  69966. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  69967. }
  69968. var color = new BABYLON.Color3(r, g, b);
  69969. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  69970. totalSolidAngle += deltaSolidAngle;
  69971. u += du;
  69972. }
  69973. v += dv;
  69974. }
  69975. }
  69976. // Solid angle for entire sphere is 4*pi
  69977. var sphereSolidAngle = 4.0 * Math.PI;
  69978. // Adjust the solid angle to allow for how many faces we processed.
  69979. var facesProcessed = 6.0;
  69980. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  69981. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  69982. // This is needed because the numerical integration over the cube uses a
  69983. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  69984. // and also to compensate for accumulative error due to float precision in the summation.
  69985. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  69986. sphericalHarmonics.scale(correctionFactor);
  69987. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  69988. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  69989. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  69990. };
  69991. CubeMapToSphericalPolynomialTools.FileFaces = [
  69992. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  69993. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  69994. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  69995. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  69996. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  69997. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  69998. ];
  69999. return CubeMapToSphericalPolynomialTools;
  70000. }());
  70001. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70002. })(BABYLON || (BABYLON = {}));
  70003. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70004. var BABYLON;
  70005. (function (BABYLON) {
  70006. /**
  70007. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70008. */
  70009. var PanoramaToCubeMapTools = /** @class */ (function () {
  70010. function PanoramaToCubeMapTools() {
  70011. }
  70012. /**
  70013. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70014. *
  70015. * @param float32Array The source data.
  70016. * @param inputWidth The width of the input panorama.
  70017. * @param inputhHeight The height of the input panorama.
  70018. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70019. * @return The cubemap data
  70020. */
  70021. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70022. if (!float32Array) {
  70023. throw "ConvertPanoramaToCubemap: input cannot be null";
  70024. }
  70025. if (float32Array.length != inputWidth * inputHeight * 3) {
  70026. throw "ConvertPanoramaToCubemap: input size is wrong";
  70027. }
  70028. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70029. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70030. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70031. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70032. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70033. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70034. return {
  70035. front: textureFront,
  70036. back: textureBack,
  70037. left: textureLeft,
  70038. right: textureRight,
  70039. up: textureUp,
  70040. down: textureDown,
  70041. size: size,
  70042. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70043. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70044. gammaSpace: false,
  70045. };
  70046. };
  70047. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70048. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70049. var textureArray = new Float32Array(buffer);
  70050. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70051. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70052. var dy = 1 / texSize;
  70053. var fy = 0;
  70054. for (var y = 0; y < texSize; y++) {
  70055. var xv1 = faceData[0];
  70056. var xv2 = faceData[2];
  70057. for (var x = 0; x < texSize; x++) {
  70058. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70059. v.normalize();
  70060. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70061. // 3 channels per pixels
  70062. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70063. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70064. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70065. xv1 = xv1.add(rotDX1);
  70066. xv2 = xv2.add(rotDX2);
  70067. }
  70068. fy += dy;
  70069. }
  70070. return textureArray;
  70071. };
  70072. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70073. var theta = Math.atan2(vDir.z, vDir.x);
  70074. var phi = Math.acos(vDir.y);
  70075. while (theta < -Math.PI)
  70076. theta += 2 * Math.PI;
  70077. while (theta > Math.PI)
  70078. theta -= 2 * Math.PI;
  70079. var dx = theta / Math.PI;
  70080. var dy = phi / Math.PI;
  70081. // recenter.
  70082. dx = dx * 0.5 + 0.5;
  70083. var px = Math.round(dx * inputWidth);
  70084. if (px < 0)
  70085. px = 0;
  70086. else if (px >= inputWidth)
  70087. px = inputWidth - 1;
  70088. var py = Math.round(dy * inputHeight);
  70089. if (py < 0)
  70090. py = 0;
  70091. else if (py >= inputHeight)
  70092. py = inputHeight - 1;
  70093. var inputY = (inputHeight - py - 1);
  70094. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70095. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70096. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70097. return {
  70098. r: r,
  70099. g: g,
  70100. b: b
  70101. };
  70102. };
  70103. PanoramaToCubeMapTools.FACE_FRONT = [
  70104. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70105. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70106. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70107. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70108. ];
  70109. PanoramaToCubeMapTools.FACE_BACK = [
  70110. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70111. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70112. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70113. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70114. ];
  70115. PanoramaToCubeMapTools.FACE_RIGHT = [
  70116. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70117. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70118. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70119. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70120. ];
  70121. PanoramaToCubeMapTools.FACE_LEFT = [
  70122. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70123. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70124. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70125. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70126. ];
  70127. PanoramaToCubeMapTools.FACE_DOWN = [
  70128. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70129. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70130. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70131. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70132. ];
  70133. PanoramaToCubeMapTools.FACE_UP = [
  70134. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70135. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70136. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70137. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70138. ];
  70139. return PanoramaToCubeMapTools;
  70140. }());
  70141. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70142. })(BABYLON || (BABYLON = {}));
  70143. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70144. var BABYLON;
  70145. (function (BABYLON) {
  70146. ;
  70147. /**
  70148. * This groups tools to convert HDR texture to native colors array.
  70149. */
  70150. var HDRTools = /** @class */ (function () {
  70151. function HDRTools() {
  70152. }
  70153. HDRTools.Ldexp = function (mantissa, exponent) {
  70154. if (exponent > 1023) {
  70155. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70156. }
  70157. if (exponent < -1074) {
  70158. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70159. }
  70160. return mantissa * Math.pow(2, exponent);
  70161. };
  70162. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70163. if (exponent > 0) {
  70164. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70165. float32array[index + 0] = red * exponent;
  70166. float32array[index + 1] = green * exponent;
  70167. float32array[index + 2] = blue * exponent;
  70168. }
  70169. else {
  70170. float32array[index + 0] = 0;
  70171. float32array[index + 1] = 0;
  70172. float32array[index + 2] = 0;
  70173. }
  70174. };
  70175. HDRTools.readStringLine = function (uint8array, startIndex) {
  70176. var line = "";
  70177. var character = "";
  70178. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70179. character = String.fromCharCode(uint8array[i]);
  70180. if (character == "\n") {
  70181. break;
  70182. }
  70183. line += character;
  70184. }
  70185. return line;
  70186. };
  70187. /**
  70188. * Reads header information from an RGBE texture stored in a native array.
  70189. * More information on this format are available here:
  70190. * https://en.wikipedia.org/wiki/RGBE_image_format
  70191. *
  70192. * @param uint8array The binary file stored in native array.
  70193. * @return The header information.
  70194. */
  70195. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70196. var height = 0;
  70197. var width = 0;
  70198. var line = this.readStringLine(uint8array, 0);
  70199. if (line[0] != '#' || line[1] != '?') {
  70200. throw "Bad HDR Format.";
  70201. }
  70202. var endOfHeader = false;
  70203. var findFormat = false;
  70204. var lineIndex = 0;
  70205. do {
  70206. lineIndex += (line.length + 1);
  70207. line = this.readStringLine(uint8array, lineIndex);
  70208. if (line == "FORMAT=32-bit_rle_rgbe") {
  70209. findFormat = true;
  70210. }
  70211. else if (line.length == 0) {
  70212. endOfHeader = true;
  70213. }
  70214. } while (!endOfHeader);
  70215. if (!findFormat) {
  70216. throw "HDR Bad header format, unsupported FORMAT";
  70217. }
  70218. lineIndex += (line.length + 1);
  70219. line = this.readStringLine(uint8array, lineIndex);
  70220. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70221. var match = sizeRegexp.exec(line);
  70222. // TODO. Support +Y and -X if needed.
  70223. if (!match || match.length < 3) {
  70224. throw "HDR Bad header format, no size";
  70225. }
  70226. width = parseInt(match[2]);
  70227. height = parseInt(match[1]);
  70228. if (width < 8 || width > 0x7fff) {
  70229. throw "HDR Bad header format, unsupported size";
  70230. }
  70231. lineIndex += (line.length + 1);
  70232. return {
  70233. height: height,
  70234. width: width,
  70235. dataPosition: lineIndex
  70236. };
  70237. };
  70238. /**
  70239. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  70240. * This RGBE texture needs to store the information as a panorama.
  70241. *
  70242. * More information on this format are available here:
  70243. * https://en.wikipedia.org/wiki/RGBE_image_format
  70244. *
  70245. * @param buffer The binary file stored in an array buffer.
  70246. * @param size The expected size of the extracted cubemap.
  70247. * @return The Cube Map information.
  70248. */
  70249. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  70250. var uint8array = new Uint8Array(buffer);
  70251. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  70252. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70253. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  70254. return cubeMapData;
  70255. };
  70256. /**
  70257. * Returns the pixels data extracted from an RGBE texture.
  70258. * This pixels will be stored left to right up to down in the R G B order in one array.
  70259. *
  70260. * More information on this format are available here:
  70261. * https://en.wikipedia.org/wiki/RGBE_image_format
  70262. *
  70263. * @param uint8array The binary file stored in an array buffer.
  70264. * @param hdrInfo The header information of the file.
  70265. * @return The pixels data in RGB right to left up to down order.
  70266. */
  70267. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  70268. // Keep for multi format supports.
  70269. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70270. };
  70271. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  70272. var num_scanlines = hdrInfo.height;
  70273. var scanline_width = hdrInfo.width;
  70274. var a, b, c, d, count;
  70275. var dataIndex = hdrInfo.dataPosition;
  70276. var index = 0, endIndex = 0, i = 0;
  70277. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  70278. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  70279. // 3 channels of 4 bytes per pixel in float.
  70280. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  70281. var resultArray = new Float32Array(resultBuffer);
  70282. // read in each successive scanline
  70283. while (num_scanlines > 0) {
  70284. a = uint8array[dataIndex++];
  70285. b = uint8array[dataIndex++];
  70286. c = uint8array[dataIndex++];
  70287. d = uint8array[dataIndex++];
  70288. if (a != 2 || b != 2 || (c & 0x80)) {
  70289. // this file is not run length encoded
  70290. throw "HDR Bad header format, not RLE";
  70291. }
  70292. if (((c << 8) | d) != scanline_width) {
  70293. throw "HDR Bad header format, wrong scan line width";
  70294. }
  70295. index = 0;
  70296. // read each of the four channels for the scanline into the buffer
  70297. for (i = 0; i < 4; i++) {
  70298. endIndex = (i + 1) * scanline_width;
  70299. while (index < endIndex) {
  70300. a = uint8array[dataIndex++];
  70301. b = uint8array[dataIndex++];
  70302. if (a > 128) {
  70303. // a run of the same value
  70304. count = a - 128;
  70305. if ((count == 0) || (count > endIndex - index)) {
  70306. throw "HDR Bad Format, bad scanline data (run)";
  70307. }
  70308. while (count-- > 0) {
  70309. scanLineArray[index++] = b;
  70310. }
  70311. }
  70312. else {
  70313. // a non-run
  70314. count = a;
  70315. if ((count == 0) || (count > endIndex - index)) {
  70316. throw "HDR Bad Format, bad scanline data (non-run)";
  70317. }
  70318. scanLineArray[index++] = b;
  70319. if (--count > 0) {
  70320. for (var j = 0; j < count; j++) {
  70321. scanLineArray[index++] = uint8array[dataIndex++];
  70322. }
  70323. }
  70324. }
  70325. }
  70326. }
  70327. // now convert data from buffer into floats
  70328. for (i = 0; i < scanline_width; i++) {
  70329. a = scanLineArray[i];
  70330. b = scanLineArray[i + scanline_width];
  70331. c = scanLineArray[i + 2 * scanline_width];
  70332. d = scanLineArray[i + 3 * scanline_width];
  70333. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  70334. }
  70335. num_scanlines--;
  70336. }
  70337. return resultArray;
  70338. };
  70339. return HDRTools;
  70340. }());
  70341. BABYLON.HDRTools = HDRTools;
  70342. })(BABYLON || (BABYLON = {}));
  70343. //# sourceMappingURL=babylon.hdr.js.map
  70344. var BABYLON;
  70345. (function (BABYLON) {
  70346. /**
  70347. * This represents a texture coming from an HDR input.
  70348. *
  70349. * The only supported format is currently panorama picture stored in RGBE format.
  70350. * Example of such files can be found on HDRLib: http://hdrlib.com/
  70351. */
  70352. var HDRCubeTexture = /** @class */ (function (_super) {
  70353. __extends(HDRCubeTexture, _super);
  70354. /**
  70355. * Instantiates an HDRTexture from the following parameters.
  70356. *
  70357. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  70358. * @param scene The scene the texture will be used in
  70359. * @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.
  70360. * @param noMipmap Forces to not generate the mipmap if true
  70361. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  70362. * @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)
  70363. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  70364. */
  70365. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  70366. if (noMipmap === void 0) { noMipmap = false; }
  70367. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70368. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70369. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70370. if (onLoad === void 0) { onLoad = null; }
  70371. if (onError === void 0) { onError = null; }
  70372. var _this = _super.call(this, scene) || this;
  70373. _this._useInGammaSpace = false;
  70374. _this._generateHarmonics = true;
  70375. _this._isBABYLONPreprocessed = false;
  70376. _this._onLoad = null;
  70377. _this._onError = null;
  70378. /**
  70379. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  70380. */
  70381. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70382. /**
  70383. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  70384. * This is usefull at run time to apply the good shader.
  70385. */
  70386. _this.isPMREM = false;
  70387. _this._isBlocking = true;
  70388. if (!url) {
  70389. return _this;
  70390. }
  70391. _this.name = url;
  70392. _this.url = url;
  70393. _this.hasAlpha = false;
  70394. _this.isCube = true;
  70395. _this._textureMatrix = BABYLON.Matrix.Identity();
  70396. _this._onLoad = onLoad;
  70397. _this._onError = onError;
  70398. _this.gammaSpace = false;
  70399. var caps = scene.getEngine().getCaps();
  70400. if (size) {
  70401. _this._isBABYLONPreprocessed = false;
  70402. _this._noMipmap = noMipmap;
  70403. _this._size = size;
  70404. _this._useInGammaSpace = useInGammaSpace;
  70405. _this._usePMREMGenerator = usePMREMGenerator &&
  70406. caps.textureLOD &&
  70407. caps.textureFloat &&
  70408. !_this._useInGammaSpace;
  70409. }
  70410. else {
  70411. _this._isBABYLONPreprocessed = true;
  70412. _this._noMipmap = false;
  70413. _this._useInGammaSpace = false;
  70414. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  70415. !_this._useInGammaSpace;
  70416. }
  70417. _this.isPMREM = _this._usePMREMGenerator;
  70418. _this._texture = _this._getFromCache(url, _this._noMipmap);
  70419. if (!_this._texture) {
  70420. if (!scene.useDelayedTextureLoading) {
  70421. _this.loadTexture();
  70422. }
  70423. else {
  70424. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70425. }
  70426. }
  70427. return _this;
  70428. }
  70429. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  70430. /**
  70431. * Gets wether or not the texture is blocking during loading.
  70432. */
  70433. get: function () {
  70434. return this._isBlocking;
  70435. },
  70436. /**
  70437. * Sets wether or not the texture is blocking during loading.
  70438. */
  70439. set: function (value) {
  70440. this._isBlocking = value;
  70441. },
  70442. enumerable: true,
  70443. configurable: true
  70444. });
  70445. /**
  70446. * Occurs when the file is a preprocessed .babylon.hdr file.
  70447. */
  70448. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  70449. var _this = this;
  70450. var mipLevels = 0;
  70451. var floatArrayView = null;
  70452. var scene = this.getScene();
  70453. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  70454. var mips = new Array();
  70455. if (!floatArrayView) {
  70456. return mips;
  70457. }
  70458. var startIndex = 30;
  70459. for (var level = 0; level < mipLevels; level++) {
  70460. mips.push([]);
  70461. // Fill each pixel of the mip level.
  70462. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  70463. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70464. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  70465. mips[level].push(faceData);
  70466. startIndex += faceSize;
  70467. }
  70468. }
  70469. return mips;
  70470. } : null;
  70471. var callback = function (buffer) {
  70472. var scene = _this.getScene();
  70473. if (!scene) {
  70474. return null;
  70475. }
  70476. // Create Native Array Views
  70477. var intArrayView = new Int32Array(buffer);
  70478. floatArrayView = new Float32Array(buffer);
  70479. // Fill header.
  70480. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  70481. _this._size = intArrayView[1]; // CubeMap max mip face size.
  70482. // Update Texture Information.
  70483. if (!_this._texture) {
  70484. return null;
  70485. }
  70486. _this._texture.updateSize(_this._size, _this._size);
  70487. // Fill polynomial information.
  70488. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  70489. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  70490. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  70491. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  70492. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  70493. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  70494. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  70495. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  70496. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  70497. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  70498. _this.sphericalPolynomial = sphericalPolynomial;
  70499. // Fill pixel data.
  70500. mipLevels = intArrayView[29]; // Number of mip levels.
  70501. var startIndex = 30;
  70502. var data = [];
  70503. var faceSize = Math.pow(_this._size, 2) * 3;
  70504. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70505. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  70506. startIndex += faceSize;
  70507. }
  70508. var results = [];
  70509. var byteArray = null;
  70510. // Push each faces.
  70511. for (var k = 0; k < 6; k++) {
  70512. var dataFace = null;
  70513. // To be deprecated.
  70514. if (version === 1) {
  70515. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  70516. dataFace = data[j];
  70517. }
  70518. // If special cases.
  70519. if (!mipmapGenerator && dataFace) {
  70520. if (!scene.getEngine().getCaps().textureFloat) {
  70521. // 3 channels of 1 bytes per pixel in bytes.
  70522. var byteBuffer = new ArrayBuffer(faceSize);
  70523. byteArray = new Uint8Array(byteBuffer);
  70524. }
  70525. for (var i = 0; i < _this._size * _this._size; i++) {
  70526. // Put in gamma space if requested.
  70527. if (_this._useInGammaSpace) {
  70528. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  70529. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  70530. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  70531. }
  70532. // Convert to int texture for fallback.
  70533. if (byteArray) {
  70534. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  70535. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  70536. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  70537. // May use luminance instead if the result is not accurate.
  70538. var max = Math.max(Math.max(r, g), b);
  70539. if (max > 255) {
  70540. var scale = 255 / max;
  70541. r *= scale;
  70542. g *= scale;
  70543. b *= scale;
  70544. }
  70545. byteArray[(i * 3) + 0] = r;
  70546. byteArray[(i * 3) + 1] = g;
  70547. byteArray[(i * 3) + 2] = b;
  70548. }
  70549. }
  70550. }
  70551. // Fill the array accordingly.
  70552. if (byteArray) {
  70553. results.push(byteArray);
  70554. }
  70555. else {
  70556. results.push(dataFace);
  70557. }
  70558. }
  70559. return results;
  70560. };
  70561. if (scene) {
  70562. 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);
  70563. }
  70564. };
  70565. /**
  70566. * Occurs when the file is raw .hdr file.
  70567. */
  70568. HDRCubeTexture.prototype.loadHDRTexture = function () {
  70569. var _this = this;
  70570. var callback = function (buffer) {
  70571. var scene = _this.getScene();
  70572. if (!scene) {
  70573. return null;
  70574. }
  70575. // Extract the raw linear data.
  70576. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  70577. // Generate harmonics if needed.
  70578. if (_this._generateHarmonics) {
  70579. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  70580. _this.sphericalPolynomial = sphericalPolynomial;
  70581. }
  70582. var results = [];
  70583. var byteArray = null;
  70584. // Push each faces.
  70585. for (var j = 0; j < 6; j++) {
  70586. // Create uintarray fallback.
  70587. if (!scene.getEngine().getCaps().textureFloat) {
  70588. // 3 channels of 1 bytes per pixel in bytes.
  70589. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  70590. byteArray = new Uint8Array(byteBuffer);
  70591. }
  70592. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  70593. // If special cases.
  70594. if (_this._useInGammaSpace || byteArray) {
  70595. for (var i = 0; i < _this._size * _this._size; i++) {
  70596. // Put in gamma space if requested.
  70597. if (_this._useInGammaSpace) {
  70598. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  70599. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  70600. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  70601. }
  70602. // Convert to int texture for fallback.
  70603. if (byteArray) {
  70604. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  70605. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  70606. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  70607. // May use luminance instead if the result is not accurate.
  70608. var max = Math.max(Math.max(r, g), b);
  70609. if (max > 255) {
  70610. var scale = 255 / max;
  70611. r *= scale;
  70612. g *= scale;
  70613. b *= scale;
  70614. }
  70615. byteArray[(i * 3) + 0] = r;
  70616. byteArray[(i * 3) + 1] = g;
  70617. byteArray[(i * 3) + 2] = b;
  70618. }
  70619. }
  70620. }
  70621. if (byteArray) {
  70622. results.push(byteArray);
  70623. }
  70624. else {
  70625. results.push(dataFace);
  70626. }
  70627. }
  70628. return results;
  70629. };
  70630. var mipmapGenerator = null;
  70631. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  70632. // if (!this._noMipmap &&
  70633. // this._usePMREMGenerator) {
  70634. // mipmapGenerator = (data: ArrayBufferView[]) => {
  70635. // // Custom setup of the generator matching with the PBR shader values.
  70636. // var generator = new BABYLON.PMREMGenerator(data,
  70637. // this._size,
  70638. // this._size,
  70639. // 0,
  70640. // 3,
  70641. // this.getScene().getEngine().getCaps().textureFloat,
  70642. // 2048,
  70643. // 0.25,
  70644. // false,
  70645. // true);
  70646. // return generator.filterCubeMap();
  70647. // };
  70648. // }
  70649. var scene = this.getScene();
  70650. if (scene) {
  70651. 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);
  70652. }
  70653. };
  70654. /**
  70655. * Starts the loading process of the texture.
  70656. */
  70657. HDRCubeTexture.prototype.loadTexture = function () {
  70658. if (this._isBABYLONPreprocessed) {
  70659. this.loadBabylonTexture();
  70660. }
  70661. else {
  70662. this.loadHDRTexture();
  70663. }
  70664. };
  70665. HDRCubeTexture.prototype.clone = function () {
  70666. var scene = this.getScene();
  70667. if (!scene) {
  70668. return this;
  70669. }
  70670. var size = (this._isBABYLONPreprocessed ? null : this._size);
  70671. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  70672. // Base texture
  70673. newTexture.level = this.level;
  70674. newTexture.wrapU = this.wrapU;
  70675. newTexture.wrapV = this.wrapV;
  70676. newTexture.coordinatesIndex = this.coordinatesIndex;
  70677. newTexture.coordinatesMode = this.coordinatesMode;
  70678. return newTexture;
  70679. };
  70680. // Methods
  70681. HDRCubeTexture.prototype.delayLoad = function () {
  70682. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  70683. return;
  70684. }
  70685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  70686. this._texture = this._getFromCache(this.url, this._noMipmap);
  70687. if (!this._texture) {
  70688. this.loadTexture();
  70689. }
  70690. };
  70691. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  70692. return this._textureMatrix;
  70693. };
  70694. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  70695. this._textureMatrix = value;
  70696. };
  70697. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  70698. var texture = null;
  70699. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  70700. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  70701. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  70702. texture.name = parsedTexture.name;
  70703. texture.hasAlpha = parsedTexture.hasAlpha;
  70704. texture.level = parsedTexture.level;
  70705. texture.coordinatesMode = parsedTexture.coordinatesMode;
  70706. texture.isBlocking = parsedTexture.isBlocking;
  70707. }
  70708. return texture;
  70709. };
  70710. HDRCubeTexture.prototype.serialize = function () {
  70711. if (!this.name) {
  70712. return null;
  70713. }
  70714. var serializationObject = {};
  70715. serializationObject.name = this.name;
  70716. serializationObject.hasAlpha = this.hasAlpha;
  70717. serializationObject.isCube = true;
  70718. serializationObject.level = this.level;
  70719. serializationObject.size = this._size;
  70720. serializationObject.coordinatesMode = this.coordinatesMode;
  70721. serializationObject.useInGammaSpace = this._useInGammaSpace;
  70722. serializationObject.generateHarmonics = this._generateHarmonics;
  70723. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  70724. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  70725. serializationObject.customType = "BABYLON.HDRCubeTexture";
  70726. serializationObject.noMipmap = this._noMipmap;
  70727. serializationObject.isBlocking = this._isBlocking;
  70728. return serializationObject;
  70729. };
  70730. /**
  70731. * Saves as a file the data contained in the texture in a binary format.
  70732. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  70733. * as the spherical used in the lighting.
  70734. * @param url The HDR file url.
  70735. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  70736. * @param onError Method called if any error happens during download.
  70737. * @return The packed binary data.
  70738. */
  70739. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  70740. if (onError === void 0) { onError = null; }
  70741. var callback = function (buffer) {
  70742. var data = new Blob([buffer], { type: 'application/octet-stream' });
  70743. // Returns a URL you can use as a href.
  70744. var objUrl = window.URL.createObjectURL(data);
  70745. // Simulates a link to it and click to dowload.
  70746. var a = document.createElement("a");
  70747. document.body.appendChild(a);
  70748. a.style.display = "none";
  70749. a.href = objUrl;
  70750. a.download = "envmap.babylon.hdr";
  70751. a.click();
  70752. };
  70753. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  70754. };
  70755. /**
  70756. * Serializes the data contained in the texture in a binary format.
  70757. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  70758. * as the spherical used in the lighting.
  70759. * @param url The HDR file url.
  70760. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  70761. * @param onError Method called if any error happens during download.
  70762. * @return The packed binary data.
  70763. */
  70764. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  70765. if (onError === void 0) { onError = null; }
  70766. // Needs the url tho create the texture.
  70767. if (!url) {
  70768. return;
  70769. }
  70770. // Check Power of two size.
  70771. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  70772. return;
  70773. }
  70774. // Coming Back in 3.x.
  70775. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  70776. };
  70777. HDRCubeTexture._facesMapping = [
  70778. "right",
  70779. "left",
  70780. "up",
  70781. "down",
  70782. "front",
  70783. "back"
  70784. ];
  70785. return HDRCubeTexture;
  70786. }(BABYLON.BaseTexture));
  70787. BABYLON.HDRCubeTexture = HDRCubeTexture;
  70788. })(BABYLON || (BABYLON = {}));
  70789. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  70790. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  70791. // Huge respect for a such great lib.
  70792. // Earcut license:
  70793. // Copyright (c) 2016, Mapbox
  70794. //
  70795. // Permission to use, copy, modify, and/or distribute this software for any purpose
  70796. // with or without fee is hereby granted, provided that the above copyright notice
  70797. // and this permission notice appear in all copies.
  70798. //
  70799. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  70800. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  70801. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  70802. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  70803. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  70804. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  70805. // THIS SOFTWARE.
  70806. var Earcut;
  70807. (function (Earcut) {
  70808. /**
  70809. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  70810. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  70811. * @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).
  70812. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  70813. */
  70814. function earcut(data, holeIndices, dim) {
  70815. dim = dim || 2;
  70816. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  70817. if (!outerNode)
  70818. return triangles;
  70819. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  70820. if (hasHoles)
  70821. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  70822. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  70823. if (data.length > 80 * dim) {
  70824. minX = maxX = data[0];
  70825. minY = maxY = data[1];
  70826. for (var i = dim; i < outerLen; i += dim) {
  70827. x = data[i];
  70828. y = data[i + 1];
  70829. if (x < minX)
  70830. minX = x;
  70831. if (y < minY)
  70832. minY = y;
  70833. if (x > maxX)
  70834. maxX = x;
  70835. if (y > maxY)
  70836. maxY = y;
  70837. }
  70838. // minX, minY and size are later used to transform coords into integers for z-order calculation
  70839. size = Math.max(maxX - minX, maxY - minY);
  70840. }
  70841. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  70842. return triangles;
  70843. }
  70844. Earcut.earcut = earcut;
  70845. var Node = /** @class */ (function () {
  70846. function Node(i, x, y) {
  70847. this.i = i;
  70848. this.x = x;
  70849. this.y = y;
  70850. this.prev = null;
  70851. this.next = null;
  70852. this.z = null;
  70853. this.prevZ = null;
  70854. this.nextZ = null;
  70855. this.steiner = false;
  70856. }
  70857. return Node;
  70858. }());
  70859. // create a circular doubly linked list from polygon points in the specified winding order
  70860. function linkedList(data, start, end, dim, clockwise) {
  70861. var i, last = null;
  70862. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  70863. for (i = start; i < end; i += dim)
  70864. last = insertNode(i, data[i], data[i + 1], last);
  70865. }
  70866. else {
  70867. for (i = end - dim; i >= start; i -= dim)
  70868. last = insertNode(i, data[i], data[i + 1], last);
  70869. }
  70870. if (last && equals(last, last.next)) {
  70871. removeNode(last);
  70872. last = last.next;
  70873. }
  70874. return last;
  70875. }
  70876. // eliminate colinear or duplicate points
  70877. function filterPoints(start, end) {
  70878. if (!start)
  70879. return start;
  70880. if (!end)
  70881. end = start;
  70882. var p = start, again;
  70883. do {
  70884. again = false;
  70885. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  70886. removeNode(p);
  70887. p = end = p.prev;
  70888. if (p === p.next)
  70889. return undefined;
  70890. again = true;
  70891. }
  70892. else {
  70893. p = p.next;
  70894. }
  70895. } while (again || p !== end);
  70896. return end;
  70897. }
  70898. // main ear slicing loop which triangulates a polygon (given as a linked list)
  70899. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  70900. if (!ear)
  70901. return;
  70902. // interlink polygon nodes in z-order
  70903. if (!pass && size)
  70904. indexCurve(ear, minX, minY, size);
  70905. var stop = ear, prev, next;
  70906. // iterate through ears, slicing them one by one
  70907. while (ear.prev !== ear.next) {
  70908. prev = ear.prev;
  70909. next = ear.next;
  70910. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  70911. // cut off the triangle
  70912. triangles.push(prev.i / dim);
  70913. triangles.push(ear.i / dim);
  70914. triangles.push(next.i / dim);
  70915. removeNode(ear);
  70916. // skipping the next vertice leads to less sliver triangles
  70917. ear = next.next;
  70918. stop = next.next;
  70919. continue;
  70920. }
  70921. ear = next;
  70922. // if we looped through the whole remaining polygon and can't find any more ears
  70923. if (ear === stop) {
  70924. // try filtering points and slicing again
  70925. if (!pass) {
  70926. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  70927. // if this didn't work, try curing all small self-intersections locally
  70928. }
  70929. else if (pass === 1) {
  70930. ear = cureLocalIntersections(ear, triangles, dim);
  70931. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  70932. // as a last resort, try splitting the remaining polygon into two
  70933. }
  70934. else if (pass === 2) {
  70935. splitEarcut(ear, triangles, dim, minX, minY, size);
  70936. }
  70937. break;
  70938. }
  70939. }
  70940. }
  70941. // check whether a polygon node forms a valid ear with adjacent nodes
  70942. function isEar(ear) {
  70943. var a = ear.prev, b = ear, c = ear.next;
  70944. if (area(a, b, c) >= 0)
  70945. return false; // reflex, can't be an ear
  70946. // now make sure we don't have other points inside the potential ear
  70947. var p = ear.next.next;
  70948. while (p !== ear.prev) {
  70949. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  70950. area(p.prev, p, p.next) >= 0)
  70951. return false;
  70952. p = p.next;
  70953. }
  70954. return true;
  70955. }
  70956. function isEarHashed(ear, minX, minY, size) {
  70957. var a = ear.prev, b = ear, c = ear.next;
  70958. if (area(a, b, c) >= 0)
  70959. return false; // reflex, can't be an ear
  70960. // triangle bbox; min & max are calculated like this for speed
  70961. 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);
  70962. // z-order range for the current triangle bbox;
  70963. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  70964. // first look for points inside the triangle in increasing z-order
  70965. var p = ear.nextZ;
  70966. while (p && p.z <= maxZ) {
  70967. if (p !== ear.prev &&
  70968. p !== ear.next &&
  70969. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  70970. area(p.prev, p, p.next) >= 0)
  70971. return false;
  70972. p = p.nextZ;
  70973. }
  70974. // then look for points in decreasing z-order
  70975. p = ear.prevZ;
  70976. while (p && p.z >= minZ) {
  70977. if (p !== ear.prev &&
  70978. p !== ear.next &&
  70979. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  70980. area(p.prev, p, p.next) >= 0)
  70981. return false;
  70982. p = p.prevZ;
  70983. }
  70984. return true;
  70985. }
  70986. // go through all polygon nodes and cure small local self-intersections
  70987. function cureLocalIntersections(start, triangles, dim) {
  70988. var p = start;
  70989. do {
  70990. var a = p.prev, b = p.next.next;
  70991. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  70992. triangles.push(a.i / dim);
  70993. triangles.push(p.i / dim);
  70994. triangles.push(b.i / dim);
  70995. // remove two nodes involved
  70996. removeNode(p);
  70997. removeNode(p.next);
  70998. p = start = b;
  70999. }
  71000. p = p.next;
  71001. } while (p !== start);
  71002. return p;
  71003. }
  71004. // try splitting polygon into two and triangulate them independently
  71005. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71006. // look for a valid diagonal that divides the polygon into two
  71007. var a = start;
  71008. do {
  71009. var b = a.next.next;
  71010. while (b !== a.prev) {
  71011. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71012. // split the polygon in two by the diagonal
  71013. var c = splitPolygon(a, b);
  71014. // filter colinear points around the cuts
  71015. a = filterPoints(a, a.next);
  71016. c = filterPoints(c, c.next);
  71017. // run earcut on each half
  71018. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71019. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71020. return;
  71021. }
  71022. b = b.next;
  71023. }
  71024. a = a.next;
  71025. } while (a !== start);
  71026. }
  71027. // link every hole into the outer loop, producing a single-ring polygon without holes
  71028. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71029. var queue = [], i, len, start, end, list;
  71030. for (i = 0, len = holeIndices.length; i < len; i++) {
  71031. start = holeIndices[i] * dim;
  71032. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71033. list = linkedList(data, start, end, dim, false);
  71034. if (list === list.next)
  71035. list.steiner = true;
  71036. queue.push(getLeftmost(list));
  71037. }
  71038. queue.sort(compareX);
  71039. // process holes from left to right
  71040. for (i = 0; i < queue.length; i++) {
  71041. eliminateHole(queue[i], outerNode);
  71042. outerNode = filterPoints(outerNode, outerNode.next);
  71043. }
  71044. return outerNode;
  71045. }
  71046. function compareX(a, b) {
  71047. return a.x - b.x;
  71048. }
  71049. // find a bridge between vertices that connects hole with an outer ring and and link it
  71050. function eliminateHole(hole, outerNode) {
  71051. outerNode = findHoleBridge(hole, outerNode);
  71052. if (outerNode) {
  71053. var b = splitPolygon(outerNode, hole);
  71054. filterPoints(b, b.next);
  71055. }
  71056. }
  71057. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71058. function findHoleBridge(hole, outerNode) {
  71059. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71060. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71061. // segment's endpoint with lesser x will be potential connection point
  71062. do {
  71063. if (hy <= p.y && hy >= p.next.y) {
  71064. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71065. if (x <= hx && x > qx) {
  71066. qx = x;
  71067. if (x === hx) {
  71068. if (hy === p.y)
  71069. return p;
  71070. if (hy === p.next.y)
  71071. return p.next;
  71072. }
  71073. m = p.x < p.next.x ? p : p.next;
  71074. }
  71075. }
  71076. p = p.next;
  71077. } while (p !== outerNode);
  71078. if (!m)
  71079. return null;
  71080. if (hx === qx)
  71081. return m.prev; // hole touches outer segment; pick lower endpoint
  71082. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71083. // if there are no points found, we have a valid connection;
  71084. // otherwise choose the point of the minimum angle with the ray as connection point
  71085. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71086. p = m.next;
  71087. while (p !== stop) {
  71088. if (hx >= p.x &&
  71089. p.x >= mx &&
  71090. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71091. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71092. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71093. m = p;
  71094. tanMin = tan;
  71095. }
  71096. }
  71097. p = p.next;
  71098. }
  71099. return m;
  71100. }
  71101. // interlink polygon nodes in z-order
  71102. function indexCurve(start, minX, minY, size) {
  71103. var p = start;
  71104. do {
  71105. if (p.z === null)
  71106. p.z = zOrder(p.x, p.y, minX, minY, size);
  71107. p.prevZ = p.prev;
  71108. p.nextZ = p.next;
  71109. p = p.next;
  71110. } while (p !== start);
  71111. p.prevZ.nextZ = null;
  71112. p.prevZ = null;
  71113. sortLinked(p);
  71114. }
  71115. // Simon Tatham's linked list merge sort algorithm
  71116. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71117. function sortLinked(list) {
  71118. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71119. do {
  71120. p = list;
  71121. list = null;
  71122. tail = null;
  71123. numMerges = 0;
  71124. while (p) {
  71125. numMerges++;
  71126. q = p;
  71127. pSize = 0;
  71128. for (i = 0; i < inSize; i++) {
  71129. pSize++;
  71130. q = q.nextZ;
  71131. if (!q)
  71132. break;
  71133. }
  71134. qSize = inSize;
  71135. while (pSize > 0 || (qSize > 0 && q)) {
  71136. if (pSize === 0) {
  71137. e = q;
  71138. q = q.nextZ;
  71139. qSize--;
  71140. }
  71141. else if (qSize === 0 || !q) {
  71142. e = p;
  71143. p = p.nextZ;
  71144. pSize--;
  71145. }
  71146. else if (p.z <= q.z) {
  71147. e = p;
  71148. p = p.nextZ;
  71149. pSize--;
  71150. }
  71151. else {
  71152. e = q;
  71153. q = q.nextZ;
  71154. qSize--;
  71155. }
  71156. if (tail)
  71157. tail.nextZ = e;
  71158. else
  71159. list = e;
  71160. e.prevZ = tail;
  71161. tail = e;
  71162. }
  71163. p = q;
  71164. }
  71165. tail.nextZ = null;
  71166. inSize *= 2;
  71167. } while (numMerges > 1);
  71168. return list;
  71169. }
  71170. // z-order of a point given coords and size of the data bounding box
  71171. function zOrder(x, y, minX, minY, size) {
  71172. // coords are transformed into non-negative 15-bit integer range
  71173. x = 32767 * (x - minX) / size;
  71174. y = 32767 * (y - minY) / size;
  71175. x = (x | (x << 8)) & 0x00FF00FF;
  71176. x = (x | (x << 4)) & 0x0F0F0F0F;
  71177. x = (x | (x << 2)) & 0x33333333;
  71178. x = (x | (x << 1)) & 0x55555555;
  71179. y = (y | (y << 8)) & 0x00FF00FF;
  71180. y = (y | (y << 4)) & 0x0F0F0F0F;
  71181. y = (y | (y << 2)) & 0x33333333;
  71182. y = (y | (y << 1)) & 0x55555555;
  71183. return x | (y << 1);
  71184. }
  71185. // find the leftmost node of a polygon ring
  71186. function getLeftmost(start) {
  71187. var p = start, leftmost = start;
  71188. do {
  71189. if (p.x < leftmost.x)
  71190. leftmost = p;
  71191. p = p.next;
  71192. } while (p !== start);
  71193. return leftmost;
  71194. }
  71195. // check if a point lies within a convex triangle
  71196. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71197. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71198. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71199. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71200. }
  71201. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71202. function isValidDiagonal(a, b) {
  71203. return a.next.i !== b.i &&
  71204. a.prev.i !== b.i &&
  71205. !intersectsPolygon(a, b) &&
  71206. locallyInside(a, b) &&
  71207. locallyInside(b, a) &&
  71208. middleInside(a, b);
  71209. }
  71210. // signed area of a triangle
  71211. function area(p, q, r) {
  71212. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71213. }
  71214. // check if two points are equal
  71215. function equals(p1, p2) {
  71216. return p1.x === p2.x && p1.y === p2.y;
  71217. }
  71218. // check if two segments intersect
  71219. function intersects(p1, q1, p2, q2) {
  71220. if ((equals(p1, q1) && equals(p2, q2)) ||
  71221. (equals(p1, q2) && equals(p2, q1)))
  71222. return true;
  71223. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71224. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71225. }
  71226. // check if a polygon diagonal intersects any polygon segments
  71227. function intersectsPolygon(a, b) {
  71228. var p = a;
  71229. do {
  71230. if (p.i !== a.i &&
  71231. p.next.i !== a.i &&
  71232. p.i !== b.i &&
  71233. p.next.i !== b.i &&
  71234. intersects(p, p.next, a, b))
  71235. return true;
  71236. p = p.next;
  71237. } while (p !== a);
  71238. return false;
  71239. }
  71240. // check if a polygon diagonal is locally inside the polygon
  71241. function locallyInside(a, b) {
  71242. return area(a.prev, a, a.next) < 0
  71243. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  71244. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  71245. }
  71246. // check if the middle point of a polygon diagonal is inside the polygon
  71247. function middleInside(a, b) {
  71248. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  71249. do {
  71250. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  71251. inside = !inside;
  71252. p = p.next;
  71253. } while (p !== a);
  71254. return inside;
  71255. }
  71256. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  71257. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  71258. function splitPolygon(a, b) {
  71259. 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;
  71260. a.next = b;
  71261. b.prev = a;
  71262. a2.next = an;
  71263. an.prev = a2;
  71264. b2.next = a2;
  71265. a2.prev = b2;
  71266. bp.next = b2;
  71267. b2.prev = bp;
  71268. return b2;
  71269. }
  71270. // create a node and optionally link it with previous one (in a circular doubly linked list)
  71271. function insertNode(i, x, y, last) {
  71272. var p = new Node(i, x, y);
  71273. if (!last) {
  71274. p.prev = p;
  71275. p.next = p;
  71276. }
  71277. else {
  71278. p.next = last.next;
  71279. p.prev = last;
  71280. last.next.prev = p;
  71281. last.next = p;
  71282. }
  71283. return p;
  71284. }
  71285. function removeNode(p) {
  71286. p.next.prev = p.prev;
  71287. p.prev.next = p.next;
  71288. if (p.prevZ)
  71289. p.prevZ.nextZ = p.nextZ;
  71290. if (p.nextZ)
  71291. p.nextZ.prevZ = p.prevZ;
  71292. }
  71293. /**
  71294. * return a percentage difference between the polygon area and its triangulation area;
  71295. * used to verify correctness of triangulation
  71296. */
  71297. function deviation(data, holeIndices, dim, triangles) {
  71298. var hasHoles = holeIndices && holeIndices.length;
  71299. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  71300. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  71301. if (hasHoles) {
  71302. for (var i = 0, len = holeIndices.length; i < len; i++) {
  71303. var start = holeIndices[i] * dim;
  71304. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71305. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  71306. }
  71307. }
  71308. var trianglesArea = 0;
  71309. for (i = 0; i < triangles.length; i += 3) {
  71310. var a = triangles[i] * dim;
  71311. var b = triangles[i + 1] * dim;
  71312. var c = triangles[i + 2] * dim;
  71313. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  71314. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  71315. }
  71316. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  71317. }
  71318. Earcut.deviation = deviation;
  71319. ;
  71320. function signedArea(data, start, end, dim) {
  71321. var sum = 0;
  71322. for (var i = start, j = end - dim; i < end; i += dim) {
  71323. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  71324. j = i;
  71325. }
  71326. return sum;
  71327. }
  71328. /**
  71329. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  71330. */
  71331. function flatten(data) {
  71332. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  71333. for (var i = 0; i < data.length; i++) {
  71334. for (var j = 0; j < data[i].length; j++) {
  71335. for (var d = 0; d < dim; d++)
  71336. result.vertices.push(data[i][j][d]);
  71337. }
  71338. if (i > 0) {
  71339. holeIndex += data[i - 1].length;
  71340. result.holes.push(holeIndex);
  71341. }
  71342. }
  71343. return result;
  71344. }
  71345. Earcut.flatten = flatten;
  71346. ;
  71347. })(Earcut || (Earcut = {}));
  71348. //# sourceMappingURL=babylon.earcut.js.map
  71349. var BABYLON;
  71350. (function (BABYLON) {
  71351. var IndexedVector2 = /** @class */ (function (_super) {
  71352. __extends(IndexedVector2, _super);
  71353. function IndexedVector2(original, index) {
  71354. var _this = _super.call(this, original.x, original.y) || this;
  71355. _this.index = index;
  71356. return _this;
  71357. }
  71358. return IndexedVector2;
  71359. }(BABYLON.Vector2));
  71360. var PolygonPoints = /** @class */ (function () {
  71361. function PolygonPoints() {
  71362. this.elements = new Array();
  71363. }
  71364. PolygonPoints.prototype.add = function (originalPoints) {
  71365. var _this = this;
  71366. var result = new Array();
  71367. originalPoints.forEach(function (point) {
  71368. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  71369. var newPoint = new IndexedVector2(point, _this.elements.length);
  71370. result.push(newPoint);
  71371. _this.elements.push(newPoint);
  71372. }
  71373. });
  71374. return result;
  71375. };
  71376. PolygonPoints.prototype.computeBounds = function () {
  71377. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71378. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71379. this.elements.forEach(function (point) {
  71380. // x
  71381. if (point.x < lmin.x) {
  71382. lmin.x = point.x;
  71383. }
  71384. else if (point.x > lmax.x) {
  71385. lmax.x = point.x;
  71386. }
  71387. // y
  71388. if (point.y < lmin.y) {
  71389. lmin.y = point.y;
  71390. }
  71391. else if (point.y > lmax.y) {
  71392. lmax.y = point.y;
  71393. }
  71394. });
  71395. return {
  71396. min: lmin,
  71397. max: lmax,
  71398. width: lmax.x - lmin.x,
  71399. height: lmax.y - lmin.y
  71400. };
  71401. };
  71402. return PolygonPoints;
  71403. }());
  71404. var Polygon = /** @class */ (function () {
  71405. function Polygon() {
  71406. }
  71407. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  71408. return [
  71409. new BABYLON.Vector2(xmin, ymin),
  71410. new BABYLON.Vector2(xmax, ymin),
  71411. new BABYLON.Vector2(xmax, ymax),
  71412. new BABYLON.Vector2(xmin, ymax)
  71413. ];
  71414. };
  71415. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  71416. if (cx === void 0) { cx = 0; }
  71417. if (cy === void 0) { cy = 0; }
  71418. if (numberOfSides === void 0) { numberOfSides = 32; }
  71419. var result = new Array();
  71420. var angle = 0;
  71421. var increment = (Math.PI * 2) / numberOfSides;
  71422. for (var i = 0; i < numberOfSides; i++) {
  71423. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  71424. angle -= increment;
  71425. }
  71426. return result;
  71427. };
  71428. Polygon.Parse = function (input) {
  71429. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  71430. var i, result = [];
  71431. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  71432. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  71433. }
  71434. return result;
  71435. };
  71436. Polygon.StartingAt = function (x, y) {
  71437. return BABYLON.Path2.StartingAt(x, y);
  71438. };
  71439. return Polygon;
  71440. }());
  71441. BABYLON.Polygon = Polygon;
  71442. var PolygonMeshBuilder = /** @class */ (function () {
  71443. function PolygonMeshBuilder(name, contours, scene) {
  71444. this._points = new PolygonPoints();
  71445. this._outlinepoints = new PolygonPoints();
  71446. this._holes = new Array();
  71447. this._epoints = new Array();
  71448. this._eholes = new Array();
  71449. this._name = name;
  71450. this._scene = scene;
  71451. var points;
  71452. if (contours instanceof BABYLON.Path2) {
  71453. points = contours.getPoints();
  71454. }
  71455. else {
  71456. points = contours;
  71457. }
  71458. this._addToepoint(points);
  71459. this._points.add(points);
  71460. this._outlinepoints.add(points);
  71461. }
  71462. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  71463. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  71464. var p = points_1[_i];
  71465. this._epoints.push(p.x, p.y);
  71466. }
  71467. };
  71468. PolygonMeshBuilder.prototype.addHole = function (hole) {
  71469. this._points.add(hole);
  71470. var holepoints = new PolygonPoints();
  71471. holepoints.add(hole);
  71472. this._holes.push(holepoints);
  71473. this._eholes.push(this._epoints.length / 2);
  71474. this._addToepoint(hole);
  71475. return this;
  71476. };
  71477. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  71478. var _this = this;
  71479. if (updatable === void 0) { updatable = false; }
  71480. if (depth === void 0) { depth = 0; }
  71481. var result = new BABYLON.Mesh(this._name, this._scene);
  71482. var normals = new Array();
  71483. var positions = new Array();
  71484. var uvs = new Array();
  71485. var bounds = this._points.computeBounds();
  71486. this._points.elements.forEach(function (p) {
  71487. normals.push(0, 1.0, 0);
  71488. positions.push(p.x, 0, p.y);
  71489. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  71490. });
  71491. var indices = new Array();
  71492. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  71493. for (var i = 0; i < res.length; i++) {
  71494. indices.push(res[i]);
  71495. }
  71496. if (depth > 0) {
  71497. var positionscount = (positions.length / 3); //get the current pointcount
  71498. this._points.elements.forEach(function (p) {
  71499. normals.push(0, -1.0, 0);
  71500. positions.push(p.x, -depth, p.y);
  71501. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  71502. });
  71503. var totalCount = indices.length;
  71504. for (var i = 0; i < totalCount; i += 3) {
  71505. var i0 = indices[i + 0];
  71506. var i1 = indices[i + 1];
  71507. var i2 = indices[i + 2];
  71508. indices.push(i2 + positionscount);
  71509. indices.push(i1 + positionscount);
  71510. indices.push(i0 + positionscount);
  71511. }
  71512. //Add the sides
  71513. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  71514. this._holes.forEach(function (hole) {
  71515. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  71516. });
  71517. }
  71518. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  71519. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  71520. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  71521. result.setIndices(indices);
  71522. return result;
  71523. };
  71524. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  71525. var StartIndex = positions.length / 3;
  71526. var ulength = 0;
  71527. for (var i = 0; i < points.elements.length; i++) {
  71528. var p = points.elements[i];
  71529. var p1;
  71530. if ((i + 1) > points.elements.length - 1) {
  71531. p1 = points.elements[0];
  71532. }
  71533. else {
  71534. p1 = points.elements[i + 1];
  71535. }
  71536. positions.push(p.x, 0, p.y);
  71537. positions.push(p.x, -depth, p.y);
  71538. positions.push(p1.x, 0, p1.y);
  71539. positions.push(p1.x, -depth, p1.y);
  71540. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  71541. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  71542. var v3 = v2.subtract(v1);
  71543. var v4 = new BABYLON.Vector3(0, 1, 0);
  71544. var vn = BABYLON.Vector3.Cross(v3, v4);
  71545. vn = vn.normalize();
  71546. uvs.push(ulength / bounds.width, 0);
  71547. uvs.push(ulength / bounds.width, 1);
  71548. ulength += v3.length();
  71549. uvs.push((ulength / bounds.width), 0);
  71550. uvs.push((ulength / bounds.width), 1);
  71551. if (!flip) {
  71552. normals.push(-vn.x, -vn.y, -vn.z);
  71553. normals.push(-vn.x, -vn.y, -vn.z);
  71554. normals.push(-vn.x, -vn.y, -vn.z);
  71555. normals.push(-vn.x, -vn.y, -vn.z);
  71556. indices.push(StartIndex);
  71557. indices.push(StartIndex + 1);
  71558. indices.push(StartIndex + 2);
  71559. indices.push(StartIndex + 1);
  71560. indices.push(StartIndex + 3);
  71561. indices.push(StartIndex + 2);
  71562. }
  71563. else {
  71564. normals.push(vn.x, vn.y, vn.z);
  71565. normals.push(vn.x, vn.y, vn.z);
  71566. normals.push(vn.x, vn.y, vn.z);
  71567. normals.push(vn.x, vn.y, vn.z);
  71568. indices.push(StartIndex);
  71569. indices.push(StartIndex + 2);
  71570. indices.push(StartIndex + 1);
  71571. indices.push(StartIndex + 1);
  71572. indices.push(StartIndex + 2);
  71573. indices.push(StartIndex + 3);
  71574. }
  71575. StartIndex += 4;
  71576. }
  71577. ;
  71578. };
  71579. return PolygonMeshBuilder;
  71580. }());
  71581. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  71582. })(BABYLON || (BABYLON = {}));
  71583. //# sourceMappingURL=babylon.polygonMesh.js.map
  71584. var BABYLON;
  71585. (function (BABYLON) {
  71586. // Unique ID when we import meshes from Babylon to CSG
  71587. var currentCSGMeshId = 0;
  71588. // # class Vertex
  71589. // Represents a vertex of a polygon. Use your own vertex class instead of this
  71590. // one to provide additional features like texture coordinates and vertex
  71591. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  71592. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  71593. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  71594. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  71595. // is not used anywhere else.
  71596. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  71597. var Vertex = /** @class */ (function () {
  71598. function Vertex(pos, normal, uv) {
  71599. this.pos = pos;
  71600. this.normal = normal;
  71601. this.uv = uv;
  71602. }
  71603. Vertex.prototype.clone = function () {
  71604. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  71605. };
  71606. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  71607. // orientation of a polygon is flipped.
  71608. Vertex.prototype.flip = function () {
  71609. this.normal = this.normal.scale(-1);
  71610. };
  71611. // Create a new vertex between this vertex and `other` by linearly
  71612. // interpolating all properties using a parameter of `t`. Subclasses should
  71613. // override this to interpolate additional properties.
  71614. Vertex.prototype.interpolate = function (other, t) {
  71615. 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));
  71616. };
  71617. return Vertex;
  71618. }());
  71619. // # class Plane
  71620. // Represents a plane in 3D space.
  71621. var Plane = /** @class */ (function () {
  71622. function Plane(normal, w) {
  71623. this.normal = normal;
  71624. this.w = w;
  71625. }
  71626. Plane.FromPoints = function (a, b, c) {
  71627. var v0 = c.subtract(a);
  71628. var v1 = b.subtract(a);
  71629. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  71630. return null;
  71631. }
  71632. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  71633. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  71634. };
  71635. Plane.prototype.clone = function () {
  71636. return new Plane(this.normal.clone(), this.w);
  71637. };
  71638. Plane.prototype.flip = function () {
  71639. this.normal.scaleInPlace(-1);
  71640. this.w = -this.w;
  71641. };
  71642. // Split `polygon` by this plane if needed, then put the polygon or polygon
  71643. // fragments in the appropriate lists. Coplanar polygons go into either
  71644. // `coplanarFront` or `coplanarBack` depending on their orientation with
  71645. // respect to this plane. Polygons in front or in back of this plane go into
  71646. // either `front` or `back`.
  71647. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  71648. var COPLANAR = 0;
  71649. var FRONT = 1;
  71650. var BACK = 2;
  71651. var SPANNING = 3;
  71652. // Classify each point as well as the entire polygon into one of the above
  71653. // four classes.
  71654. var polygonType = 0;
  71655. var types = [];
  71656. var i;
  71657. var t;
  71658. for (i = 0; i < polygon.vertices.length; i++) {
  71659. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  71660. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  71661. polygonType |= type;
  71662. types.push(type);
  71663. }
  71664. // Put the polygon in the correct list, splitting it when necessary.
  71665. switch (polygonType) {
  71666. case COPLANAR:
  71667. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  71668. break;
  71669. case FRONT:
  71670. front.push(polygon);
  71671. break;
  71672. case BACK:
  71673. back.push(polygon);
  71674. break;
  71675. case SPANNING:
  71676. var f = [], b = [];
  71677. for (i = 0; i < polygon.vertices.length; i++) {
  71678. var j = (i + 1) % polygon.vertices.length;
  71679. var ti = types[i], tj = types[j];
  71680. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  71681. if (ti !== BACK)
  71682. f.push(vi);
  71683. if (ti !== FRONT)
  71684. b.push(ti !== BACK ? vi.clone() : vi);
  71685. if ((ti | tj) === SPANNING) {
  71686. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  71687. var v = vi.interpolate(vj, t);
  71688. f.push(v);
  71689. b.push(v.clone());
  71690. }
  71691. }
  71692. var poly;
  71693. if (f.length >= 3) {
  71694. poly = new Polygon(f, polygon.shared);
  71695. if (poly.plane)
  71696. front.push(poly);
  71697. }
  71698. if (b.length >= 3) {
  71699. poly = new Polygon(b, polygon.shared);
  71700. if (poly.plane)
  71701. back.push(poly);
  71702. }
  71703. break;
  71704. }
  71705. };
  71706. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  71707. // point is on the plane.
  71708. Plane.EPSILON = 1e-5;
  71709. return Plane;
  71710. }());
  71711. // # class Polygon
  71712. // Represents a convex polygon. The vertices used to initialize a polygon must
  71713. // be coplanar and form a convex loop.
  71714. //
  71715. // Each convex polygon has a `shared` property, which is shared between all
  71716. // polygons that are clones of each other or were split from the same polygon.
  71717. // This can be used to define per-polygon properties (such as surface color).
  71718. var Polygon = /** @class */ (function () {
  71719. function Polygon(vertices, shared) {
  71720. this.vertices = vertices;
  71721. this.shared = shared;
  71722. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  71723. }
  71724. Polygon.prototype.clone = function () {
  71725. var vertices = this.vertices.map(function (v) { return v.clone(); });
  71726. return new Polygon(vertices, this.shared);
  71727. };
  71728. Polygon.prototype.flip = function () {
  71729. this.vertices.reverse().map(function (v) { v.flip(); });
  71730. this.plane.flip();
  71731. };
  71732. return Polygon;
  71733. }());
  71734. // # class Node
  71735. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  71736. // by picking a polygon to split along. That polygon (and all other coplanar
  71737. // polygons) are added directly to that node and the other polygons are added to
  71738. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  71739. // no distinction between internal and leaf nodes.
  71740. var Node = /** @class */ (function () {
  71741. function Node(polygons) {
  71742. this.plane = null;
  71743. this.front = null;
  71744. this.back = null;
  71745. this.polygons = new Array();
  71746. if (polygons) {
  71747. this.build(polygons);
  71748. }
  71749. }
  71750. Node.prototype.clone = function () {
  71751. var node = new Node();
  71752. node.plane = this.plane && this.plane.clone();
  71753. node.front = this.front && this.front.clone();
  71754. node.back = this.back && this.back.clone();
  71755. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  71756. return node;
  71757. };
  71758. // Convert solid space to empty space and empty space to solid space.
  71759. Node.prototype.invert = function () {
  71760. for (var i = 0; i < this.polygons.length; i++) {
  71761. this.polygons[i].flip();
  71762. }
  71763. if (this.plane) {
  71764. this.plane.flip();
  71765. }
  71766. if (this.front) {
  71767. this.front.invert();
  71768. }
  71769. if (this.back) {
  71770. this.back.invert();
  71771. }
  71772. var temp = this.front;
  71773. this.front = this.back;
  71774. this.back = temp;
  71775. };
  71776. // Recursively remove all polygons in `polygons` that are inside this BSP
  71777. // tree.
  71778. Node.prototype.clipPolygons = function (polygons) {
  71779. if (!this.plane)
  71780. return polygons.slice();
  71781. var front = new Array(), back = new Array();
  71782. for (var i = 0; i < polygons.length; i++) {
  71783. this.plane.splitPolygon(polygons[i], front, back, front, back);
  71784. }
  71785. if (this.front) {
  71786. front = this.front.clipPolygons(front);
  71787. }
  71788. if (this.back) {
  71789. back = this.back.clipPolygons(back);
  71790. }
  71791. else {
  71792. back = [];
  71793. }
  71794. return front.concat(back);
  71795. };
  71796. // Remove all polygons in this BSP tree that are inside the other BSP tree
  71797. // `bsp`.
  71798. Node.prototype.clipTo = function (bsp) {
  71799. this.polygons = bsp.clipPolygons(this.polygons);
  71800. if (this.front)
  71801. this.front.clipTo(bsp);
  71802. if (this.back)
  71803. this.back.clipTo(bsp);
  71804. };
  71805. // Return a list of all polygons in this BSP tree.
  71806. Node.prototype.allPolygons = function () {
  71807. var polygons = this.polygons.slice();
  71808. if (this.front)
  71809. polygons = polygons.concat(this.front.allPolygons());
  71810. if (this.back)
  71811. polygons = polygons.concat(this.back.allPolygons());
  71812. return polygons;
  71813. };
  71814. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  71815. // new polygons are filtered down to the bottom of the tree and become new
  71816. // nodes there. Each set of polygons is partitioned using the first polygon
  71817. // (no heuristic is used to pick a good split).
  71818. Node.prototype.build = function (polygons) {
  71819. if (!polygons.length)
  71820. return;
  71821. if (!this.plane)
  71822. this.plane = polygons[0].plane.clone();
  71823. var front = new Array(), back = new Array();
  71824. for (var i = 0; i < polygons.length; i++) {
  71825. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  71826. }
  71827. if (front.length) {
  71828. if (!this.front)
  71829. this.front = new Node();
  71830. this.front.build(front);
  71831. }
  71832. if (back.length) {
  71833. if (!this.back)
  71834. this.back = new Node();
  71835. this.back.build(back);
  71836. }
  71837. };
  71838. return Node;
  71839. }());
  71840. var CSG = /** @class */ (function () {
  71841. function CSG() {
  71842. this.polygons = new Array();
  71843. }
  71844. // Convert BABYLON.Mesh to BABYLON.CSG
  71845. CSG.FromMesh = function (mesh) {
  71846. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  71847. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  71848. if (mesh instanceof BABYLON.Mesh) {
  71849. mesh.computeWorldMatrix(true);
  71850. matrix = mesh.getWorldMatrix();
  71851. meshPosition = mesh.position.clone();
  71852. meshRotation = mesh.rotation.clone();
  71853. if (mesh.rotationQuaternion) {
  71854. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  71855. }
  71856. meshScaling = mesh.scaling.clone();
  71857. }
  71858. else {
  71859. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  71860. }
  71861. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  71862. var subMeshes = mesh.subMeshes;
  71863. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  71864. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  71865. vertices = [];
  71866. for (var j = 0; j < 3; j++) {
  71867. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  71868. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  71869. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  71870. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  71871. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  71872. vertex = new Vertex(position, normal, uv);
  71873. vertices.push(vertex);
  71874. }
  71875. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  71876. // To handle the case of degenerated triangle
  71877. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  71878. if (polygon.plane)
  71879. polygons.push(polygon);
  71880. }
  71881. }
  71882. var csg = CSG.FromPolygons(polygons);
  71883. csg.matrix = matrix;
  71884. csg.position = meshPosition;
  71885. csg.rotation = meshRotation;
  71886. csg.scaling = meshScaling;
  71887. csg.rotationQuaternion = meshRotationQuaternion;
  71888. currentCSGMeshId++;
  71889. return csg;
  71890. };
  71891. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  71892. CSG.FromPolygons = function (polygons) {
  71893. var csg = new CSG();
  71894. csg.polygons = polygons;
  71895. return csg;
  71896. };
  71897. CSG.prototype.clone = function () {
  71898. var csg = new CSG();
  71899. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  71900. csg.copyTransformAttributes(this);
  71901. return csg;
  71902. };
  71903. CSG.prototype.union = function (csg) {
  71904. var a = new Node(this.clone().polygons);
  71905. var b = new Node(csg.clone().polygons);
  71906. a.clipTo(b);
  71907. b.clipTo(a);
  71908. b.invert();
  71909. b.clipTo(a);
  71910. b.invert();
  71911. a.build(b.allPolygons());
  71912. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  71913. };
  71914. CSG.prototype.unionInPlace = function (csg) {
  71915. var a = new Node(this.polygons);
  71916. var b = new Node(csg.polygons);
  71917. a.clipTo(b);
  71918. b.clipTo(a);
  71919. b.invert();
  71920. b.clipTo(a);
  71921. b.invert();
  71922. a.build(b.allPolygons());
  71923. this.polygons = a.allPolygons();
  71924. };
  71925. CSG.prototype.subtract = function (csg) {
  71926. var a = new Node(this.clone().polygons);
  71927. var b = new Node(csg.clone().polygons);
  71928. a.invert();
  71929. a.clipTo(b);
  71930. b.clipTo(a);
  71931. b.invert();
  71932. b.clipTo(a);
  71933. b.invert();
  71934. a.build(b.allPolygons());
  71935. a.invert();
  71936. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  71937. };
  71938. CSG.prototype.subtractInPlace = function (csg) {
  71939. var a = new Node(this.polygons);
  71940. var b = new Node(csg.polygons);
  71941. a.invert();
  71942. a.clipTo(b);
  71943. b.clipTo(a);
  71944. b.invert();
  71945. b.clipTo(a);
  71946. b.invert();
  71947. a.build(b.allPolygons());
  71948. a.invert();
  71949. this.polygons = a.allPolygons();
  71950. };
  71951. CSG.prototype.intersect = function (csg) {
  71952. var a = new Node(this.clone().polygons);
  71953. var b = new Node(csg.clone().polygons);
  71954. a.invert();
  71955. b.clipTo(a);
  71956. b.invert();
  71957. a.clipTo(b);
  71958. b.clipTo(a);
  71959. a.build(b.allPolygons());
  71960. a.invert();
  71961. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  71962. };
  71963. CSG.prototype.intersectInPlace = function (csg) {
  71964. var a = new Node(this.polygons);
  71965. var b = new Node(csg.polygons);
  71966. a.invert();
  71967. b.clipTo(a);
  71968. b.invert();
  71969. a.clipTo(b);
  71970. b.clipTo(a);
  71971. a.build(b.allPolygons());
  71972. a.invert();
  71973. this.polygons = a.allPolygons();
  71974. };
  71975. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  71976. // not modified.
  71977. CSG.prototype.inverse = function () {
  71978. var csg = this.clone();
  71979. csg.inverseInPlace();
  71980. return csg;
  71981. };
  71982. CSG.prototype.inverseInPlace = function () {
  71983. this.polygons.map(function (p) { p.flip(); });
  71984. };
  71985. // This is used to keep meshes transformations so they can be restored
  71986. // when we build back a Babylon Mesh
  71987. // NB : All CSG operations are performed in world coordinates
  71988. CSG.prototype.copyTransformAttributes = function (csg) {
  71989. this.matrix = csg.matrix;
  71990. this.position = csg.position;
  71991. this.rotation = csg.rotation;
  71992. this.scaling = csg.scaling;
  71993. this.rotationQuaternion = csg.rotationQuaternion;
  71994. return this;
  71995. };
  71996. // Build Raw mesh from CSG
  71997. // Coordinates here are in world space
  71998. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  71999. var matrix = this.matrix.clone();
  72000. matrix.invert();
  72001. 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;
  72002. if (keepSubMeshes) {
  72003. // Sort Polygons, since subMeshes are indices range
  72004. polygons.sort(function (a, b) {
  72005. if (a.shared.meshId === b.shared.meshId) {
  72006. return a.shared.subMeshId - b.shared.subMeshId;
  72007. }
  72008. else {
  72009. return a.shared.meshId - b.shared.meshId;
  72010. }
  72011. });
  72012. }
  72013. for (var i = 0, il = polygons.length; i < il; i++) {
  72014. polygon = polygons[i];
  72015. // Building SubMeshes
  72016. if (!subMesh_dict[polygon.shared.meshId]) {
  72017. subMesh_dict[polygon.shared.meshId] = {};
  72018. }
  72019. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72020. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72021. indexStart: +Infinity,
  72022. indexEnd: -Infinity,
  72023. materialIndex: polygon.shared.materialIndex
  72024. };
  72025. }
  72026. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72027. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72028. polygonIndices[0] = 0;
  72029. polygonIndices[1] = j - 1;
  72030. polygonIndices[2] = j;
  72031. for (var k = 0; k < 3; k++) {
  72032. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72033. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72034. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72035. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72036. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72037. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72038. // Check if 2 points can be merged
  72039. if (!(typeof vertex_idx !== 'undefined' &&
  72040. normals[vertex_idx * 3] === localNormal.x &&
  72041. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72042. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72043. uvs[vertex_idx * 2] === uv.x &&
  72044. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72045. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72046. uvs.push(uv.x, uv.y);
  72047. normals.push(normal.x, normal.y, normal.z);
  72048. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72049. }
  72050. indices.push(vertex_idx);
  72051. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72052. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72053. currentIndex++;
  72054. }
  72055. }
  72056. }
  72057. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72058. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72059. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72060. mesh.setIndices(indices, null);
  72061. if (keepSubMeshes) {
  72062. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72063. var materialIndexOffset = 0, materialMaxIndex;
  72064. mesh.subMeshes = new Array();
  72065. for (var m in subMesh_dict) {
  72066. materialMaxIndex = -1;
  72067. for (var sm in subMesh_dict[m]) {
  72068. subMesh_obj = subMesh_dict[m][sm];
  72069. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72070. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72071. }
  72072. materialIndexOffset += ++materialMaxIndex;
  72073. }
  72074. }
  72075. return mesh;
  72076. };
  72077. // Build Mesh from CSG taking material and transforms into account
  72078. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72079. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72080. mesh.material = material;
  72081. mesh.position.copyFrom(this.position);
  72082. mesh.rotation.copyFrom(this.rotation);
  72083. if (this.rotationQuaternion) {
  72084. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72085. }
  72086. mesh.scaling.copyFrom(this.scaling);
  72087. mesh.computeWorldMatrix(true);
  72088. return mesh;
  72089. };
  72090. return CSG;
  72091. }());
  72092. BABYLON.CSG = CSG;
  72093. })(BABYLON || (BABYLON = {}));
  72094. //# sourceMappingURL=babylon.csg.js.map
  72095. var BABYLON;
  72096. (function (BABYLON) {
  72097. var LensFlare = /** @class */ (function () {
  72098. function LensFlare(size, position, color, imgUrl, system) {
  72099. this.size = size;
  72100. this.position = position;
  72101. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72102. this.color = color || new BABYLON.Color3(1, 1, 1);
  72103. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72104. this._system = system;
  72105. system.lensFlares.push(this);
  72106. }
  72107. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72108. return new LensFlare(size, position, color, imgUrl, system);
  72109. };
  72110. LensFlare.prototype.dispose = function () {
  72111. if (this.texture) {
  72112. this.texture.dispose();
  72113. }
  72114. // Remove from scene
  72115. var index = this._system.lensFlares.indexOf(this);
  72116. this._system.lensFlares.splice(index, 1);
  72117. };
  72118. ;
  72119. return LensFlare;
  72120. }());
  72121. BABYLON.LensFlare = LensFlare;
  72122. })(BABYLON || (BABYLON = {}));
  72123. //# sourceMappingURL=babylon.lensFlare.js.map
  72124. var BABYLON;
  72125. (function (BABYLON) {
  72126. var LensFlareSystem = /** @class */ (function () {
  72127. function LensFlareSystem(name, emitter, scene) {
  72128. this.name = name;
  72129. this.lensFlares = new Array();
  72130. this.borderLimit = 300;
  72131. this.viewportBorder = 0;
  72132. this.layerMask = 0x0FFFFFFF;
  72133. this._vertexBuffers = {};
  72134. this._isEnabled = true;
  72135. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72136. this._emitter = emitter;
  72137. this.id = name;
  72138. scene.lensFlareSystems.push(this);
  72139. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72140. var engine = scene.getEngine();
  72141. // VBO
  72142. var vertices = [];
  72143. vertices.push(1, 1);
  72144. vertices.push(-1, 1);
  72145. vertices.push(-1, -1);
  72146. vertices.push(1, -1);
  72147. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72148. // Indices
  72149. var indices = [];
  72150. indices.push(0);
  72151. indices.push(1);
  72152. indices.push(2);
  72153. indices.push(0);
  72154. indices.push(2);
  72155. indices.push(3);
  72156. this._indexBuffer = engine.createIndexBuffer(indices);
  72157. // Effects
  72158. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72159. }
  72160. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72161. get: function () {
  72162. return this._isEnabled;
  72163. },
  72164. set: function (value) {
  72165. this._isEnabled = value;
  72166. },
  72167. enumerable: true,
  72168. configurable: true
  72169. });
  72170. LensFlareSystem.prototype.getScene = function () {
  72171. return this._scene;
  72172. };
  72173. LensFlareSystem.prototype.getEmitter = function () {
  72174. return this._emitter;
  72175. };
  72176. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72177. this._emitter = newEmitter;
  72178. };
  72179. LensFlareSystem.prototype.getEmitterPosition = function () {
  72180. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72181. };
  72182. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72183. var position = this.getEmitterPosition();
  72184. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72185. this._positionX = position.x;
  72186. this._positionY = position.y;
  72187. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72188. if (this.viewportBorder > 0) {
  72189. globalViewport.x -= this.viewportBorder;
  72190. globalViewport.y -= this.viewportBorder;
  72191. globalViewport.width += this.viewportBorder * 2;
  72192. globalViewport.height += this.viewportBorder * 2;
  72193. position.x += this.viewportBorder;
  72194. position.y += this.viewportBorder;
  72195. this._positionX += this.viewportBorder;
  72196. this._positionY += this.viewportBorder;
  72197. }
  72198. if (position.z > 0) {
  72199. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72200. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72201. return true;
  72202. }
  72203. return true;
  72204. }
  72205. return false;
  72206. };
  72207. LensFlareSystem.prototype._isVisible = function () {
  72208. if (!this._isEnabled || !this._scene.activeCamera) {
  72209. return false;
  72210. }
  72211. var emitterPosition = this.getEmitterPosition();
  72212. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72213. var distance = direction.length();
  72214. direction.normalize();
  72215. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72216. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72217. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72218. };
  72219. LensFlareSystem.prototype.render = function () {
  72220. if (!this._effect.isReady() || !this._scene.activeCamera)
  72221. return false;
  72222. var engine = this._scene.getEngine();
  72223. var viewport = this._scene.activeCamera.viewport;
  72224. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72225. // Position
  72226. if (!this.computeEffectivePosition(globalViewport)) {
  72227. return false;
  72228. }
  72229. // Visibility
  72230. if (!this._isVisible()) {
  72231. return false;
  72232. }
  72233. // Intensity
  72234. var awayX;
  72235. var awayY;
  72236. if (this._positionX < this.borderLimit + globalViewport.x) {
  72237. awayX = this.borderLimit + globalViewport.x - this._positionX;
  72238. }
  72239. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  72240. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  72241. }
  72242. else {
  72243. awayX = 0;
  72244. }
  72245. if (this._positionY < this.borderLimit + globalViewport.y) {
  72246. awayY = this.borderLimit + globalViewport.y - this._positionY;
  72247. }
  72248. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  72249. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  72250. }
  72251. else {
  72252. awayY = 0;
  72253. }
  72254. var away = (awayX > awayY) ? awayX : awayY;
  72255. away -= this.viewportBorder;
  72256. if (away > this.borderLimit) {
  72257. away = this.borderLimit;
  72258. }
  72259. var intensity = 1.0 - (away / this.borderLimit);
  72260. if (intensity < 0) {
  72261. return false;
  72262. }
  72263. if (intensity > 1.0) {
  72264. intensity = 1.0;
  72265. }
  72266. if (this.viewportBorder > 0) {
  72267. globalViewport.x += this.viewportBorder;
  72268. globalViewport.y += this.viewportBorder;
  72269. globalViewport.width -= this.viewportBorder * 2;
  72270. globalViewport.height -= this.viewportBorder * 2;
  72271. this._positionX -= this.viewportBorder;
  72272. this._positionY -= this.viewportBorder;
  72273. }
  72274. // Position
  72275. var centerX = globalViewport.x + globalViewport.width / 2;
  72276. var centerY = globalViewport.y + globalViewport.height / 2;
  72277. var distX = centerX - this._positionX;
  72278. var distY = centerY - this._positionY;
  72279. // Effects
  72280. engine.enableEffect(this._effect);
  72281. engine.setState(false);
  72282. engine.setDepthBuffer(false);
  72283. // VBOs
  72284. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72285. // Flares
  72286. for (var index = 0; index < this.lensFlares.length; index++) {
  72287. var flare = this.lensFlares[index];
  72288. engine.setAlphaMode(flare.alphaMode);
  72289. var x = centerX - (distX * flare.position);
  72290. var y = centerY - (distY * flare.position);
  72291. var cw = flare.size;
  72292. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  72293. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  72294. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  72295. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  72296. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  72297. // Texture
  72298. this._effect.setTexture("textureSampler", flare.texture);
  72299. // Color
  72300. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  72301. // Draw order
  72302. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72303. }
  72304. engine.setDepthBuffer(true);
  72305. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72306. return true;
  72307. };
  72308. LensFlareSystem.prototype.dispose = function () {
  72309. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72310. if (vertexBuffer) {
  72311. vertexBuffer.dispose();
  72312. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72313. }
  72314. if (this._indexBuffer) {
  72315. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72316. this._indexBuffer = null;
  72317. }
  72318. while (this.lensFlares.length) {
  72319. this.lensFlares[0].dispose();
  72320. }
  72321. // Remove from scene
  72322. var index = this._scene.lensFlareSystems.indexOf(this);
  72323. this._scene.lensFlareSystems.splice(index, 1);
  72324. };
  72325. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  72326. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  72327. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  72328. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  72329. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  72330. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  72331. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  72332. var parsedFlare = parsedLensFlareSystem.flares[index];
  72333. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  72334. }
  72335. return lensFlareSystem;
  72336. };
  72337. LensFlareSystem.prototype.serialize = function () {
  72338. var serializationObject = {};
  72339. serializationObject.id = this.id;
  72340. serializationObject.name = this.name;
  72341. serializationObject.emitterId = this.getEmitter().id;
  72342. serializationObject.borderLimit = this.borderLimit;
  72343. serializationObject.flares = [];
  72344. for (var index = 0; index < this.lensFlares.length; index++) {
  72345. var flare = this.lensFlares[index];
  72346. serializationObject.flares.push({
  72347. size: flare.size,
  72348. position: flare.position,
  72349. color: flare.color.asArray(),
  72350. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  72351. });
  72352. }
  72353. return serializationObject;
  72354. };
  72355. return LensFlareSystem;
  72356. }());
  72357. BABYLON.LensFlareSystem = LensFlareSystem;
  72358. })(BABYLON || (BABYLON = {}));
  72359. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  72360. var BABYLON;
  72361. (function (BABYLON) {
  72362. /**
  72363. * This is a holder class for the physics joint created by the physics plugin.
  72364. * It holds a set of functions to control the underlying joint.
  72365. */
  72366. var PhysicsJoint = /** @class */ (function () {
  72367. function PhysicsJoint(type, jointData) {
  72368. this.type = type;
  72369. this.jointData = jointData;
  72370. jointData.nativeParams = jointData.nativeParams || {};
  72371. }
  72372. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  72373. get: function () {
  72374. return this._physicsJoint;
  72375. },
  72376. set: function (newJoint) {
  72377. if (this._physicsJoint) {
  72378. //remove from the wolrd
  72379. }
  72380. this._physicsJoint = newJoint;
  72381. },
  72382. enumerable: true,
  72383. configurable: true
  72384. });
  72385. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  72386. set: function (physicsPlugin) {
  72387. this._physicsPlugin = physicsPlugin;
  72388. },
  72389. enumerable: true,
  72390. configurable: true
  72391. });
  72392. /**
  72393. * Execute a function that is physics-plugin specific.
  72394. * @param {Function} func the function that will be executed.
  72395. * It accepts two parameters: the physics world and the physics joint.
  72396. */
  72397. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  72398. func(this._physicsPlugin.world, this._physicsJoint);
  72399. };
  72400. //TODO check if the native joints are the same
  72401. //Joint Types
  72402. PhysicsJoint.DistanceJoint = 0;
  72403. PhysicsJoint.HingeJoint = 1;
  72404. PhysicsJoint.BallAndSocketJoint = 2;
  72405. PhysicsJoint.WheelJoint = 3;
  72406. PhysicsJoint.SliderJoint = 4;
  72407. //OIMO
  72408. PhysicsJoint.PrismaticJoint = 5;
  72409. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  72410. PhysicsJoint.UniversalJoint = 6;
  72411. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  72412. //Cannon
  72413. //Similar to a Ball-Joint. Different in params
  72414. PhysicsJoint.PointToPointJoint = 8;
  72415. //Cannon only at the moment
  72416. PhysicsJoint.SpringJoint = 9;
  72417. PhysicsJoint.LockJoint = 10;
  72418. return PhysicsJoint;
  72419. }());
  72420. BABYLON.PhysicsJoint = PhysicsJoint;
  72421. /**
  72422. * A class representing a physics distance joint.
  72423. */
  72424. var DistanceJoint = /** @class */ (function (_super) {
  72425. __extends(DistanceJoint, _super);
  72426. function DistanceJoint(jointData) {
  72427. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  72428. }
  72429. /**
  72430. * Update the predefined distance.
  72431. */
  72432. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  72433. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  72434. };
  72435. return DistanceJoint;
  72436. }(PhysicsJoint));
  72437. BABYLON.DistanceJoint = DistanceJoint;
  72438. var MotorEnabledJoint = /** @class */ (function (_super) {
  72439. __extends(MotorEnabledJoint, _super);
  72440. function MotorEnabledJoint(type, jointData) {
  72441. return _super.call(this, type, jointData) || this;
  72442. }
  72443. /**
  72444. * Set the motor values.
  72445. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72446. * @param {number} force the force to apply
  72447. * @param {number} maxForce max force for this motor.
  72448. */
  72449. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  72450. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  72451. };
  72452. /**
  72453. * Set the motor's limits.
  72454. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72455. */
  72456. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  72457. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  72458. };
  72459. return MotorEnabledJoint;
  72460. }(PhysicsJoint));
  72461. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  72462. /**
  72463. * This class represents a single hinge physics joint
  72464. */
  72465. var HingeJoint = /** @class */ (function (_super) {
  72466. __extends(HingeJoint, _super);
  72467. function HingeJoint(jointData) {
  72468. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  72469. }
  72470. /**
  72471. * Set the motor values.
  72472. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72473. * @param {number} force the force to apply
  72474. * @param {number} maxForce max force for this motor.
  72475. */
  72476. HingeJoint.prototype.setMotor = function (force, maxForce) {
  72477. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  72478. };
  72479. /**
  72480. * Set the motor's limits.
  72481. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72482. */
  72483. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  72484. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  72485. };
  72486. return HingeJoint;
  72487. }(MotorEnabledJoint));
  72488. BABYLON.HingeJoint = HingeJoint;
  72489. /**
  72490. * This class represents a dual hinge physics joint (same as wheel joint)
  72491. */
  72492. var Hinge2Joint = /** @class */ (function (_super) {
  72493. __extends(Hinge2Joint, _super);
  72494. function Hinge2Joint(jointData) {
  72495. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  72496. }
  72497. /**
  72498. * Set the motor values.
  72499. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72500. * @param {number} force the force to apply
  72501. * @param {number} maxForce max force for this motor.
  72502. * @param {motorIndex} the motor's index, 0 or 1.
  72503. */
  72504. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  72505. if (motorIndex === void 0) { motorIndex = 0; }
  72506. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  72507. };
  72508. /**
  72509. * Set the motor limits.
  72510. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72511. * @param {number} upperLimit the upper limit
  72512. * @param {number} lowerLimit lower limit
  72513. * @param {motorIndex} the motor's index, 0 or 1.
  72514. */
  72515. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  72516. if (motorIndex === void 0) { motorIndex = 0; }
  72517. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  72518. };
  72519. return Hinge2Joint;
  72520. }(MotorEnabledJoint));
  72521. BABYLON.Hinge2Joint = Hinge2Joint;
  72522. })(BABYLON || (BABYLON = {}));
  72523. //# sourceMappingURL=babylon.physicsJoint.js.map
  72524. var BABYLON;
  72525. (function (BABYLON) {
  72526. var PhysicsImpostor = /** @class */ (function () {
  72527. function PhysicsImpostor(object, type, _options, _scene) {
  72528. if (_options === void 0) { _options = { mass: 0 }; }
  72529. var _this = this;
  72530. this.object = object;
  72531. this.type = type;
  72532. this._options = _options;
  72533. this._scene = _scene;
  72534. this._bodyUpdateRequired = false;
  72535. this._onBeforePhysicsStepCallbacks = new Array();
  72536. this._onAfterPhysicsStepCallbacks = new Array();
  72537. this._onPhysicsCollideCallbacks = [];
  72538. this._deltaPosition = BABYLON.Vector3.Zero();
  72539. this._isDisposed = false;
  72540. //temp variables for parent rotation calculations
  72541. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  72542. this._tmpQuat = new BABYLON.Quaternion();
  72543. this._tmpQuat2 = new BABYLON.Quaternion();
  72544. /**
  72545. * this function is executed by the physics engine.
  72546. */
  72547. this.beforeStep = function () {
  72548. if (!_this._physicsEngine) {
  72549. return;
  72550. }
  72551. _this.object.translate(_this._deltaPosition, -1);
  72552. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  72553. _this.object.computeWorldMatrix(false);
  72554. if (_this.object.parent && _this.object.rotationQuaternion) {
  72555. _this.getParentsRotation();
  72556. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  72557. }
  72558. else {
  72559. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  72560. }
  72561. if (!_this._options.disableBidirectionalTransformation) {
  72562. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  72563. }
  72564. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  72565. func(_this);
  72566. });
  72567. };
  72568. /**
  72569. * this function is executed by the physics engine.
  72570. */
  72571. this.afterStep = function () {
  72572. if (!_this._physicsEngine) {
  72573. return;
  72574. }
  72575. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  72576. func(_this);
  72577. });
  72578. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  72579. // object has now its world rotation. needs to be converted to local.
  72580. if (_this.object.parent && _this.object.rotationQuaternion) {
  72581. _this.getParentsRotation();
  72582. _this._tmpQuat.conjugateInPlace();
  72583. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  72584. }
  72585. // take the position set and make it the absolute position of this object.
  72586. _this.object.setAbsolutePosition(_this.object.position);
  72587. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  72588. _this.object.translate(_this._deltaPosition, 1);
  72589. };
  72590. /**
  72591. * Legacy collision detection event support
  72592. */
  72593. this.onCollideEvent = null;
  72594. //event and body object due to cannon's event-based architecture.
  72595. this.onCollide = function (e) {
  72596. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  72597. return;
  72598. }
  72599. if (!_this._physicsEngine) {
  72600. return;
  72601. }
  72602. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  72603. if (otherImpostor) {
  72604. // Legacy collision detection event support
  72605. if (_this.onCollideEvent) {
  72606. _this.onCollideEvent(_this, otherImpostor);
  72607. }
  72608. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  72609. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  72610. }).forEach(function (obj) {
  72611. obj.callback(_this, otherImpostor);
  72612. });
  72613. }
  72614. };
  72615. //sanity check!
  72616. if (!this.object) {
  72617. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  72618. return;
  72619. }
  72620. //legacy support for old syntax.
  72621. if (!this._scene && object.getScene) {
  72622. this._scene = object.getScene();
  72623. }
  72624. if (!this._scene) {
  72625. return;
  72626. }
  72627. this._physicsEngine = this._scene.getPhysicsEngine();
  72628. if (!this._physicsEngine) {
  72629. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  72630. }
  72631. else {
  72632. //set the object's quaternion, if not set
  72633. if (!this.object.rotationQuaternion) {
  72634. if (this.object.rotation) {
  72635. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  72636. }
  72637. else {
  72638. this.object.rotationQuaternion = new BABYLON.Quaternion();
  72639. }
  72640. }
  72641. //default options params
  72642. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  72643. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  72644. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  72645. this._joints = [];
  72646. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  72647. if (!this.object.parent || this._options.ignoreParent) {
  72648. this._init();
  72649. }
  72650. else if (this.object.parent.physicsImpostor) {
  72651. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  72652. }
  72653. }
  72654. }
  72655. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  72656. get: function () {
  72657. return this._isDisposed;
  72658. },
  72659. enumerable: true,
  72660. configurable: true
  72661. });
  72662. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  72663. get: function () {
  72664. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  72665. },
  72666. set: function (value) {
  72667. this.setMass(value);
  72668. },
  72669. enumerable: true,
  72670. configurable: true
  72671. });
  72672. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  72673. get: function () {
  72674. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  72675. },
  72676. set: function (value) {
  72677. if (!this._physicsEngine) {
  72678. return;
  72679. }
  72680. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  72681. },
  72682. enumerable: true,
  72683. configurable: true
  72684. });
  72685. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  72686. get: function () {
  72687. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  72688. },
  72689. set: function (value) {
  72690. if (!this._physicsEngine) {
  72691. return;
  72692. }
  72693. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  72694. },
  72695. enumerable: true,
  72696. configurable: true
  72697. });
  72698. /**
  72699. * This function will completly initialize this impostor.
  72700. * It will create a new body - but only if this mesh has no parent.
  72701. * If it has, this impostor will not be used other than to define the impostor
  72702. * of the child mesh.
  72703. */
  72704. PhysicsImpostor.prototype._init = function () {
  72705. if (!this._physicsEngine) {
  72706. return;
  72707. }
  72708. this._physicsEngine.removeImpostor(this);
  72709. this.physicsBody = null;
  72710. this._parent = this._parent || this._getPhysicsParent();
  72711. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  72712. this._physicsEngine.addImpostor(this);
  72713. }
  72714. };
  72715. PhysicsImpostor.prototype._getPhysicsParent = function () {
  72716. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  72717. var parentMesh = this.object.parent;
  72718. return parentMesh.physicsImpostor;
  72719. }
  72720. return null;
  72721. };
  72722. /**
  72723. * Should a new body be generated.
  72724. */
  72725. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  72726. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  72727. };
  72728. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  72729. this.forceUpdate();
  72730. };
  72731. /**
  72732. * Force a regeneration of this or the parent's impostor's body.
  72733. * Use under cautious - This will remove all joints already implemented.
  72734. */
  72735. PhysicsImpostor.prototype.forceUpdate = function () {
  72736. this._init();
  72737. if (this.parent && !this._options.ignoreParent) {
  72738. this.parent.forceUpdate();
  72739. }
  72740. };
  72741. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  72742. /*public get mesh(): AbstractMesh {
  72743. return this._mesh;
  72744. }*/
  72745. /**
  72746. * Gets the body that holds this impostor. Either its own, or its parent.
  72747. */
  72748. get: function () {
  72749. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  72750. },
  72751. /**
  72752. * Set the physics body. Used mainly by the physics engine/plugin
  72753. */
  72754. set: function (physicsBody) {
  72755. if (this._physicsBody && this._physicsEngine) {
  72756. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  72757. }
  72758. this._physicsBody = physicsBody;
  72759. this.resetUpdateFlags();
  72760. },
  72761. enumerable: true,
  72762. configurable: true
  72763. });
  72764. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  72765. get: function () {
  72766. return !this._options.ignoreParent && this._parent ? this._parent : null;
  72767. },
  72768. set: function (value) {
  72769. this._parent = value;
  72770. },
  72771. enumerable: true,
  72772. configurable: true
  72773. });
  72774. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  72775. this._bodyUpdateRequired = false;
  72776. };
  72777. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  72778. if (this.object.getBoundingInfo) {
  72779. var q = this.object.rotationQuaternion;
  72780. //reset rotation
  72781. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  72782. //calculate the world matrix with no rotation
  72783. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  72784. var boundingInfo = this.object.getBoundingInfo();
  72785. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  72786. //bring back the rotation
  72787. this.object.rotationQuaternion = q;
  72788. //calculate the world matrix with the new rotation
  72789. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  72790. return size;
  72791. }
  72792. else {
  72793. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  72794. }
  72795. };
  72796. PhysicsImpostor.prototype.getObjectCenter = function () {
  72797. if (this.object.getBoundingInfo) {
  72798. var boundingInfo = this.object.getBoundingInfo();
  72799. return boundingInfo.boundingBox.centerWorld;
  72800. }
  72801. else {
  72802. return this.object.position;
  72803. }
  72804. };
  72805. /**
  72806. * Get a specific parametes from the options parameter.
  72807. */
  72808. PhysicsImpostor.prototype.getParam = function (paramName) {
  72809. return this._options[paramName];
  72810. };
  72811. /**
  72812. * Sets a specific parameter in the options given to the physics plugin
  72813. */
  72814. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  72815. this._options[paramName] = value;
  72816. this._bodyUpdateRequired = true;
  72817. };
  72818. /**
  72819. * Specifically change the body's mass option. Won't recreate the physics body object
  72820. */
  72821. PhysicsImpostor.prototype.setMass = function (mass) {
  72822. if (this.getParam("mass") !== mass) {
  72823. this.setParam("mass", mass);
  72824. }
  72825. if (this._physicsEngine) {
  72826. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  72827. }
  72828. };
  72829. PhysicsImpostor.prototype.getLinearVelocity = function () {
  72830. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  72831. };
  72832. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  72833. if (this._physicsEngine) {
  72834. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  72835. }
  72836. };
  72837. PhysicsImpostor.prototype.getAngularVelocity = function () {
  72838. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  72839. };
  72840. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  72841. if (this._physicsEngine) {
  72842. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  72843. }
  72844. };
  72845. /**
  72846. * Execute a function with the physics plugin native code.
  72847. * Provide a function the will have two variables - the world object and the physics body object.
  72848. */
  72849. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  72850. if (this._physicsEngine) {
  72851. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  72852. }
  72853. };
  72854. /**
  72855. * Register a function that will be executed before the physics world is stepping forward.
  72856. */
  72857. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  72858. this._onBeforePhysicsStepCallbacks.push(func);
  72859. };
  72860. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  72861. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  72862. if (index > -1) {
  72863. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  72864. }
  72865. else {
  72866. BABYLON.Tools.Warn("Function to remove was not found");
  72867. }
  72868. };
  72869. /**
  72870. * Register a function that will be executed after the physics step
  72871. */
  72872. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  72873. this._onAfterPhysicsStepCallbacks.push(func);
  72874. };
  72875. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  72876. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  72877. if (index > -1) {
  72878. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  72879. }
  72880. else {
  72881. BABYLON.Tools.Warn("Function to remove was not found");
  72882. }
  72883. };
  72884. /**
  72885. * register a function that will be executed when this impostor collides against a different body.
  72886. */
  72887. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  72888. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  72889. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  72890. };
  72891. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  72892. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  72893. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  72894. if (index > -1) {
  72895. this._onPhysicsCollideCallbacks.splice(index, 1);
  72896. }
  72897. else {
  72898. BABYLON.Tools.Warn("Function to remove was not found");
  72899. }
  72900. };
  72901. PhysicsImpostor.prototype.getParentsRotation = function () {
  72902. var parent = this.object.parent;
  72903. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  72904. while (parent) {
  72905. if (parent.rotationQuaternion) {
  72906. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  72907. }
  72908. else {
  72909. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  72910. }
  72911. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  72912. parent = parent.parent;
  72913. }
  72914. return this._tmpQuat;
  72915. };
  72916. /**
  72917. * Apply a force
  72918. */
  72919. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  72920. if (this._physicsEngine) {
  72921. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  72922. }
  72923. return this;
  72924. };
  72925. /**
  72926. * Apply an impulse
  72927. */
  72928. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  72929. if (this._physicsEngine) {
  72930. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  72931. }
  72932. return this;
  72933. };
  72934. /**
  72935. * A help function to create a joint.
  72936. */
  72937. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  72938. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  72939. this.addJoint(otherImpostor, joint);
  72940. return this;
  72941. };
  72942. /**
  72943. * Add a joint to this impostor with a different impostor.
  72944. */
  72945. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  72946. this._joints.push({
  72947. otherImpostor: otherImpostor,
  72948. joint: joint
  72949. });
  72950. if (this._physicsEngine) {
  72951. this._physicsEngine.addJoint(this, otherImpostor, joint);
  72952. }
  72953. return this;
  72954. };
  72955. /**
  72956. * Will keep this body still, in a sleep mode.
  72957. */
  72958. PhysicsImpostor.prototype.sleep = function () {
  72959. if (this._physicsEngine) {
  72960. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  72961. }
  72962. return this;
  72963. };
  72964. /**
  72965. * Wake the body up.
  72966. */
  72967. PhysicsImpostor.prototype.wakeUp = function () {
  72968. if (this._physicsEngine) {
  72969. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  72970. }
  72971. return this;
  72972. };
  72973. PhysicsImpostor.prototype.clone = function (newObject) {
  72974. if (!newObject)
  72975. return null;
  72976. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  72977. };
  72978. PhysicsImpostor.prototype.dispose = function () {
  72979. var _this = this;
  72980. //no dispose if no physics engine is available.
  72981. if (!this._physicsEngine) {
  72982. return;
  72983. }
  72984. this._joints.forEach(function (j) {
  72985. if (_this._physicsEngine) {
  72986. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  72987. }
  72988. });
  72989. //dispose the physics body
  72990. this._physicsEngine.removeImpostor(this);
  72991. if (this.parent) {
  72992. this.parent.forceUpdate();
  72993. }
  72994. else {
  72995. /*this._object.getChildMeshes().forEach(function(mesh) {
  72996. if (mesh.physicsImpostor) {
  72997. if (disposeChildren) {
  72998. mesh.physicsImpostor.dispose();
  72999. mesh.physicsImpostor = null;
  73000. }
  73001. }
  73002. })*/
  73003. }
  73004. this._isDisposed = true;
  73005. };
  73006. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73007. this._deltaPosition.copyFrom(position);
  73008. };
  73009. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73010. if (!this._deltaRotation) {
  73011. this._deltaRotation = new BABYLON.Quaternion();
  73012. }
  73013. this._deltaRotation.copyFrom(rotation);
  73014. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73015. };
  73016. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73017. if (this._physicsEngine) {
  73018. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73019. }
  73020. return this;
  73021. };
  73022. PhysicsImpostor.prototype.getRadius = function () {
  73023. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73024. };
  73025. /**
  73026. * Sync a bone with this impostor
  73027. * @param bone The bone to sync to the impostor.
  73028. * @param boneMesh The mesh that the bone is influencing.
  73029. * @param jointPivot The pivot of the joint / bone in local space.
  73030. * @param distToJoint Optional distance from the impostor to the joint.
  73031. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73032. */
  73033. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73034. var tempVec = PhysicsImpostor._tmpVecs[0];
  73035. var mesh = this.object;
  73036. if (mesh.rotationQuaternion) {
  73037. if (adjustRotation) {
  73038. var tempQuat = PhysicsImpostor._tmpQuat;
  73039. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73040. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73041. }
  73042. else {
  73043. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73044. }
  73045. }
  73046. tempVec.x = 0;
  73047. tempVec.y = 0;
  73048. tempVec.z = 0;
  73049. if (jointPivot) {
  73050. tempVec.x = jointPivot.x;
  73051. tempVec.y = jointPivot.y;
  73052. tempVec.z = jointPivot.z;
  73053. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73054. if (distToJoint === undefined || distToJoint === null) {
  73055. distToJoint = jointPivot.length();
  73056. }
  73057. tempVec.x *= distToJoint;
  73058. tempVec.y *= distToJoint;
  73059. tempVec.z *= distToJoint;
  73060. }
  73061. if (bone.getParent()) {
  73062. tempVec.addInPlace(mesh.getAbsolutePosition());
  73063. bone.setAbsolutePosition(tempVec, boneMesh);
  73064. }
  73065. else {
  73066. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73067. boneMesh.position.x -= tempVec.x;
  73068. boneMesh.position.y -= tempVec.y;
  73069. boneMesh.position.z -= tempVec.z;
  73070. }
  73071. };
  73072. /**
  73073. * Sync impostor to a bone
  73074. * @param bone The bone that the impostor will be synced to.
  73075. * @param boneMesh The mesh that the bone is influencing.
  73076. * @param jointPivot The pivot of the joint / bone in local space.
  73077. * @param distToJoint Optional distance from the impostor to the joint.
  73078. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73079. * @param boneAxis Optional vector3 axis the bone is aligned with
  73080. */
  73081. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73082. var mesh = this.object;
  73083. if (mesh.rotationQuaternion) {
  73084. if (adjustRotation) {
  73085. var tempQuat = PhysicsImpostor._tmpQuat;
  73086. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73087. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73088. }
  73089. else {
  73090. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73091. }
  73092. }
  73093. var pos = PhysicsImpostor._tmpVecs[0];
  73094. var boneDir = PhysicsImpostor._tmpVecs[1];
  73095. if (!boneAxis) {
  73096. boneAxis = PhysicsImpostor._tmpVecs[2];
  73097. boneAxis.x = 0;
  73098. boneAxis.y = 1;
  73099. boneAxis.z = 0;
  73100. }
  73101. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73102. bone.getAbsolutePositionToRef(boneMesh, pos);
  73103. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73104. distToJoint = jointPivot.length();
  73105. }
  73106. if (distToJoint !== undefined && distToJoint !== null) {
  73107. pos.x += boneDir.x * distToJoint;
  73108. pos.y += boneDir.y * distToJoint;
  73109. pos.z += boneDir.z * distToJoint;
  73110. }
  73111. mesh.setAbsolutePosition(pos);
  73112. };
  73113. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73114. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73115. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73116. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73117. //Impostor types
  73118. PhysicsImpostor.NoImpostor = 0;
  73119. PhysicsImpostor.SphereImpostor = 1;
  73120. PhysicsImpostor.BoxImpostor = 2;
  73121. PhysicsImpostor.PlaneImpostor = 3;
  73122. PhysicsImpostor.MeshImpostor = 4;
  73123. PhysicsImpostor.CylinderImpostor = 7;
  73124. PhysicsImpostor.ParticleImpostor = 8;
  73125. PhysicsImpostor.HeightmapImpostor = 9;
  73126. return PhysicsImpostor;
  73127. }());
  73128. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73129. })(BABYLON || (BABYLON = {}));
  73130. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73131. var BABYLON;
  73132. (function (BABYLON) {
  73133. var PhysicsEngine = /** @class */ (function () {
  73134. function PhysicsEngine(gravity, _physicsPlugin) {
  73135. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73136. this._physicsPlugin = _physicsPlugin;
  73137. //new methods and parameters
  73138. this._impostors = [];
  73139. this._joints = [];
  73140. if (!this._physicsPlugin.isSupported()) {
  73141. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73142. + "Please make sure it is included.");
  73143. }
  73144. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73145. this.setGravity(gravity);
  73146. this.setTimeStep();
  73147. }
  73148. PhysicsEngine.prototype.setGravity = function (gravity) {
  73149. this.gravity = gravity;
  73150. this._physicsPlugin.setGravity(this.gravity);
  73151. };
  73152. /**
  73153. * Set the time step of the physics engine.
  73154. * default is 1/60.
  73155. * To slow it down, enter 1/600 for example.
  73156. * To speed it up, 1/30
  73157. * @param {number} newTimeStep the new timestep to apply to this world.
  73158. */
  73159. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73160. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73161. this._physicsPlugin.setTimeStep(newTimeStep);
  73162. };
  73163. /**
  73164. * Get the time step of the physics engine.
  73165. */
  73166. PhysicsEngine.prototype.getTimeStep = function () {
  73167. return this._physicsPlugin.getTimeStep();
  73168. };
  73169. PhysicsEngine.prototype.dispose = function () {
  73170. this._impostors.forEach(function (impostor) {
  73171. impostor.dispose();
  73172. });
  73173. this._physicsPlugin.dispose();
  73174. };
  73175. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73176. return this._physicsPlugin.name;
  73177. };
  73178. /**
  73179. * Adding a new impostor for the impostor tracking.
  73180. * This will be done by the impostor itself.
  73181. * @param {PhysicsImpostor} impostor the impostor to add
  73182. */
  73183. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73184. impostor.uniqueId = this._impostors.push(impostor);
  73185. //if no parent, generate the body
  73186. if (!impostor.parent) {
  73187. this._physicsPlugin.generatePhysicsBody(impostor);
  73188. }
  73189. };
  73190. /**
  73191. * Remove an impostor from the engine.
  73192. * This impostor and its mesh will not longer be updated by the physics engine.
  73193. * @param {PhysicsImpostor} impostor the impostor to remove
  73194. */
  73195. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73196. var index = this._impostors.indexOf(impostor);
  73197. if (index > -1) {
  73198. var removed = this._impostors.splice(index, 1);
  73199. //Is it needed?
  73200. if (removed.length) {
  73201. //this will also remove it from the world.
  73202. removed[0].physicsBody = null;
  73203. }
  73204. }
  73205. };
  73206. /**
  73207. * Add a joint to the physics engine
  73208. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73209. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73210. * @param {PhysicsJoint} the joint that will connect both impostors.
  73211. */
  73212. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73213. var impostorJoint = {
  73214. mainImpostor: mainImpostor,
  73215. connectedImpostor: connectedImpostor,
  73216. joint: joint
  73217. };
  73218. joint.physicsPlugin = this._physicsPlugin;
  73219. this._joints.push(impostorJoint);
  73220. this._physicsPlugin.generateJoint(impostorJoint);
  73221. };
  73222. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73223. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73224. return (impostorJoint.connectedImpostor === connectedImpostor
  73225. && impostorJoint.joint === joint
  73226. && impostorJoint.mainImpostor === mainImpostor);
  73227. });
  73228. if (matchingJoints.length) {
  73229. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73230. //TODO remove it from the list as well
  73231. }
  73232. };
  73233. /**
  73234. * Called by the scene. no need to call it.
  73235. */
  73236. PhysicsEngine.prototype._step = function (delta) {
  73237. var _this = this;
  73238. //check if any mesh has no body / requires an update
  73239. this._impostors.forEach(function (impostor) {
  73240. if (impostor.isBodyInitRequired()) {
  73241. _this._physicsPlugin.generatePhysicsBody(impostor);
  73242. }
  73243. });
  73244. if (delta > 0.1) {
  73245. delta = 0.1;
  73246. }
  73247. else if (delta <= 0) {
  73248. delta = 1.0 / 60.0;
  73249. }
  73250. this._physicsPlugin.executeStep(delta, this._impostors);
  73251. };
  73252. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  73253. return this._physicsPlugin;
  73254. };
  73255. PhysicsEngine.prototype.getImpostors = function () {
  73256. return this._impostors;
  73257. };
  73258. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  73259. for (var i = 0; i < this._impostors.length; ++i) {
  73260. if (this._impostors[i].object === object) {
  73261. return this._impostors[i];
  73262. }
  73263. }
  73264. return null;
  73265. };
  73266. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  73267. for (var i = 0; i < this._impostors.length; ++i) {
  73268. if (this._impostors[i].physicsBody === body) {
  73269. return this._impostors[i];
  73270. }
  73271. }
  73272. return null;
  73273. };
  73274. // Statics
  73275. PhysicsEngine.Epsilon = 0.001;
  73276. return PhysicsEngine;
  73277. }());
  73278. BABYLON.PhysicsEngine = PhysicsEngine;
  73279. })(BABYLON || (BABYLON = {}));
  73280. //# sourceMappingURL=babylon.physicsEngine.js.map
  73281. var BABYLON;
  73282. (function (BABYLON) {
  73283. var PhysicsHelper = /** @class */ (function () {
  73284. function PhysicsHelper(scene) {
  73285. this._scene = scene;
  73286. this._physicsEngine = this._scene.getPhysicsEngine();
  73287. if (!this._physicsEngine) {
  73288. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  73289. }
  73290. }
  73291. /**
  73292. * @param {Vector3} origin the origin of the explosion
  73293. * @param {number} radius the explosion radius
  73294. * @param {number} strength the explosion strength
  73295. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73296. */
  73297. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  73298. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73299. if (!this._physicsEngine) {
  73300. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  73301. return null;
  73302. }
  73303. var impostors = this._physicsEngine.getImpostors();
  73304. if (impostors.length === 0) {
  73305. return null;
  73306. }
  73307. var event = new PhysicsRadialExplosionEvent(this._scene);
  73308. impostors.forEach(function (impostor) {
  73309. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73310. if (!impostorForceAndContactPoint) {
  73311. return;
  73312. }
  73313. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73314. });
  73315. event.dispose(false);
  73316. return event;
  73317. };
  73318. /**
  73319. * @param {Vector3} origin the origin of the explosion
  73320. * @param {number} radius the explosion radius
  73321. * @param {number} strength the explosion strength
  73322. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73323. */
  73324. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  73325. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73326. if (!this._physicsEngine) {
  73327. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73328. return null;
  73329. }
  73330. var impostors = this._physicsEngine.getImpostors();
  73331. if (impostors.length === 0) {
  73332. return null;
  73333. }
  73334. var event = new PhysicsRadialExplosionEvent(this._scene);
  73335. impostors.forEach(function (impostor) {
  73336. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73337. if (!impostorForceAndContactPoint) {
  73338. return;
  73339. }
  73340. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73341. });
  73342. event.dispose(false);
  73343. return event;
  73344. };
  73345. /**
  73346. * @param {Vector3} origin the origin of the explosion
  73347. * @param {number} radius the explosion radius
  73348. * @param {number} strength the explosion strength
  73349. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73350. */
  73351. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  73352. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73353. if (!this._physicsEngine) {
  73354. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73355. return null;
  73356. }
  73357. var impostors = this._physicsEngine.getImpostors();
  73358. if (impostors.length === 0) {
  73359. return null;
  73360. }
  73361. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  73362. event.dispose(false);
  73363. return event;
  73364. };
  73365. /**
  73366. * @param {Vector3} origin the origin of the updraft
  73367. * @param {number} radius the radius of the updraft
  73368. * @param {number} strength the strength of the updraft
  73369. * @param {number} height the height of the updraft
  73370. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  73371. */
  73372. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  73373. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  73374. if (!this._physicsEngine) {
  73375. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73376. return null;
  73377. }
  73378. if (this._physicsEngine.getImpostors().length === 0) {
  73379. return null;
  73380. }
  73381. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  73382. event.dispose(false);
  73383. return event;
  73384. };
  73385. /**
  73386. * @param {Vector3} origin the of the vortex
  73387. * @param {number} radius the radius of the vortex
  73388. * @param {number} strength the strength of the vortex
  73389. * @param {number} height the height of the vortex
  73390. */
  73391. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  73392. if (!this._physicsEngine) {
  73393. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73394. return null;
  73395. }
  73396. if (this._physicsEngine.getImpostors().length === 0) {
  73397. return null;
  73398. }
  73399. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  73400. event.dispose(false);
  73401. return event;
  73402. };
  73403. return PhysicsHelper;
  73404. }());
  73405. BABYLON.PhysicsHelper = PhysicsHelper;
  73406. /***** Radial explosion *****/
  73407. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  73408. function PhysicsRadialExplosionEvent(scene) {
  73409. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  73410. this._rays = [];
  73411. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  73412. this._scene = scene;
  73413. }
  73414. /**
  73415. * Returns the data related to the radial explosion event (sphere & rays).
  73416. * @returns {PhysicsRadialExplosionEventData}
  73417. */
  73418. PhysicsRadialExplosionEvent.prototype.getData = function () {
  73419. this._dataFetched = true;
  73420. return {
  73421. sphere: this._sphere,
  73422. rays: this._rays,
  73423. };
  73424. };
  73425. /**
  73426. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  73427. * @param impostor
  73428. * @param {Vector3} origin the origin of the explosion
  73429. * @param {number} radius the explosion radius
  73430. * @param {number} strength the explosion strength
  73431. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  73432. * @returns {Nullable<PhysicsForceAndContactPoint>}
  73433. */
  73434. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  73435. if (impostor.mass === 0) {
  73436. return null;
  73437. }
  73438. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  73439. return null;
  73440. }
  73441. if (impostor.object.getClassName() !== 'Mesh') {
  73442. return null;
  73443. }
  73444. var impostorObject = impostor.object;
  73445. var impostorObjectCenter = impostor.getObjectCenter();
  73446. var direction = impostorObjectCenter.subtract(origin);
  73447. var ray = new BABYLON.Ray(origin, direction, radius);
  73448. this._rays.push(ray);
  73449. var hit = ray.intersectsMesh(impostorObject);
  73450. var contactPoint = hit.pickedPoint;
  73451. if (!contactPoint) {
  73452. return null;
  73453. }
  73454. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  73455. if (distanceFromOrigin > radius) {
  73456. return null;
  73457. }
  73458. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  73459. ? strength
  73460. : strength * (1 - (distanceFromOrigin / radius));
  73461. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  73462. return { force: force, contactPoint: contactPoint };
  73463. };
  73464. /**
  73465. * Disposes the sphere.
  73466. * @param {bolean} force
  73467. */
  73468. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  73469. var _this = this;
  73470. if (force === void 0) { force = true; }
  73471. if (force) {
  73472. this._sphere.dispose();
  73473. }
  73474. else {
  73475. setTimeout(function () {
  73476. if (!_this._dataFetched) {
  73477. _this._sphere.dispose();
  73478. }
  73479. }, 0);
  73480. }
  73481. };
  73482. /*** Helpers ***/
  73483. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  73484. if (!this._sphere) {
  73485. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  73486. this._sphere.isVisible = false;
  73487. }
  73488. };
  73489. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  73490. var impostorObject = impostor.object;
  73491. this._prepareSphere();
  73492. this._sphere.position = origin;
  73493. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  73494. this._sphere._updateBoundingInfo();
  73495. this._sphere.computeWorldMatrix(true);
  73496. return this._sphere.intersectsMesh(impostorObject, true);
  73497. };
  73498. return PhysicsRadialExplosionEvent;
  73499. }());
  73500. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  73501. /***** Gravitational Field *****/
  73502. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  73503. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  73504. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73505. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  73506. this._physicsHelper = physicsHelper;
  73507. this._scene = scene;
  73508. this._origin = origin;
  73509. this._radius = radius;
  73510. this._strength = strength;
  73511. this._falloff = falloff;
  73512. this._tickCallback = this._tick.bind(this);
  73513. }
  73514. /**
  73515. * Returns the data related to the gravitational field event (sphere).
  73516. * @returns {PhysicsGravitationalFieldEventData}
  73517. */
  73518. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  73519. this._dataFetched = true;
  73520. return {
  73521. sphere: this._sphere,
  73522. };
  73523. };
  73524. /**
  73525. * Enables the gravitational field.
  73526. */
  73527. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  73528. this._tickCallback.call(this);
  73529. this._scene.registerBeforeRender(this._tickCallback);
  73530. };
  73531. /**
  73532. * Disables the gravitational field.
  73533. */
  73534. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  73535. this._scene.unregisterBeforeRender(this._tickCallback);
  73536. };
  73537. /**
  73538. * Disposes the sphere.
  73539. * @param {bolean} force
  73540. */
  73541. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  73542. var _this = this;
  73543. if (force === void 0) { force = true; }
  73544. if (force) {
  73545. this._sphere.dispose();
  73546. }
  73547. else {
  73548. setTimeout(function () {
  73549. if (!_this._dataFetched) {
  73550. _this._sphere.dispose();
  73551. }
  73552. }, 0);
  73553. }
  73554. };
  73555. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  73556. // Since the params won't change, we fetch the event only once
  73557. if (this._sphere) {
  73558. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  73559. }
  73560. else {
  73561. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  73562. if (radialExplosionEvent) {
  73563. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  73564. }
  73565. }
  73566. };
  73567. return PhysicsGravitationalFieldEvent;
  73568. }());
  73569. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  73570. /***** Updraft *****/
  73571. var PhysicsUpdraftEvent = /** @class */ (function () {
  73572. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  73573. this._scene = _scene;
  73574. this._origin = _origin;
  73575. this._radius = _radius;
  73576. this._strength = _strength;
  73577. this._height = _height;
  73578. this._updraftMode = _updraftMode;
  73579. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  73580. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  73581. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  73582. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  73583. this._physicsEngine = this._scene.getPhysicsEngine();
  73584. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  73585. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  73586. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  73587. this._originDirection = this._origin.subtract(this._originTop).normalize();
  73588. }
  73589. this._tickCallback = this._tick.bind(this);
  73590. }
  73591. /**
  73592. * Returns the data related to the updraft event (cylinder).
  73593. * @returns {PhysicsUpdraftEventData}
  73594. */
  73595. PhysicsUpdraftEvent.prototype.getData = function () {
  73596. this._dataFetched = true;
  73597. return {
  73598. cylinder: this._cylinder,
  73599. };
  73600. };
  73601. /**
  73602. * Enables the updraft.
  73603. */
  73604. PhysicsUpdraftEvent.prototype.enable = function () {
  73605. this._tickCallback.call(this);
  73606. this._scene.registerBeforeRender(this._tickCallback);
  73607. };
  73608. /**
  73609. * Disables the cortex.
  73610. */
  73611. PhysicsUpdraftEvent.prototype.disable = function () {
  73612. this._scene.unregisterBeforeRender(this._tickCallback);
  73613. };
  73614. /**
  73615. * Disposes the sphere.
  73616. * @param {bolean} force
  73617. */
  73618. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  73619. var _this = this;
  73620. if (force === void 0) { force = true; }
  73621. if (force) {
  73622. this._cylinder.dispose();
  73623. }
  73624. else {
  73625. setTimeout(function () {
  73626. if (!_this._dataFetched) {
  73627. _this._cylinder.dispose();
  73628. }
  73629. }, 0);
  73630. }
  73631. };
  73632. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  73633. if (impostor.mass === 0) {
  73634. return null;
  73635. }
  73636. if (!this._intersectsWithCylinder(impostor)) {
  73637. return null;
  73638. }
  73639. var impostorObjectCenter = impostor.getObjectCenter();
  73640. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  73641. var direction = this._originDirection;
  73642. }
  73643. else {
  73644. var direction = impostorObjectCenter.subtract(this._originTop);
  73645. }
  73646. var multiplier = this._strength * -1;
  73647. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  73648. return { force: force, contactPoint: impostorObjectCenter };
  73649. };
  73650. PhysicsUpdraftEvent.prototype._tick = function () {
  73651. var _this = this;
  73652. this._physicsEngine.getImpostors().forEach(function (impostor) {
  73653. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  73654. if (!impostorForceAndContactPoint) {
  73655. return;
  73656. }
  73657. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73658. });
  73659. };
  73660. /*** Helpers ***/
  73661. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  73662. if (!this._cylinder) {
  73663. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  73664. height: this._height,
  73665. diameter: this._radius * 2,
  73666. }, this._scene);
  73667. this._cylinder.isVisible = false;
  73668. }
  73669. };
  73670. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  73671. var impostorObject = impostor.object;
  73672. this._prepareCylinder();
  73673. this._cylinder.position = this._cylinderPosition;
  73674. return this._cylinder.intersectsMesh(impostorObject, true);
  73675. };
  73676. return PhysicsUpdraftEvent;
  73677. }());
  73678. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  73679. /***** Vortex *****/
  73680. var PhysicsVortexEvent = /** @class */ (function () {
  73681. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  73682. this._scene = _scene;
  73683. this._origin = _origin;
  73684. this._radius = _radius;
  73685. this._strength = _strength;
  73686. this._height = _height;
  73687. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  73688. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  73689. this._updraftMultiplier = 0.02;
  73690. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  73691. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  73692. this._physicsEngine = this._scene.getPhysicsEngine();
  73693. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  73694. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  73695. this._tickCallback = this._tick.bind(this);
  73696. }
  73697. /**
  73698. * Returns the data related to the vortex event (cylinder).
  73699. * @returns {PhysicsVortexEventData}
  73700. */
  73701. PhysicsVortexEvent.prototype.getData = function () {
  73702. this._dataFetched = true;
  73703. return {
  73704. cylinder: this._cylinder,
  73705. };
  73706. };
  73707. /**
  73708. * Enables the vortex.
  73709. */
  73710. PhysicsVortexEvent.prototype.enable = function () {
  73711. this._tickCallback.call(this);
  73712. this._scene.registerBeforeRender(this._tickCallback);
  73713. };
  73714. /**
  73715. * Disables the cortex.
  73716. */
  73717. PhysicsVortexEvent.prototype.disable = function () {
  73718. this._scene.unregisterBeforeRender(this._tickCallback);
  73719. };
  73720. /**
  73721. * Disposes the sphere.
  73722. * @param {bolean} force
  73723. */
  73724. PhysicsVortexEvent.prototype.dispose = function (force) {
  73725. var _this = this;
  73726. if (force === void 0) { force = true; }
  73727. if (force) {
  73728. this._cylinder.dispose();
  73729. }
  73730. else {
  73731. setTimeout(function () {
  73732. if (!_this._dataFetched) {
  73733. _this._cylinder.dispose();
  73734. }
  73735. }, 0);
  73736. }
  73737. };
  73738. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  73739. if (impostor.mass === 0) {
  73740. return null;
  73741. }
  73742. if (!this._intersectsWithCylinder(impostor)) {
  73743. return null;
  73744. }
  73745. if (impostor.object.getClassName() !== 'Mesh') {
  73746. return null;
  73747. }
  73748. var impostorObject = impostor.object;
  73749. var impostorObjectCenter = impostor.getObjectCenter();
  73750. 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)
  73751. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  73752. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  73753. var hit = ray.intersectsMesh(impostorObject);
  73754. var contactPoint = hit.pickedPoint;
  73755. if (!contactPoint) {
  73756. return null;
  73757. }
  73758. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  73759. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  73760. var directionToOrigin = contactPoint.normalize();
  73761. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  73762. directionToOrigin = directionToOrigin.negate();
  73763. }
  73764. // TODO: find a more physically based solution
  73765. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  73766. var forceX = directionToOrigin.x * this._strength / 8;
  73767. var forceY = directionToOrigin.y * this._updraftMultiplier;
  73768. var forceZ = directionToOrigin.z * this._strength / 8;
  73769. }
  73770. else {
  73771. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  73772. var forceY = this._originTop.y * this._updraftMultiplier;
  73773. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  73774. }
  73775. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  73776. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  73777. return { force: force, contactPoint: impostorObjectCenter };
  73778. };
  73779. PhysicsVortexEvent.prototype._tick = function () {
  73780. var _this = this;
  73781. this._physicsEngine.getImpostors().forEach(function (impostor) {
  73782. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  73783. if (!impostorForceAndContactPoint) {
  73784. return;
  73785. }
  73786. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73787. });
  73788. };
  73789. /*** Helpers ***/
  73790. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  73791. if (!this._cylinder) {
  73792. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  73793. height: this._height,
  73794. diameter: this._radius * 2,
  73795. }, this._scene);
  73796. this._cylinder.isVisible = false;
  73797. }
  73798. };
  73799. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  73800. var impostorObject = impostor.object;
  73801. this._prepareCylinder();
  73802. this._cylinder.position = this._cylinderPosition;
  73803. return this._cylinder.intersectsMesh(impostorObject, true);
  73804. };
  73805. return PhysicsVortexEvent;
  73806. }());
  73807. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  73808. /***** Enums *****/
  73809. /**
  73810. * The strenght of the force in correspondence to the distance of the affected object
  73811. */
  73812. var PhysicsRadialImpulseFalloff;
  73813. (function (PhysicsRadialImpulseFalloff) {
  73814. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  73815. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  73816. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  73817. /**
  73818. * The strenght of the force in correspondence to the distance of the affected object
  73819. */
  73820. var PhysicsUpdraftMode;
  73821. (function (PhysicsUpdraftMode) {
  73822. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  73823. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  73824. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  73825. })(BABYLON || (BABYLON = {}));
  73826. //# sourceMappingURL=babylon.physicsHelper.js.map
  73827. var BABYLON;
  73828. (function (BABYLON) {
  73829. var CannonJSPlugin = /** @class */ (function () {
  73830. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  73831. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  73832. if (iterations === void 0) { iterations = 10; }
  73833. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  73834. this.name = "CannonJSPlugin";
  73835. this._physicsMaterials = new Array();
  73836. this._fixedTimeStep = 1 / 60;
  73837. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  73838. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  73839. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  73840. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  73841. this._tmpPosition = BABYLON.Vector3.Zero();
  73842. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  73843. this._tmpUnityRotation = new BABYLON.Quaternion();
  73844. if (!this.isSupported()) {
  73845. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  73846. return;
  73847. }
  73848. this._extendNamespace();
  73849. this.world = new this.BJSCANNON.World();
  73850. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  73851. this.world.solver.iterations = iterations;
  73852. }
  73853. CannonJSPlugin.prototype.setGravity = function (gravity) {
  73854. this.world.gravity.copy(gravity);
  73855. };
  73856. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  73857. this._fixedTimeStep = timeStep;
  73858. };
  73859. CannonJSPlugin.prototype.getTimeStep = function () {
  73860. return this._fixedTimeStep;
  73861. };
  73862. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  73863. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  73864. };
  73865. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  73866. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  73867. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  73868. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  73869. };
  73870. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  73871. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  73872. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  73873. impostor.physicsBody.applyForce(impulse, worldPoint);
  73874. };
  73875. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  73876. //parent-child relationship. Does this impostor has a parent impostor?
  73877. if (impostor.parent) {
  73878. if (impostor.physicsBody) {
  73879. this.removePhysicsBody(impostor);
  73880. //TODO is that needed?
  73881. impostor.forceUpdate();
  73882. }
  73883. return;
  73884. }
  73885. //should a new body be created for this impostor?
  73886. if (impostor.isBodyInitRequired()) {
  73887. var shape = this._createShape(impostor);
  73888. //unregister events, if body is being changed
  73889. var oldBody = impostor.physicsBody;
  73890. if (oldBody) {
  73891. this.removePhysicsBody(impostor);
  73892. }
  73893. //create the body and material
  73894. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  73895. var bodyCreationObject = {
  73896. mass: impostor.getParam("mass"),
  73897. material: material
  73898. };
  73899. // A simple extend, in case native options were used.
  73900. var nativeOptions = impostor.getParam("nativeOptions");
  73901. for (var key in nativeOptions) {
  73902. if (nativeOptions.hasOwnProperty(key)) {
  73903. bodyCreationObject[key] = nativeOptions[key];
  73904. }
  73905. }
  73906. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  73907. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  73908. this.world.addEventListener("preStep", impostor.beforeStep);
  73909. this.world.addEventListener("postStep", impostor.afterStep);
  73910. impostor.physicsBody.addShape(shape);
  73911. this.world.add(impostor.physicsBody);
  73912. //try to keep the body moving in the right direction by taking old properties.
  73913. //Should be tested!
  73914. if (oldBody) {
  73915. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  73916. impostor.physicsBody[param].copy(oldBody[param]);
  73917. });
  73918. }
  73919. this._processChildMeshes(impostor);
  73920. }
  73921. //now update the body's transformation
  73922. this._updatePhysicsBodyTransformation(impostor);
  73923. };
  73924. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  73925. var _this = this;
  73926. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  73927. var currentRotation = mainImpostor.object.rotationQuaternion;
  73928. if (meshChildren.length) {
  73929. var processMesh = function (localPosition, mesh) {
  73930. if (!currentRotation || !mesh.rotationQuaternion) {
  73931. return;
  73932. }
  73933. var childImpostor = mesh.getPhysicsImpostor();
  73934. if (childImpostor) {
  73935. var parent = childImpostor.parent;
  73936. if (parent !== mainImpostor) {
  73937. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  73938. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  73939. if (childImpostor.physicsBody) {
  73940. _this.removePhysicsBody(childImpostor);
  73941. childImpostor.physicsBody = null;
  73942. }
  73943. childImpostor.parent = mainImpostor;
  73944. childImpostor.resetUpdateFlags();
  73945. 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));
  73946. //Add the mass of the children.
  73947. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  73948. }
  73949. }
  73950. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  73951. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  73952. };
  73953. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  73954. }
  73955. };
  73956. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  73957. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  73958. this.world.removeEventListener("preStep", impostor.beforeStep);
  73959. this.world.removeEventListener("postStep", impostor.afterStep);
  73960. this.world.remove(impostor.physicsBody);
  73961. };
  73962. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  73963. var mainBody = impostorJoint.mainImpostor.physicsBody;
  73964. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  73965. if (!mainBody || !connectedBody) {
  73966. return;
  73967. }
  73968. var constraint;
  73969. var jointData = impostorJoint.joint.jointData;
  73970. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  73971. var constraintData = {
  73972. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  73973. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  73974. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  73975. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  73976. maxForce: jointData.nativeParams.maxForce,
  73977. collideConnected: !!jointData.collision
  73978. };
  73979. switch (impostorJoint.joint.type) {
  73980. case BABYLON.PhysicsJoint.HingeJoint:
  73981. case BABYLON.PhysicsJoint.Hinge2Joint:
  73982. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  73983. break;
  73984. case BABYLON.PhysicsJoint.DistanceJoint:
  73985. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  73986. break;
  73987. case BABYLON.PhysicsJoint.SpringJoint:
  73988. var springData = jointData;
  73989. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  73990. restLength: springData.length,
  73991. stiffness: springData.stiffness,
  73992. damping: springData.damping,
  73993. localAnchorA: constraintData.pivotA,
  73994. localAnchorB: constraintData.pivotB
  73995. });
  73996. break;
  73997. case BABYLON.PhysicsJoint.LockJoint:
  73998. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  73999. break;
  74000. case BABYLON.PhysicsJoint.PointToPointJoint:
  74001. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74002. default:
  74003. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74004. break;
  74005. }
  74006. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74007. constraint.collideConnected = !!jointData.collision;
  74008. impostorJoint.joint.physicsJoint = constraint;
  74009. //don't add spring as constraint, as it is not one.
  74010. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74011. this.world.addConstraint(constraint);
  74012. }
  74013. else {
  74014. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74015. constraint.applyForce();
  74016. });
  74017. }
  74018. };
  74019. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74020. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74021. };
  74022. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74023. var index;
  74024. var mat;
  74025. for (index = 0; index < this._physicsMaterials.length; index++) {
  74026. mat = this._physicsMaterials[index];
  74027. if (mat.friction === friction && mat.restitution === restitution) {
  74028. return mat;
  74029. }
  74030. }
  74031. var currentMat = new this.BJSCANNON.Material(name);
  74032. currentMat.friction = friction;
  74033. currentMat.restitution = restitution;
  74034. this._physicsMaterials.push(currentMat);
  74035. return currentMat;
  74036. };
  74037. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74038. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74039. };
  74040. CannonJSPlugin.prototype._createShape = function (impostor) {
  74041. var object = impostor.object;
  74042. var returnValue;
  74043. var extendSize = impostor.getObjectExtendSize();
  74044. switch (impostor.type) {
  74045. case BABYLON.PhysicsImpostor.SphereImpostor:
  74046. var radiusX = extendSize.x;
  74047. var radiusY = extendSize.y;
  74048. var radiusZ = extendSize.z;
  74049. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74050. break;
  74051. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74052. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74053. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74054. break;
  74055. case BABYLON.PhysicsImpostor.BoxImpostor:
  74056. var box = extendSize.scale(0.5);
  74057. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74058. break;
  74059. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74060. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74061. returnValue = new this.BJSCANNON.Plane();
  74062. break;
  74063. case BABYLON.PhysicsImpostor.MeshImpostor:
  74064. // should transform the vertex data to world coordinates!!
  74065. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74066. var rawFaces = object.getIndices ? object.getIndices() : [];
  74067. if (!rawVerts)
  74068. return;
  74069. // get only scale! so the object could transform correctly.
  74070. var oldPosition = object.position.clone();
  74071. var oldRotation = object.rotation && object.rotation.clone();
  74072. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74073. object.position.copyFromFloats(0, 0, 0);
  74074. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74075. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74076. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74077. var transform = object.computeWorldMatrix(true);
  74078. // convert rawVerts to object space
  74079. var temp = new Array();
  74080. var index;
  74081. for (index = 0; index < rawVerts.length; index += 3) {
  74082. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74083. }
  74084. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74085. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74086. //now set back the transformation!
  74087. object.position.copyFrom(oldPosition);
  74088. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74089. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74090. break;
  74091. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74092. var oldPosition2 = object.position.clone();
  74093. var oldRotation2 = object.rotation && object.rotation.clone();
  74094. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74095. object.position.copyFromFloats(0, 0, 0);
  74096. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74097. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74098. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74099. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74100. returnValue = this._createHeightmap(object);
  74101. object.position.copyFrom(oldPosition2);
  74102. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74103. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74104. object.computeWorldMatrix(true);
  74105. break;
  74106. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74107. returnValue = new this.BJSCANNON.Particle();
  74108. break;
  74109. }
  74110. return returnValue;
  74111. };
  74112. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74113. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74114. var transform = object.computeWorldMatrix(true);
  74115. // convert rawVerts to object space
  74116. var temp = new Array();
  74117. var index;
  74118. for (index = 0; index < pos.length; index += 3) {
  74119. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74120. }
  74121. pos = temp;
  74122. var matrix = new Array();
  74123. //For now pointDepth will not be used and will be automatically calculated.
  74124. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74125. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74126. var boundingInfo = object.getBoundingInfo();
  74127. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74128. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74129. var elementSize = dim * 2 / arraySize;
  74130. for (var i = 0; i < pos.length; i = i + 3) {
  74131. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74132. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74133. var y = -pos[i + 2] + minY;
  74134. if (!matrix[x]) {
  74135. matrix[x] = [];
  74136. }
  74137. if (!matrix[x][z]) {
  74138. matrix[x][z] = y;
  74139. }
  74140. matrix[x][z] = Math.max(y, matrix[x][z]);
  74141. }
  74142. for (var x = 0; x <= arraySize; ++x) {
  74143. if (!matrix[x]) {
  74144. var loc = 1;
  74145. while (!matrix[(x + loc) % arraySize]) {
  74146. loc++;
  74147. }
  74148. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74149. //console.log("missing x", x);
  74150. }
  74151. for (var z = 0; z <= arraySize; ++z) {
  74152. if (!matrix[x][z]) {
  74153. var loc = 1;
  74154. var newValue;
  74155. while (newValue === undefined) {
  74156. newValue = matrix[x][(z + loc++) % arraySize];
  74157. }
  74158. matrix[x][z] = newValue;
  74159. }
  74160. }
  74161. }
  74162. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74163. elementSize: elementSize
  74164. });
  74165. //For future reference, needed for body transformation
  74166. shape.minY = minY;
  74167. return shape;
  74168. };
  74169. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74170. var object = impostor.object;
  74171. //make sure it is updated...
  74172. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74173. // The delta between the mesh position and the mesh bounding box center
  74174. var bInfo = object.getBoundingInfo();
  74175. if (!bInfo)
  74176. return;
  74177. var center = impostor.getObjectCenter();
  74178. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74179. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74180. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74181. this._tmpPosition.copyFrom(center);
  74182. var quaternion = object.rotationQuaternion;
  74183. if (!quaternion) {
  74184. return;
  74185. }
  74186. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74187. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74188. //-90 DEG in X, precalculated
  74189. quaternion = quaternion.multiply(this._minus90X);
  74190. //Invert! (Precalculated, 90 deg in X)
  74191. //No need to clone. this will never change.
  74192. impostor.setDeltaRotation(this._plus90X);
  74193. }
  74194. //If it is a heightfield, if should be centered.
  74195. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74196. var mesh = object;
  74197. var boundingInfo = mesh.getBoundingInfo();
  74198. //calculate the correct body position:
  74199. var rotationQuaternion = mesh.rotationQuaternion;
  74200. mesh.rotationQuaternion = this._tmpUnityRotation;
  74201. mesh.computeWorldMatrix(true);
  74202. //get original center with no rotation
  74203. var c = center.clone();
  74204. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74205. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74206. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74207. mesh.setPreTransformMatrix(p);
  74208. mesh.computeWorldMatrix(true);
  74209. //calculate the translation
  74210. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74211. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74212. //add it inverted to the delta
  74213. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74214. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74215. //rotation is back
  74216. mesh.rotationQuaternion = rotationQuaternion;
  74217. mesh.setPreTransformMatrix(oldPivot);
  74218. mesh.computeWorldMatrix(true);
  74219. }
  74220. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74221. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74222. //this._tmpPosition.copyFrom(object.position);
  74223. }
  74224. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74225. //Now update the impostor object
  74226. impostor.physicsBody.position.copy(this._tmpPosition);
  74227. impostor.physicsBody.quaternion.copy(quaternion);
  74228. };
  74229. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74230. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74231. if (impostor.object.rotationQuaternion) {
  74232. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  74233. }
  74234. };
  74235. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74236. impostor.physicsBody.position.copy(newPosition);
  74237. impostor.physicsBody.quaternion.copy(newRotation);
  74238. };
  74239. CannonJSPlugin.prototype.isSupported = function () {
  74240. return this.BJSCANNON !== undefined;
  74241. };
  74242. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74243. impostor.physicsBody.velocity.copy(velocity);
  74244. };
  74245. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74246. impostor.physicsBody.angularVelocity.copy(velocity);
  74247. };
  74248. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74249. var v = impostor.physicsBody.velocity;
  74250. if (!v) {
  74251. return null;
  74252. }
  74253. return new BABYLON.Vector3(v.x, v.y, v.z);
  74254. };
  74255. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74256. var v = impostor.physicsBody.angularVelocity;
  74257. if (!v) {
  74258. return null;
  74259. }
  74260. return new BABYLON.Vector3(v.x, v.y, v.z);
  74261. };
  74262. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74263. impostor.physicsBody.mass = mass;
  74264. impostor.physicsBody.updateMassProperties();
  74265. };
  74266. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  74267. return impostor.physicsBody.mass;
  74268. };
  74269. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  74270. return impostor.physicsBody.material.friction;
  74271. };
  74272. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74273. impostor.physicsBody.material.friction = friction;
  74274. };
  74275. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74276. return impostor.physicsBody.material.restitution;
  74277. };
  74278. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74279. impostor.physicsBody.material.restitution = restitution;
  74280. };
  74281. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  74282. impostor.physicsBody.sleep();
  74283. };
  74284. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  74285. impostor.physicsBody.wakeUp();
  74286. };
  74287. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74288. joint.physicsJoint.distance = maxDistance;
  74289. };
  74290. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74291. // if (!motorIndex) {
  74292. // joint.physicsJoint.enableMotor();
  74293. // }
  74294. // }
  74295. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74296. // if (!motorIndex) {
  74297. // joint.physicsJoint.disableMotor();
  74298. // }
  74299. // }
  74300. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74301. if (!motorIndex) {
  74302. joint.physicsJoint.enableMotor();
  74303. joint.physicsJoint.setMotorSpeed(speed);
  74304. if (maxForce) {
  74305. this.setLimit(joint, maxForce);
  74306. }
  74307. }
  74308. };
  74309. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  74310. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  74311. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  74312. };
  74313. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74314. var body = impostor.physicsBody;
  74315. mesh.position.x = body.position.x;
  74316. mesh.position.y = body.position.y;
  74317. mesh.position.z = body.position.z;
  74318. if (mesh.rotationQuaternion) {
  74319. mesh.rotationQuaternion.x = body.quaternion.x;
  74320. mesh.rotationQuaternion.y = body.quaternion.y;
  74321. mesh.rotationQuaternion.z = body.quaternion.z;
  74322. mesh.rotationQuaternion.w = body.quaternion.w;
  74323. }
  74324. };
  74325. CannonJSPlugin.prototype.getRadius = function (impostor) {
  74326. var shape = impostor.physicsBody.shapes[0];
  74327. return shape.boundingSphereRadius;
  74328. };
  74329. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  74330. var shape = impostor.physicsBody.shapes[0];
  74331. result.x = shape.halfExtents.x * 2;
  74332. result.y = shape.halfExtents.y * 2;
  74333. result.z = shape.halfExtents.z * 2;
  74334. };
  74335. CannonJSPlugin.prototype.dispose = function () {
  74336. };
  74337. CannonJSPlugin.prototype._extendNamespace = function () {
  74338. //this will force cannon to execute at least one step when using interpolation
  74339. var step_tmp1 = new this.BJSCANNON.Vec3();
  74340. var Engine = this.BJSCANNON;
  74341. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  74342. maxSubSteps = maxSubSteps || 10;
  74343. timeSinceLastCalled = timeSinceLastCalled || 0;
  74344. if (timeSinceLastCalled === 0) {
  74345. this.internalStep(dt);
  74346. this.time += dt;
  74347. }
  74348. else {
  74349. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  74350. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  74351. var t0 = performance.now();
  74352. for (var i = 0; i !== internalSteps; i++) {
  74353. this.internalStep(dt);
  74354. if (performance.now() - t0 > dt * 1000) {
  74355. break;
  74356. }
  74357. }
  74358. this.time += timeSinceLastCalled;
  74359. var h = this.time % dt;
  74360. var h_div_dt = h / dt;
  74361. var interpvelo = step_tmp1;
  74362. var bodies = this.bodies;
  74363. for (var j = 0; j !== bodies.length; j++) {
  74364. var b = bodies[j];
  74365. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  74366. b.position.vsub(b.previousPosition, interpvelo);
  74367. interpvelo.scale(h_div_dt, interpvelo);
  74368. b.position.vadd(interpvelo, b.interpolatedPosition);
  74369. }
  74370. else {
  74371. b.interpolatedPosition.copy(b.position);
  74372. b.interpolatedQuaternion.copy(b.quaternion);
  74373. }
  74374. }
  74375. }
  74376. };
  74377. };
  74378. return CannonJSPlugin;
  74379. }());
  74380. BABYLON.CannonJSPlugin = CannonJSPlugin;
  74381. })(BABYLON || (BABYLON = {}));
  74382. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  74383. var BABYLON;
  74384. (function (BABYLON) {
  74385. var OimoJSPlugin = /** @class */ (function () {
  74386. function OimoJSPlugin(iterations) {
  74387. this.name = "OimoJSPlugin";
  74388. this._tmpImpostorsArray = [];
  74389. this._tmpPositionVector = BABYLON.Vector3.Zero();
  74390. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  74391. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  74392. this.world.worldscale(1);
  74393. this.world.clear();
  74394. //making sure no stats are calculated
  74395. this.world.isNoStat = true;
  74396. }
  74397. OimoJSPlugin.prototype.setGravity = function (gravity) {
  74398. this.world.gravity.copy(gravity);
  74399. };
  74400. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  74401. this.world.timeStep = timeStep;
  74402. };
  74403. OimoJSPlugin.prototype.getTimeStep = function () {
  74404. return this.world.timeStep;
  74405. };
  74406. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  74407. var _this = this;
  74408. impostors.forEach(function (impostor) {
  74409. impostor.beforeStep();
  74410. });
  74411. this.world.step();
  74412. impostors.forEach(function (impostor) {
  74413. impostor.afterStep();
  74414. //update the ordered impostors array
  74415. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  74416. });
  74417. //check for collisions
  74418. var contact = this.world.contacts;
  74419. while (contact !== null) {
  74420. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  74421. contact = contact.next;
  74422. continue;
  74423. }
  74424. //is this body colliding with any other? get the impostor
  74425. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  74426. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  74427. if (!mainImpostor || !collidingImpostor) {
  74428. contact = contact.next;
  74429. continue;
  74430. }
  74431. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  74432. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  74433. contact = contact.next;
  74434. }
  74435. };
  74436. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74437. var mass = impostor.physicsBody.massInfo.mass;
  74438. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  74439. };
  74440. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74441. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  74442. this.applyImpulse(impostor, force, contactPoint);
  74443. };
  74444. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74445. var _this = this;
  74446. //parent-child relationship. Does this impostor has a parent impostor?
  74447. if (impostor.parent) {
  74448. if (impostor.physicsBody) {
  74449. this.removePhysicsBody(impostor);
  74450. //TODO is that needed?
  74451. impostor.forceUpdate();
  74452. }
  74453. return;
  74454. }
  74455. if (impostor.isBodyInitRequired()) {
  74456. var bodyConfig = {
  74457. name: impostor.uniqueId,
  74458. //Oimo must have mass, also for static objects.
  74459. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  74460. size: [],
  74461. type: [],
  74462. pos: [],
  74463. rot: [],
  74464. move: impostor.getParam("mass") !== 0,
  74465. //Supporting older versions of Oimo
  74466. world: this.world
  74467. };
  74468. var impostors = [impostor];
  74469. var addToArray = function (parent) {
  74470. if (!parent.getChildMeshes)
  74471. return;
  74472. parent.getChildMeshes().forEach(function (m) {
  74473. if (m.physicsImpostor) {
  74474. impostors.push(m.physicsImpostor);
  74475. //m.physicsImpostor._init();
  74476. }
  74477. });
  74478. };
  74479. addToArray(impostor.object);
  74480. var checkWithEpsilon_1 = function (value) {
  74481. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  74482. };
  74483. impostors.forEach(function (i) {
  74484. if (!impostor.object.rotationQuaternion) {
  74485. return;
  74486. }
  74487. //get the correct bounding box
  74488. var oldQuaternion = i.object.rotationQuaternion;
  74489. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  74490. x: impostor.object.rotationQuaternion.x,
  74491. y: impostor.object.rotationQuaternion.y,
  74492. z: impostor.object.rotationQuaternion.z,
  74493. s: impostor.object.rotationQuaternion.w
  74494. });
  74495. var extendSize = i.getObjectExtendSize();
  74496. if (i === impostor) {
  74497. var center = impostor.getObjectCenter();
  74498. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  74499. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  74500. //Can also use Array.prototype.push.apply
  74501. bodyConfig.pos.push(center.x);
  74502. bodyConfig.pos.push(center.y);
  74503. bodyConfig.pos.push(center.z);
  74504. //tmp solution
  74505. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74506. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74507. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74508. }
  74509. else {
  74510. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  74511. bodyConfig.pos.push(localPosition.x);
  74512. bodyConfig.pos.push(localPosition.y);
  74513. bodyConfig.pos.push(localPosition.z);
  74514. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  74515. bodyConfig.rot.push(0);
  74516. bodyConfig.rot.push(0);
  74517. bodyConfig.rot.push(0);
  74518. }
  74519. // register mesh
  74520. switch (i.type) {
  74521. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74522. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  74523. case BABYLON.PhysicsImpostor.SphereImpostor:
  74524. var radiusX = extendSize.x;
  74525. var radiusY = extendSize.y;
  74526. var radiusZ = extendSize.z;
  74527. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  74528. bodyConfig.type.push('sphere');
  74529. //due to the way oimo works with compounds, add 3 times
  74530. bodyConfig.size.push(size);
  74531. bodyConfig.size.push(size);
  74532. bodyConfig.size.push(size);
  74533. break;
  74534. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74535. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  74536. var sizeY = checkWithEpsilon_1(extendSize.y);
  74537. bodyConfig.type.push('cylinder');
  74538. bodyConfig.size.push(sizeX);
  74539. bodyConfig.size.push(sizeY);
  74540. //due to the way oimo works with compounds, add one more value.
  74541. bodyConfig.size.push(sizeY);
  74542. break;
  74543. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74544. case BABYLON.PhysicsImpostor.BoxImpostor:
  74545. default:
  74546. var sizeX = checkWithEpsilon_1(extendSize.x);
  74547. var sizeY = checkWithEpsilon_1(extendSize.y);
  74548. var sizeZ = checkWithEpsilon_1(extendSize.z);
  74549. bodyConfig.type.push('box');
  74550. bodyConfig.size.push(sizeX);
  74551. bodyConfig.size.push(sizeY);
  74552. bodyConfig.size.push(sizeZ);
  74553. break;
  74554. }
  74555. //actually not needed, but hey...
  74556. i.object.rotationQuaternion = oldQuaternion;
  74557. });
  74558. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  74559. }
  74560. else {
  74561. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  74562. }
  74563. impostor.setDeltaPosition(this._tmpPositionVector);
  74564. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  74565. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  74566. };
  74567. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74568. //impostor.physicsBody.dispose();
  74569. //Same as : (older oimo versions)
  74570. this.world.removeRigidBody(impostor.physicsBody);
  74571. };
  74572. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74573. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74574. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74575. if (!mainBody || !connectedBody) {
  74576. return;
  74577. }
  74578. var jointData = impostorJoint.joint.jointData;
  74579. var options = jointData.nativeParams || {};
  74580. var type;
  74581. var nativeJointData = {
  74582. body1: mainBody,
  74583. body2: connectedBody,
  74584. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  74585. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  74586. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  74587. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  74588. min: options.min,
  74589. max: options.max,
  74590. collision: options.collision || jointData.collision,
  74591. spring: options.spring,
  74592. //supporting older version of Oimo
  74593. world: this.world
  74594. };
  74595. switch (impostorJoint.joint.type) {
  74596. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74597. type = "jointBall";
  74598. break;
  74599. case BABYLON.PhysicsJoint.SpringJoint:
  74600. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  74601. var springData = jointData;
  74602. nativeJointData.min = springData.length || nativeJointData.min;
  74603. //Max should also be set, just make sure it is at least min
  74604. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  74605. case BABYLON.PhysicsJoint.DistanceJoint:
  74606. type = "jointDistance";
  74607. nativeJointData.max = jointData.maxDistance;
  74608. break;
  74609. case BABYLON.PhysicsJoint.PrismaticJoint:
  74610. type = "jointPrisme";
  74611. break;
  74612. case BABYLON.PhysicsJoint.SliderJoint:
  74613. type = "jointSlide";
  74614. break;
  74615. case BABYLON.PhysicsJoint.WheelJoint:
  74616. type = "jointWheel";
  74617. break;
  74618. case BABYLON.PhysicsJoint.HingeJoint:
  74619. default:
  74620. type = "jointHinge";
  74621. break;
  74622. }
  74623. nativeJointData.type = type;
  74624. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  74625. };
  74626. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74627. //Bug in Oimo prevents us from disposing a joint in the playground
  74628. //joint.joint.physicsJoint.dispose();
  74629. //So we will bruteforce it!
  74630. try {
  74631. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  74632. }
  74633. catch (e) {
  74634. BABYLON.Tools.Warn(e);
  74635. }
  74636. };
  74637. OimoJSPlugin.prototype.isSupported = function () {
  74638. return this.BJSOIMO !== undefined;
  74639. };
  74640. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74641. if (!impostor.physicsBody.sleeping) {
  74642. //TODO check that
  74643. if (impostor.physicsBody.shapes.next) {
  74644. var parentShape = this._getLastShape(impostor.physicsBody);
  74645. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  74646. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  74647. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  74648. }
  74649. else {
  74650. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  74651. }
  74652. if (impostor.object.rotationQuaternion) {
  74653. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  74654. impostor.object.rotationQuaternion.normalize();
  74655. }
  74656. }
  74657. };
  74658. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74659. var body = impostor.physicsBody;
  74660. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  74661. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  74662. body.syncShapes();
  74663. body.awake();
  74664. };
  74665. OimoJSPlugin.prototype._getLastShape = function (body) {
  74666. var lastShape = body.shapes;
  74667. while (lastShape.next) {
  74668. lastShape = lastShape.next;
  74669. }
  74670. return lastShape;
  74671. };
  74672. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74673. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  74674. };
  74675. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74676. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  74677. };
  74678. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74679. var v = impostor.physicsBody.linearVelocity;
  74680. if (!v) {
  74681. return null;
  74682. }
  74683. return new BABYLON.Vector3(v.x, v.y, v.z);
  74684. };
  74685. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74686. var v = impostor.physicsBody.angularVelocity;
  74687. if (!v) {
  74688. return null;
  74689. }
  74690. return new BABYLON.Vector3(v.x, v.y, v.z);
  74691. };
  74692. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74693. var staticBody = mass === 0;
  74694. //this will actually set the body's density and not its mass.
  74695. //But this is how oimo treats the mass variable.
  74696. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  74697. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  74698. };
  74699. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  74700. return impostor.physicsBody.shapes.density;
  74701. };
  74702. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  74703. return impostor.physicsBody.shapes.friction;
  74704. };
  74705. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74706. impostor.physicsBody.shapes.friction = friction;
  74707. };
  74708. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74709. return impostor.physicsBody.shapes.restitution;
  74710. };
  74711. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74712. impostor.physicsBody.shapes.restitution = restitution;
  74713. };
  74714. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  74715. impostor.physicsBody.sleep();
  74716. };
  74717. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  74718. impostor.physicsBody.awake();
  74719. };
  74720. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74721. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  74722. if (minDistance !== void 0) {
  74723. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  74724. }
  74725. };
  74726. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74727. //TODO separate rotational and transational motors.
  74728. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  74729. if (motor) {
  74730. motor.setMotor(speed, maxForce);
  74731. }
  74732. };
  74733. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  74734. //TODO separate rotational and transational motors.
  74735. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  74736. if (motor) {
  74737. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  74738. }
  74739. };
  74740. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74741. var body = impostor.physicsBody;
  74742. mesh.position.x = body.position.x;
  74743. mesh.position.y = body.position.y;
  74744. mesh.position.z = body.position.z;
  74745. if (mesh.rotationQuaternion) {
  74746. mesh.rotationQuaternion.x = body.orientation.x;
  74747. mesh.rotationQuaternion.y = body.orientation.y;
  74748. mesh.rotationQuaternion.z = body.orientation.z;
  74749. mesh.rotationQuaternion.w = body.orientation.s;
  74750. }
  74751. };
  74752. OimoJSPlugin.prototype.getRadius = function (impostor) {
  74753. return impostor.physicsBody.shapes.radius;
  74754. };
  74755. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  74756. var shape = impostor.physicsBody.shapes;
  74757. result.x = shape.halfWidth * 2;
  74758. result.y = shape.halfHeight * 2;
  74759. result.z = shape.halfDepth * 2;
  74760. };
  74761. OimoJSPlugin.prototype.dispose = function () {
  74762. this.world.clear();
  74763. };
  74764. return OimoJSPlugin;
  74765. }());
  74766. BABYLON.OimoJSPlugin = OimoJSPlugin;
  74767. })(BABYLON || (BABYLON = {}));
  74768. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  74769. var BABYLON;
  74770. (function (BABYLON) {
  74771. /*
  74772. * Based on jsTGALoader - Javascript loader for TGA file
  74773. * By Vincent Thibault
  74774. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  74775. */
  74776. var TGATools = /** @class */ (function () {
  74777. function TGATools() {
  74778. }
  74779. TGATools.GetTGAHeader = function (data) {
  74780. var offset = 0;
  74781. var header = {
  74782. id_length: data[offset++],
  74783. colormap_type: data[offset++],
  74784. image_type: data[offset++],
  74785. colormap_index: data[offset++] | data[offset++] << 8,
  74786. colormap_length: data[offset++] | data[offset++] << 8,
  74787. colormap_size: data[offset++],
  74788. origin: [
  74789. data[offset++] | data[offset++] << 8,
  74790. data[offset++] | data[offset++] << 8
  74791. ],
  74792. width: data[offset++] | data[offset++] << 8,
  74793. height: data[offset++] | data[offset++] << 8,
  74794. pixel_size: data[offset++],
  74795. flags: data[offset++]
  74796. };
  74797. return header;
  74798. };
  74799. TGATools.UploadContent = function (gl, data) {
  74800. // Not enough data to contain header ?
  74801. if (data.length < 19) {
  74802. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  74803. return;
  74804. }
  74805. // Read Header
  74806. var offset = 18;
  74807. var header = TGATools.GetTGAHeader(data);
  74808. // Assume it's a valid Targa file.
  74809. if (header.id_length + offset > data.length) {
  74810. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  74811. return;
  74812. }
  74813. // Skip not needed data
  74814. offset += header.id_length;
  74815. var use_rle = false;
  74816. var use_pal = false;
  74817. var use_grey = false;
  74818. // Get some informations.
  74819. switch (header.image_type) {
  74820. case TGATools._TYPE_RLE_INDEXED:
  74821. use_rle = true;
  74822. case TGATools._TYPE_INDEXED:
  74823. use_pal = true;
  74824. break;
  74825. case TGATools._TYPE_RLE_RGB:
  74826. use_rle = true;
  74827. case TGATools._TYPE_RGB:
  74828. // use_rgb = true;
  74829. break;
  74830. case TGATools._TYPE_RLE_GREY:
  74831. use_rle = true;
  74832. case TGATools._TYPE_GREY:
  74833. use_grey = true;
  74834. break;
  74835. }
  74836. var pixel_data;
  74837. // var numAlphaBits = header.flags & 0xf;
  74838. var pixel_size = header.pixel_size >> 3;
  74839. var pixel_total = header.width * header.height * pixel_size;
  74840. // Read palettes
  74841. var palettes;
  74842. if (use_pal) {
  74843. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  74844. }
  74845. // Read LRE
  74846. if (use_rle) {
  74847. pixel_data = new Uint8Array(pixel_total);
  74848. var c, count, i;
  74849. var localOffset = 0;
  74850. var pixels = new Uint8Array(pixel_size);
  74851. while (offset < pixel_total && localOffset < pixel_total) {
  74852. c = data[offset++];
  74853. count = (c & 0x7f) + 1;
  74854. // RLE pixels
  74855. if (c & 0x80) {
  74856. // Bind pixel tmp array
  74857. for (i = 0; i < pixel_size; ++i) {
  74858. pixels[i] = data[offset++];
  74859. }
  74860. // Copy pixel array
  74861. for (i = 0; i < count; ++i) {
  74862. pixel_data.set(pixels, localOffset + i * pixel_size);
  74863. }
  74864. localOffset += pixel_size * count;
  74865. }
  74866. else {
  74867. count *= pixel_size;
  74868. for (i = 0; i < count; ++i) {
  74869. pixel_data[localOffset + i] = data[offset++];
  74870. }
  74871. localOffset += count;
  74872. }
  74873. }
  74874. }
  74875. else {
  74876. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  74877. }
  74878. // Load to texture
  74879. var x_start, y_start, x_step, y_step, y_end, x_end;
  74880. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  74881. default:
  74882. case TGATools._ORIGIN_UL:
  74883. x_start = 0;
  74884. x_step = 1;
  74885. x_end = header.width;
  74886. y_start = 0;
  74887. y_step = 1;
  74888. y_end = header.height;
  74889. break;
  74890. case TGATools._ORIGIN_BL:
  74891. x_start = 0;
  74892. x_step = 1;
  74893. x_end = header.width;
  74894. y_start = header.height - 1;
  74895. y_step = -1;
  74896. y_end = -1;
  74897. break;
  74898. case TGATools._ORIGIN_UR:
  74899. x_start = header.width - 1;
  74900. x_step = -1;
  74901. x_end = -1;
  74902. y_start = 0;
  74903. y_step = 1;
  74904. y_end = header.height;
  74905. break;
  74906. case TGATools._ORIGIN_BR:
  74907. x_start = header.width - 1;
  74908. x_step = -1;
  74909. x_end = -1;
  74910. y_start = header.height - 1;
  74911. y_step = -1;
  74912. y_end = -1;
  74913. break;
  74914. }
  74915. // Load the specify method
  74916. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  74917. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  74918. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  74919. };
  74920. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74921. var image = pixel_data, colormap = palettes;
  74922. var width = header.width, height = header.height;
  74923. var color, i = 0, x, y;
  74924. var imageData = new Uint8Array(width * height * 4);
  74925. for (y = y_start; y !== y_end; y += y_step) {
  74926. for (x = x_start; x !== x_end; x += x_step, i++) {
  74927. color = image[i];
  74928. imageData[(x + width * y) * 4 + 3] = 255;
  74929. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  74930. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  74931. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  74932. }
  74933. }
  74934. return imageData;
  74935. };
  74936. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74937. var image = pixel_data;
  74938. var width = header.width, height = header.height;
  74939. var color, i = 0, x, y;
  74940. var imageData = new Uint8Array(width * height * 4);
  74941. for (y = y_start; y !== y_end; y += y_step) {
  74942. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  74943. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  74944. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  74945. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  74946. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  74947. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  74948. }
  74949. }
  74950. return imageData;
  74951. };
  74952. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74953. var image = pixel_data;
  74954. var width = header.width, height = header.height;
  74955. var i = 0, x, y;
  74956. var imageData = new Uint8Array(width * height * 4);
  74957. for (y = y_start; y !== y_end; y += y_step) {
  74958. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  74959. imageData[(x + width * y) * 4 + 3] = 255;
  74960. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  74961. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  74962. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  74963. }
  74964. }
  74965. return imageData;
  74966. };
  74967. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74968. var image = pixel_data;
  74969. var width = header.width, height = header.height;
  74970. var i = 0, x, y;
  74971. var imageData = new Uint8Array(width * height * 4);
  74972. for (y = y_start; y !== y_end; y += y_step) {
  74973. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  74974. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  74975. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  74976. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  74977. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  74978. }
  74979. }
  74980. return imageData;
  74981. };
  74982. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74983. var image = pixel_data;
  74984. var width = header.width, height = header.height;
  74985. var color, i = 0, x, y;
  74986. var imageData = new Uint8Array(width * height * 4);
  74987. for (y = y_start; y !== y_end; y += y_step) {
  74988. for (x = x_start; x !== x_end; x += x_step, i++) {
  74989. color = image[i];
  74990. imageData[(x + width * y) * 4 + 0] = color;
  74991. imageData[(x + width * y) * 4 + 1] = color;
  74992. imageData[(x + width * y) * 4 + 2] = color;
  74993. imageData[(x + width * y) * 4 + 3] = 255;
  74994. }
  74995. }
  74996. return imageData;
  74997. };
  74998. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74999. var image = pixel_data;
  75000. var width = header.width, height = header.height;
  75001. var i = 0, x, y;
  75002. var imageData = new Uint8Array(width * height * 4);
  75003. for (y = y_start; y !== y_end; y += y_step) {
  75004. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75005. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75006. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75007. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75008. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75009. }
  75010. }
  75011. return imageData;
  75012. };
  75013. //private static _TYPE_NO_DATA = 0;
  75014. TGATools._TYPE_INDEXED = 1;
  75015. TGATools._TYPE_RGB = 2;
  75016. TGATools._TYPE_GREY = 3;
  75017. TGATools._TYPE_RLE_INDEXED = 9;
  75018. TGATools._TYPE_RLE_RGB = 10;
  75019. TGATools._TYPE_RLE_GREY = 11;
  75020. TGATools._ORIGIN_MASK = 0x30;
  75021. TGATools._ORIGIN_SHIFT = 0x04;
  75022. TGATools._ORIGIN_BL = 0x00;
  75023. TGATools._ORIGIN_BR = 0x01;
  75024. TGATools._ORIGIN_UL = 0x02;
  75025. TGATools._ORIGIN_UR = 0x03;
  75026. return TGATools;
  75027. }());
  75028. BABYLON.TGATools = TGATools;
  75029. })(BABYLON || (BABYLON = {}));
  75030. //# sourceMappingURL=babylon.tga.js.map
  75031. var BABYLON;
  75032. (function (BABYLON) {
  75033. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75034. // All values and structures referenced from:
  75035. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75036. var DDS_MAGIC = 0x20534444;
  75037. var
  75038. //DDSD_CAPS = 0x1,
  75039. //DDSD_HEIGHT = 0x2,
  75040. //DDSD_WIDTH = 0x4,
  75041. //DDSD_PITCH = 0x8,
  75042. //DDSD_PIXELFORMAT = 0x1000,
  75043. DDSD_MIPMAPCOUNT = 0x20000;
  75044. //DDSD_LINEARSIZE = 0x80000,
  75045. //DDSD_DEPTH = 0x800000;
  75046. // var DDSCAPS_COMPLEX = 0x8,
  75047. // DDSCAPS_MIPMAP = 0x400000,
  75048. // DDSCAPS_TEXTURE = 0x1000;
  75049. var DDSCAPS2_CUBEMAP = 0x200;
  75050. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75051. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75052. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75053. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75054. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75055. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75056. // DDSCAPS2_VOLUME = 0x200000;
  75057. var
  75058. //DDPF_ALPHAPIXELS = 0x1,
  75059. //DDPF_ALPHA = 0x2,
  75060. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75061. //DDPF_YUV = 0x200,
  75062. DDPF_LUMINANCE = 0x20000;
  75063. function FourCCToInt32(value) {
  75064. return value.charCodeAt(0) +
  75065. (value.charCodeAt(1) << 8) +
  75066. (value.charCodeAt(2) << 16) +
  75067. (value.charCodeAt(3) << 24);
  75068. }
  75069. function Int32ToFourCC(value) {
  75070. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75071. }
  75072. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75073. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75074. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75075. var FOURCC_DX10 = FourCCToInt32("DX10");
  75076. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75077. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75078. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75079. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75080. var headerLengthInt = 31; // The header length in 32 bit ints
  75081. // Offsets into the header array
  75082. var off_magic = 0;
  75083. var off_size = 1;
  75084. var off_flags = 2;
  75085. var off_height = 3;
  75086. var off_width = 4;
  75087. var off_mipmapCount = 7;
  75088. var off_pfFlags = 20;
  75089. var off_pfFourCC = 21;
  75090. var off_RGBbpp = 22;
  75091. var off_RMask = 23;
  75092. var off_GMask = 24;
  75093. var off_BMask = 25;
  75094. var off_AMask = 26;
  75095. // var off_caps1 = 27;
  75096. var off_caps2 = 28;
  75097. // var off_caps3 = 29;
  75098. // var off_caps4 = 30;
  75099. var off_dxgiFormat = 32;
  75100. ;
  75101. var DDSTools = /** @class */ (function () {
  75102. function DDSTools() {
  75103. }
  75104. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75105. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75106. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75107. var mipmapCount = 1;
  75108. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75109. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75110. }
  75111. var fourCC = header[off_pfFourCC];
  75112. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75113. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75114. switch (fourCC) {
  75115. case FOURCC_D3DFMT_R16G16B16A16F:
  75116. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75117. break;
  75118. case FOURCC_D3DFMT_R32G32B32A32F:
  75119. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75120. break;
  75121. case FOURCC_DX10:
  75122. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75123. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75124. break;
  75125. }
  75126. }
  75127. return {
  75128. width: header[off_width],
  75129. height: header[off_height],
  75130. mipmapCount: mipmapCount,
  75131. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75132. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75133. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75134. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75135. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75136. dxgiFormat: dxgiFormat,
  75137. textureType: textureType
  75138. };
  75139. };
  75140. DDSTools._ToHalfFloat = function (value) {
  75141. if (!DDSTools._FloatView) {
  75142. DDSTools._FloatView = new Float32Array(1);
  75143. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75144. }
  75145. DDSTools._FloatView[0] = value;
  75146. var x = DDSTools._Int32View[0];
  75147. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75148. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75149. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75150. /* If zero, or denormal, or exponent underflows too much for a denormal
  75151. * half, return signed zero. */
  75152. if (e < 103) {
  75153. return bits;
  75154. }
  75155. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75156. if (e > 142) {
  75157. bits |= 0x7c00;
  75158. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75159. * not Inf, so make sure we set one mantissa bit too. */
  75160. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75161. return bits;
  75162. }
  75163. /* If exponent underflows but not too much, return a denormal */
  75164. if (e < 113) {
  75165. m |= 0x0800;
  75166. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75167. * to 1, which is OK. */
  75168. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75169. return bits;
  75170. }
  75171. bits |= ((e - 112) << 10) | (m >> 1);
  75172. bits += m & 1;
  75173. return bits;
  75174. };
  75175. DDSTools._FromHalfFloat = function (value) {
  75176. var s = (value & 0x8000) >> 15;
  75177. var e = (value & 0x7C00) >> 10;
  75178. var f = value & 0x03FF;
  75179. if (e === 0) {
  75180. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75181. }
  75182. else if (e == 0x1F) {
  75183. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75184. }
  75185. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75186. };
  75187. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75188. var destArray = new Float32Array(dataLength);
  75189. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75190. var index = 0;
  75191. for (var y = 0; y < height; y++) {
  75192. for (var x = 0; x < width; x++) {
  75193. var srcPos = (x + y * width) * 4;
  75194. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75195. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75196. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75197. if (DDSTools.StoreLODInAlphaChannel) {
  75198. destArray[index + 3] = lod;
  75199. }
  75200. else {
  75201. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75202. }
  75203. index += 4;
  75204. }
  75205. }
  75206. return destArray;
  75207. };
  75208. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75209. if (DDSTools.StoreLODInAlphaChannel) {
  75210. var destArray = new Uint16Array(dataLength);
  75211. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75212. var index = 0;
  75213. for (var y = 0; y < height; y++) {
  75214. for (var x = 0; x < width; x++) {
  75215. var srcPos = (x + y * width) * 4;
  75216. destArray[index] = srcData[srcPos];
  75217. destArray[index + 1] = srcData[srcPos + 1];
  75218. destArray[index + 2] = srcData[srcPos + 2];
  75219. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75220. index += 4;
  75221. }
  75222. }
  75223. return destArray;
  75224. }
  75225. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75226. };
  75227. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75228. if (DDSTools.StoreLODInAlphaChannel) {
  75229. var destArray = new Float32Array(dataLength);
  75230. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75231. var index = 0;
  75232. for (var y = 0; y < height; y++) {
  75233. for (var x = 0; x < width; x++) {
  75234. var srcPos = (x + y * width) * 4;
  75235. destArray[index] = srcData[srcPos];
  75236. destArray[index + 1] = srcData[srcPos + 1];
  75237. destArray[index + 2] = srcData[srcPos + 2];
  75238. destArray[index + 3] = lod;
  75239. index += 4;
  75240. }
  75241. }
  75242. return destArray;
  75243. }
  75244. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  75245. };
  75246. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75247. var destArray = new Uint8Array(dataLength);
  75248. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75249. var index = 0;
  75250. for (var y = 0; y < height; y++) {
  75251. for (var x = 0; x < width; x++) {
  75252. var srcPos = (x + y * width) * 4;
  75253. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  75254. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  75255. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  75256. if (DDSTools.StoreLODInAlphaChannel) {
  75257. destArray[index + 3] = lod;
  75258. }
  75259. else {
  75260. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  75261. }
  75262. index += 4;
  75263. }
  75264. }
  75265. return destArray;
  75266. };
  75267. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75268. var destArray = new Uint8Array(dataLength);
  75269. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75270. var index = 0;
  75271. for (var y = 0; y < height; y++) {
  75272. for (var x = 0; x < width; x++) {
  75273. var srcPos = (x + y * width) * 4;
  75274. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  75275. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  75276. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  75277. if (DDSTools.StoreLODInAlphaChannel) {
  75278. destArray[index + 3] = lod;
  75279. }
  75280. else {
  75281. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  75282. }
  75283. index += 4;
  75284. }
  75285. }
  75286. return destArray;
  75287. };
  75288. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  75289. var byteArray = new Uint8Array(dataLength);
  75290. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75291. var index = 0;
  75292. for (var y = 0; y < height; y++) {
  75293. for (var x = 0; x < width; x++) {
  75294. var srcPos = (x + y * width) * 4;
  75295. byteArray[index] = srcData[srcPos + rOffset];
  75296. byteArray[index + 1] = srcData[srcPos + gOffset];
  75297. byteArray[index + 2] = srcData[srcPos + bOffset];
  75298. byteArray[index + 3] = srcData[srcPos + aOffset];
  75299. index += 4;
  75300. }
  75301. }
  75302. return byteArray;
  75303. };
  75304. DDSTools._ExtractLongWordOrder = function (value) {
  75305. if (value === 0 || value === 255 || value === -16777216) {
  75306. return 0;
  75307. }
  75308. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  75309. };
  75310. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  75311. var byteArray = new Uint8Array(dataLength);
  75312. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75313. var index = 0;
  75314. for (var y = 0; y < height; y++) {
  75315. for (var x = 0; x < width; x++) {
  75316. var srcPos = (x + y * width) * 3;
  75317. byteArray[index] = srcData[srcPos + rOffset];
  75318. byteArray[index + 1] = srcData[srcPos + gOffset];
  75319. byteArray[index + 2] = srcData[srcPos + bOffset];
  75320. index += 3;
  75321. }
  75322. }
  75323. return byteArray;
  75324. };
  75325. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  75326. var byteArray = new Uint8Array(dataLength);
  75327. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75328. var index = 0;
  75329. for (var y = 0; y < height; y++) {
  75330. for (var x = 0; x < width; x++) {
  75331. var srcPos = (x + y * width);
  75332. byteArray[index] = srcData[srcPos];
  75333. index++;
  75334. }
  75335. }
  75336. return byteArray;
  75337. };
  75338. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  75339. if (lodIndex === void 0) { lodIndex = -1; }
  75340. var ext = engine.getCaps().s3tc;
  75341. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75342. var fourCC, width, height, dataLength = 0, dataOffset;
  75343. var byteArray, mipmapCount, mip;
  75344. var internalFormat = 0;
  75345. var format = 0;
  75346. var blockBytes = 1;
  75347. if (header[off_magic] !== DDS_MAGIC) {
  75348. BABYLON.Tools.Error("Invalid magic number in DDS header");
  75349. return;
  75350. }
  75351. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  75352. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  75353. return;
  75354. }
  75355. if (info.isCompressed && !ext) {
  75356. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  75357. return;
  75358. }
  75359. var bpp = header[off_RGBbpp];
  75360. dataOffset = header[off_size] + 4;
  75361. var computeFormats = false;
  75362. if (info.isFourCC) {
  75363. fourCC = header[off_pfFourCC];
  75364. switch (fourCC) {
  75365. case FOURCC_DXT1:
  75366. blockBytes = 8;
  75367. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  75368. break;
  75369. case FOURCC_DXT3:
  75370. blockBytes = 16;
  75371. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  75372. break;
  75373. case FOURCC_DXT5:
  75374. blockBytes = 16;
  75375. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  75376. break;
  75377. case FOURCC_D3DFMT_R16G16B16A16F:
  75378. computeFormats = true;
  75379. break;
  75380. case FOURCC_D3DFMT_R32G32B32A32F:
  75381. computeFormats = true;
  75382. break;
  75383. case FOURCC_DX10:
  75384. // There is an additionnal header so dataOffset need to be changed
  75385. dataOffset += 5 * 4; // 5 uints
  75386. var supported = false;
  75387. switch (info.dxgiFormat) {
  75388. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  75389. computeFormats = true;
  75390. supported = true;
  75391. break;
  75392. case DXGI_FORMAT_B8G8R8X8_UNORM:
  75393. info.isRGB = true;
  75394. info.isFourCC = false;
  75395. bpp = 32;
  75396. supported = true;
  75397. break;
  75398. }
  75399. if (supported) {
  75400. break;
  75401. }
  75402. default:
  75403. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  75404. return;
  75405. }
  75406. }
  75407. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  75408. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  75409. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  75410. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  75411. if (computeFormats) {
  75412. format = engine._getWebGLTextureType(info.textureType);
  75413. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75414. }
  75415. mipmapCount = 1;
  75416. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  75417. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75418. }
  75419. for (var face = 0; face < faces; face++) {
  75420. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  75421. width = header[off_width];
  75422. height = header[off_height];
  75423. for (mip = 0; mip < mipmapCount; ++mip) {
  75424. if (lodIndex === -1 || lodIndex === mip) {
  75425. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  75426. var i = (lodIndex === -1) ? mip : 0;
  75427. if (!info.isCompressed && info.isFourCC) {
  75428. dataLength = width * height * 4;
  75429. var floatArray = null;
  75430. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  75431. if (bpp === 128) {
  75432. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75433. }
  75434. else if (bpp === 64) {
  75435. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75436. }
  75437. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75438. format = engine._getWebGLTextureType(info.textureType);
  75439. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75440. }
  75441. else {
  75442. if (bpp === 128) {
  75443. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75444. }
  75445. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  75446. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75447. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75448. format = engine._getWebGLTextureType(info.textureType);
  75449. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75450. }
  75451. else {
  75452. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75453. }
  75454. }
  75455. if (floatArray) {
  75456. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  75457. }
  75458. }
  75459. else if (info.isRGB) {
  75460. if (bpp === 24) {
  75461. dataLength = width * height * 3;
  75462. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  75463. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  75464. }
  75465. else {
  75466. dataLength = width * height * 4;
  75467. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  75468. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  75469. }
  75470. }
  75471. else if (info.isLuminance) {
  75472. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  75473. var unpaddedRowSize = width;
  75474. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  75475. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  75476. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  75477. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  75478. }
  75479. else {
  75480. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  75481. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  75482. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  75483. }
  75484. }
  75485. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  75486. width *= 0.5;
  75487. height *= 0.5;
  75488. width = Math.max(1.0, width);
  75489. height = Math.max(1.0, height);
  75490. }
  75491. if (currentFace !== undefined) {
  75492. // Loading a single face
  75493. break;
  75494. }
  75495. }
  75496. };
  75497. DDSTools.StoreLODInAlphaChannel = false;
  75498. return DDSTools;
  75499. }());
  75500. BABYLON.DDSTools = DDSTools;
  75501. })(BABYLON || (BABYLON = {}));
  75502. //# sourceMappingURL=babylon.dds.js.map
  75503. var BABYLON;
  75504. (function (BABYLON) {
  75505. /**
  75506. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  75507. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  75508. */
  75509. var KhronosTextureContainer = /** @class */ (function () {
  75510. /**
  75511. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  75512. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  75513. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  75514. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  75515. */
  75516. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  75517. this.arrayBuffer = arrayBuffer;
  75518. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  75519. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  75520. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  75521. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  75522. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  75523. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  75524. BABYLON.Tools.Error("texture missing KTX identifier");
  75525. return;
  75526. }
  75527. // load the reset of the header in native 32 bit int
  75528. var header = new Int32Array(this.arrayBuffer, 12, 13);
  75529. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  75530. var oppositeEndianess = header[0] === 0x01020304;
  75531. // read all the header elements in order they exist in the file, without modification (sans endainness)
  75532. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  75533. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  75534. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  75535. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  75536. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  75537. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  75538. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  75539. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  75540. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  75541. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  75542. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  75543. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  75544. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  75545. if (this.glType !== 0) {
  75546. BABYLON.Tools.Error("only compressed formats currently supported");
  75547. return;
  75548. }
  75549. else {
  75550. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  75551. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  75552. }
  75553. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  75554. BABYLON.Tools.Error("only 2D textures currently supported");
  75555. return;
  75556. }
  75557. if (this.numberOfArrayElements !== 0) {
  75558. BABYLON.Tools.Error("texture arrays not currently supported");
  75559. return;
  75560. }
  75561. if (this.numberOfFaces !== facesExpected) {
  75562. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  75563. return;
  75564. }
  75565. // we now have a completely validated file, so could use existence of loadType as success
  75566. // would need to make this more elaborate & adjust checks above to support more than one load type
  75567. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  75568. }
  75569. // not as fast hardware based, but will probably never need to use
  75570. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  75571. return ((val & 0xFF) << 24)
  75572. | ((val & 0xFF00) << 8)
  75573. | ((val >> 8) & 0xFF00)
  75574. | ((val >> 24) & 0xFF);
  75575. };
  75576. /**
  75577. * It is assumed that the texture has already been created & is currently bound
  75578. */
  75579. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  75580. switch (this.loadType) {
  75581. case KhronosTextureContainer.COMPRESSED_2D:
  75582. this._upload2DCompressedLevels(gl, loadMipmaps);
  75583. break;
  75584. case KhronosTextureContainer.TEX_2D:
  75585. case KhronosTextureContainer.COMPRESSED_3D:
  75586. case KhronosTextureContainer.TEX_3D:
  75587. }
  75588. };
  75589. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  75590. // initialize width & height for level 1
  75591. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  75592. var width = this.pixelWidth;
  75593. var height = this.pixelHeight;
  75594. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  75595. for (var level = 0; level < mipmapCount; level++) {
  75596. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  75597. for (var face = 0; face < this.numberOfFaces; face++) {
  75598. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  75599. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  75600. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  75601. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  75602. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  75603. }
  75604. width = Math.max(1.0, width * 0.5);
  75605. height = Math.max(1.0, height * 0.5);
  75606. }
  75607. };
  75608. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  75609. // load types
  75610. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  75611. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  75612. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  75613. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  75614. return KhronosTextureContainer;
  75615. }());
  75616. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  75617. })(BABYLON || (BABYLON = {}));
  75618. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  75619. var BABYLON;
  75620. (function (BABYLON) {
  75621. var Debug = /** @class */ (function () {
  75622. function Debug() {
  75623. }
  75624. Debug.AxesViewer = /** @class */ (function () {
  75625. function AxesViewer(scene, scaleLines) {
  75626. if (scaleLines === void 0) { scaleLines = 1; }
  75627. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75628. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75629. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75630. this.scaleLines = 1;
  75631. this.scaleLines = scaleLines;
  75632. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  75633. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  75634. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  75635. this._xmesh.renderingGroupId = 2;
  75636. this._ymesh.renderingGroupId = 2;
  75637. this._zmesh.renderingGroupId = 2;
  75638. this._xmesh.material.checkReadyOnlyOnce = true;
  75639. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  75640. this._ymesh.material.checkReadyOnlyOnce = true;
  75641. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  75642. this._zmesh.material.checkReadyOnlyOnce = true;
  75643. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  75644. this.scene = scene;
  75645. }
  75646. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  75647. var scaleLines = this.scaleLines;
  75648. if (this._xmesh) {
  75649. this._xmesh.position.copyFrom(position);
  75650. }
  75651. if (this._ymesh) {
  75652. this._ymesh.position.copyFrom(position);
  75653. }
  75654. if (this._zmesh) {
  75655. this._zmesh.position.copyFrom(position);
  75656. }
  75657. var point2 = this._xline[1];
  75658. point2.x = xaxis.x * scaleLines;
  75659. point2.y = xaxis.y * scaleLines;
  75660. point2.z = xaxis.z * scaleLines;
  75661. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  75662. point2 = this._yline[1];
  75663. point2.x = yaxis.x * scaleLines;
  75664. point2.y = yaxis.y * scaleLines;
  75665. point2.z = yaxis.z * scaleLines;
  75666. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  75667. point2 = this._zline[1];
  75668. point2.x = zaxis.x * scaleLines;
  75669. point2.y = zaxis.y * scaleLines;
  75670. point2.z = zaxis.z * scaleLines;
  75671. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  75672. };
  75673. AxesViewer.prototype.dispose = function () {
  75674. if (this._xmesh) {
  75675. this._xmesh.dispose();
  75676. }
  75677. if (this._ymesh) {
  75678. this._ymesh.dispose();
  75679. }
  75680. if (this._zmesh) {
  75681. this._zmesh.dispose();
  75682. }
  75683. this._xmesh = null;
  75684. this._ymesh = null;
  75685. this._zmesh = null;
  75686. this.scene = null;
  75687. };
  75688. return AxesViewer;
  75689. }());
  75690. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  75691. __extends(BoneAxesViewer, _super);
  75692. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  75693. if (scaleLines === void 0) { scaleLines = 1; }
  75694. var _this = _super.call(this, scene, scaleLines) || this;
  75695. _this.pos = BABYLON.Vector3.Zero();
  75696. _this.xaxis = BABYLON.Vector3.Zero();
  75697. _this.yaxis = BABYLON.Vector3.Zero();
  75698. _this.zaxis = BABYLON.Vector3.Zero();
  75699. _this.mesh = mesh;
  75700. _this.bone = bone;
  75701. return _this;
  75702. }
  75703. BoneAxesViewer.prototype.update = function () {
  75704. if (!this.mesh || !this.bone) {
  75705. return;
  75706. }
  75707. var bone = this.bone;
  75708. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  75709. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  75710. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  75711. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  75712. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  75713. };
  75714. BoneAxesViewer.prototype.dispose = function () {
  75715. if (this.mesh) {
  75716. this.mesh = null;
  75717. this.bone = null;
  75718. _super.prototype.dispose.call(this);
  75719. }
  75720. };
  75721. return BoneAxesViewer;
  75722. }(Debug.AxesViewer));
  75723. Debug.PhysicsViewer = /** @class */ (function () {
  75724. function PhysicsViewer(scene) {
  75725. this._impostors = [];
  75726. this._meshes = [];
  75727. this._numMeshes = 0;
  75728. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75729. var physicEngine = this._scene.getPhysicsEngine();
  75730. if (physicEngine) {
  75731. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  75732. }
  75733. }
  75734. PhysicsViewer.prototype._updateDebugMeshes = function () {
  75735. var plugin = this._physicsEnginePlugin;
  75736. for (var i = 0; i < this._numMeshes; i++) {
  75737. var impostor = this._impostors[i];
  75738. if (!impostor) {
  75739. continue;
  75740. }
  75741. if (impostor.isDisposed) {
  75742. this.hideImpostor(this._impostors[i--]);
  75743. }
  75744. else {
  75745. var mesh = this._meshes[i];
  75746. if (mesh && plugin) {
  75747. plugin.syncMeshWithImpostor(mesh, impostor);
  75748. }
  75749. }
  75750. }
  75751. };
  75752. PhysicsViewer.prototype.showImpostor = function (impostor) {
  75753. if (!this._scene) {
  75754. return;
  75755. }
  75756. for (var i = 0; i < this._numMeshes; i++) {
  75757. if (this._impostors[i] == impostor) {
  75758. return;
  75759. }
  75760. }
  75761. var debugMesh = this._getDebugMesh(impostor, this._scene);
  75762. if (debugMesh) {
  75763. this._impostors[this._numMeshes] = impostor;
  75764. this._meshes[this._numMeshes] = debugMesh;
  75765. if (this._numMeshes === 0) {
  75766. this._renderFunction = this._updateDebugMeshes.bind(this);
  75767. this._scene.registerBeforeRender(this._renderFunction);
  75768. }
  75769. this._numMeshes++;
  75770. }
  75771. };
  75772. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  75773. if (!impostor || !this._scene) {
  75774. return;
  75775. }
  75776. var removed = false;
  75777. for (var i = 0; i < this._numMeshes; i++) {
  75778. if (this._impostors[i] == impostor) {
  75779. var mesh = this._meshes[i];
  75780. if (!mesh) {
  75781. continue;
  75782. }
  75783. this._scene.removeMesh(mesh);
  75784. mesh.dispose();
  75785. this._numMeshes--;
  75786. if (this._numMeshes > 0) {
  75787. this._meshes[i] = this._meshes[this._numMeshes];
  75788. this._impostors[i] = this._impostors[this._numMeshes];
  75789. this._meshes[this._numMeshes] = null;
  75790. this._impostors[this._numMeshes] = null;
  75791. }
  75792. else {
  75793. this._meshes[0] = null;
  75794. this._impostors[0] = null;
  75795. }
  75796. removed = true;
  75797. break;
  75798. }
  75799. }
  75800. if (removed && this._numMeshes === 0) {
  75801. this._scene.unregisterBeforeRender(this._renderFunction);
  75802. }
  75803. };
  75804. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  75805. if (!this._debugMaterial) {
  75806. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  75807. this._debugMaterial.wireframe = true;
  75808. }
  75809. return this._debugMaterial;
  75810. };
  75811. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  75812. if (!this._debugBoxMesh) {
  75813. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  75814. this._debugBoxMesh.renderingGroupId = 1;
  75815. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  75816. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  75817. scene.removeMesh(this._debugBoxMesh);
  75818. }
  75819. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  75820. };
  75821. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  75822. if (!this._debugSphereMesh) {
  75823. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  75824. this._debugSphereMesh.renderingGroupId = 1;
  75825. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  75826. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  75827. scene.removeMesh(this._debugSphereMesh);
  75828. }
  75829. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  75830. };
  75831. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  75832. var mesh = null;
  75833. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  75834. mesh = this._getDebugBoxMesh(scene);
  75835. impostor.getBoxSizeToRef(mesh.scaling);
  75836. }
  75837. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  75838. mesh = this._getDebugSphereMesh(scene);
  75839. var radius = impostor.getRadius();
  75840. mesh.scaling.x = radius * 2;
  75841. mesh.scaling.y = radius * 2;
  75842. mesh.scaling.z = radius * 2;
  75843. }
  75844. return mesh;
  75845. };
  75846. PhysicsViewer.prototype.dispose = function () {
  75847. for (var i = 0; i < this._numMeshes; i++) {
  75848. this.hideImpostor(this._impostors[i]);
  75849. }
  75850. if (this._debugBoxMesh) {
  75851. this._debugBoxMesh.dispose();
  75852. }
  75853. if (this._debugSphereMesh) {
  75854. this._debugSphereMesh.dispose();
  75855. }
  75856. if (this._debugMaterial) {
  75857. this._debugMaterial.dispose();
  75858. }
  75859. this._impostors.length = 0;
  75860. this._scene = null;
  75861. this._physicsEnginePlugin = null;
  75862. };
  75863. return PhysicsViewer;
  75864. }());
  75865. Debug.SkeletonViewer = /** @class */ (function () {
  75866. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  75867. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  75868. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  75869. this.skeleton = skeleton;
  75870. this.mesh = mesh;
  75871. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  75872. this.renderingGroupId = renderingGroupId;
  75873. this.color = BABYLON.Color3.White();
  75874. this._debugLines = new Array();
  75875. this._isEnabled = false;
  75876. this._scene = scene;
  75877. this.update();
  75878. this._renderFunction = this.update.bind(this);
  75879. }
  75880. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  75881. get: function () {
  75882. return this._isEnabled;
  75883. },
  75884. set: function (value) {
  75885. if (this._isEnabled === value) {
  75886. return;
  75887. }
  75888. this._isEnabled = value;
  75889. if (value) {
  75890. this._scene.registerBeforeRender(this._renderFunction);
  75891. }
  75892. else {
  75893. this._scene.unregisterBeforeRender(this._renderFunction);
  75894. }
  75895. },
  75896. enumerable: true,
  75897. configurable: true
  75898. });
  75899. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  75900. if (x === void 0) { x = 0; }
  75901. if (y === void 0) { y = 0; }
  75902. if (z === void 0) { z = 0; }
  75903. var tmat = BABYLON.Tmp.Matrix[0];
  75904. var parentBone = bone.getParent();
  75905. tmat.copyFrom(bone.getLocalMatrix());
  75906. if (x !== 0 || y !== 0 || z !== 0) {
  75907. var tmat2 = BABYLON.Tmp.Matrix[1];
  75908. BABYLON.Matrix.IdentityToRef(tmat2);
  75909. tmat2.m[12] = x;
  75910. tmat2.m[13] = y;
  75911. tmat2.m[14] = z;
  75912. tmat2.multiplyToRef(tmat, tmat);
  75913. }
  75914. if (parentBone) {
  75915. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  75916. }
  75917. tmat.multiplyToRef(meshMat, tmat);
  75918. position.x = tmat.m[12];
  75919. position.y = tmat.m[13];
  75920. position.z = tmat.m[14];
  75921. };
  75922. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  75923. var len = bones.length;
  75924. var meshPos = this.mesh.position;
  75925. for (var i = 0; i < len; i++) {
  75926. var bone = bones[i];
  75927. var points = this._debugLines[i];
  75928. if (!points) {
  75929. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75930. this._debugLines[i] = points;
  75931. }
  75932. this._getBonePosition(points[0], bone, meshMat);
  75933. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  75934. points[0].subtractInPlace(meshPos);
  75935. points[1].subtractInPlace(meshPos);
  75936. }
  75937. };
  75938. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  75939. var len = bones.length;
  75940. var boneNum = 0;
  75941. var meshPos = this.mesh.position;
  75942. for (var i = len - 1; i >= 0; i--) {
  75943. var childBone = bones[i];
  75944. var parentBone = childBone.getParent();
  75945. if (!parentBone) {
  75946. continue;
  75947. }
  75948. var points = this._debugLines[boneNum];
  75949. if (!points) {
  75950. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75951. this._debugLines[boneNum] = points;
  75952. }
  75953. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  75954. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  75955. points[0].subtractInPlace(meshPos);
  75956. points[1].subtractInPlace(meshPos);
  75957. boneNum++;
  75958. }
  75959. };
  75960. SkeletonViewer.prototype.update = function () {
  75961. if (this.autoUpdateBonesMatrices) {
  75962. this.skeleton.computeAbsoluteTransforms();
  75963. }
  75964. if (this.skeleton.bones[0].length === undefined) {
  75965. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  75966. }
  75967. else {
  75968. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  75969. }
  75970. if (!this._debugMesh) {
  75971. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  75972. this._debugMesh.renderingGroupId = this.renderingGroupId;
  75973. }
  75974. else {
  75975. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  75976. }
  75977. this._debugMesh.position.copyFrom(this.mesh.position);
  75978. this._debugMesh.color = this.color;
  75979. };
  75980. SkeletonViewer.prototype.dispose = function () {
  75981. if (this._debugMesh) {
  75982. this.isEnabled = false;
  75983. this._debugMesh.dispose();
  75984. this._debugMesh = null;
  75985. }
  75986. };
  75987. return SkeletonViewer;
  75988. }());
  75989. return Debug;
  75990. }());
  75991. BABYLON.Debug = Debug;
  75992. })(BABYLON || (BABYLON = {}));
  75993. //# sourceMappingURL=babylon.debugModules.js.map
  75994. var BABYLON;
  75995. (function (BABYLON) {
  75996. var RayHelper = /** @class */ (function () {
  75997. function RayHelper(ray) {
  75998. this.ray = ray;
  75999. }
  76000. RayHelper.CreateAndShow = function (ray, scene, color) {
  76001. var helper = new RayHelper(ray);
  76002. helper.show(scene, color);
  76003. return helper;
  76004. };
  76005. RayHelper.prototype.show = function (scene, color) {
  76006. if (!this._renderFunction && this.ray) {
  76007. var ray = this.ray;
  76008. this._renderFunction = this._render.bind(this);
  76009. this._scene = scene;
  76010. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76011. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76012. if (this._renderFunction) {
  76013. this._scene.registerBeforeRender(this._renderFunction);
  76014. }
  76015. }
  76016. if (color && this._renderLine) {
  76017. this._renderLine.color.copyFrom(color);
  76018. }
  76019. };
  76020. RayHelper.prototype.hide = function () {
  76021. if (this._renderFunction && this._scene) {
  76022. this._scene.unregisterBeforeRender(this._renderFunction);
  76023. this._scene = null;
  76024. this._renderFunction = null;
  76025. if (this._renderLine) {
  76026. this._renderLine.dispose();
  76027. this._renderLine = null;
  76028. }
  76029. this._renderPoints = [];
  76030. }
  76031. };
  76032. RayHelper.prototype._render = function () {
  76033. var ray = this.ray;
  76034. if (!ray) {
  76035. return;
  76036. }
  76037. var point = this._renderPoints[1];
  76038. var len = Math.min(ray.length, 1000000);
  76039. point.copyFrom(ray.direction);
  76040. point.scaleInPlace(len);
  76041. point.addInPlace(ray.origin);
  76042. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76043. };
  76044. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76045. this._attachedToMesh = mesh;
  76046. var ray = this.ray;
  76047. if (!ray) {
  76048. return;
  76049. }
  76050. if (!ray.direction) {
  76051. ray.direction = BABYLON.Vector3.Zero();
  76052. }
  76053. if (!ray.origin) {
  76054. ray.origin = BABYLON.Vector3.Zero();
  76055. }
  76056. if (length) {
  76057. ray.length = length;
  76058. }
  76059. if (!meshSpaceOrigin) {
  76060. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76061. }
  76062. if (!meshSpaceDirection) {
  76063. // -1 so that this will work with Mesh.lookAt
  76064. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76065. }
  76066. if (!this._meshSpaceDirection) {
  76067. this._meshSpaceDirection = meshSpaceDirection.clone();
  76068. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76069. }
  76070. else {
  76071. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76072. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76073. }
  76074. if (!this._updateToMeshFunction) {
  76075. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76076. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76077. }
  76078. this._updateToMesh();
  76079. };
  76080. RayHelper.prototype.detachFromMesh = function () {
  76081. if (this._attachedToMesh) {
  76082. if (this._updateToMeshFunction) {
  76083. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76084. }
  76085. this._attachedToMesh = null;
  76086. this._updateToMeshFunction = null;
  76087. }
  76088. };
  76089. RayHelper.prototype._updateToMesh = function () {
  76090. var ray = this.ray;
  76091. if (!this._attachedToMesh || !ray) {
  76092. return;
  76093. }
  76094. if (this._attachedToMesh._isDisposed) {
  76095. this.detachFromMesh();
  76096. return;
  76097. }
  76098. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76099. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76100. };
  76101. RayHelper.prototype.dispose = function () {
  76102. this.hide();
  76103. this.detachFromMesh();
  76104. this.ray = null;
  76105. };
  76106. return RayHelper;
  76107. }());
  76108. BABYLON.RayHelper = RayHelper;
  76109. })(BABYLON || (BABYLON = {}));
  76110. //# sourceMappingURL=babylon.rayHelper.js.map
  76111. var BABYLON;
  76112. (function (BABYLON) {
  76113. // load the inspector using require, if not present in the global namespace.
  76114. var DebugLayer = /** @class */ (function () {
  76115. function DebugLayer(scene) {
  76116. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76117. this._scene = scene;
  76118. // load inspector using require, if it doesn't exist on the global namespace.
  76119. }
  76120. /** Creates the inspector window. */
  76121. DebugLayer.prototype._createInspector = function (config) {
  76122. if (config === void 0) { config = {}; }
  76123. var popup = config.popup || false;
  76124. var initialTab = config.initialTab || 0;
  76125. var parentElement = config.parentElement || null;
  76126. if (!this._inspector) {
  76127. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76128. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76129. } // else nothing to do,; instance is already existing
  76130. };
  76131. DebugLayer.prototype.isVisible = function () {
  76132. if (!this._inspector) {
  76133. return false;
  76134. }
  76135. return true;
  76136. };
  76137. DebugLayer.prototype.hide = function () {
  76138. if (this._inspector) {
  76139. try {
  76140. this._inspector.dispose();
  76141. }
  76142. catch (e) {
  76143. // If the inspector has been removed directly from the inspector tool
  76144. }
  76145. this._inspector = null;
  76146. }
  76147. };
  76148. DebugLayer.prototype.show = function (config) {
  76149. if (config === void 0) { config = {}; }
  76150. if (typeof this.BJSINSPECTOR == 'undefined') {
  76151. // Load inspector and add it to the DOM
  76152. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76153. }
  76154. else {
  76155. // Otherwise creates the inspector
  76156. this._createInspector(config);
  76157. }
  76158. };
  76159. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76160. return DebugLayer;
  76161. }());
  76162. BABYLON.DebugLayer = DebugLayer;
  76163. })(BABYLON || (BABYLON = {}));
  76164. //# sourceMappingURL=babylon.debugLayer.js.map
  76165. var BABYLON;
  76166. (function (BABYLON) {
  76167. var BoundingBoxRenderer = /** @class */ (function () {
  76168. function BoundingBoxRenderer(scene) {
  76169. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76170. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76171. this.showBackLines = true;
  76172. this.renderList = new BABYLON.SmartArray(32);
  76173. this._vertexBuffers = {};
  76174. this._scene = scene;
  76175. }
  76176. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76177. if (this._colorShader) {
  76178. return;
  76179. }
  76180. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76181. attributes: [BABYLON.VertexBuffer.PositionKind],
  76182. uniforms: ["world", "viewProjection", "color"]
  76183. });
  76184. var engine = this._scene.getEngine();
  76185. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76186. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76187. this._createIndexBuffer();
  76188. };
  76189. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76190. var engine = this._scene.getEngine();
  76191. 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]);
  76192. };
  76193. BoundingBoxRenderer.prototype._rebuild = function () {
  76194. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76195. if (vb) {
  76196. vb._rebuild();
  76197. }
  76198. this._createIndexBuffer();
  76199. };
  76200. BoundingBoxRenderer.prototype.reset = function () {
  76201. this.renderList.reset();
  76202. };
  76203. BoundingBoxRenderer.prototype.render = function () {
  76204. if (this.renderList.length === 0) {
  76205. return;
  76206. }
  76207. this._prepareRessources();
  76208. if (!this._colorShader.isReady()) {
  76209. return;
  76210. }
  76211. var engine = this._scene.getEngine();
  76212. engine.setDepthWrite(false);
  76213. this._colorShader._preBind();
  76214. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76215. var boundingBox = this.renderList.data[boundingBoxIndex];
  76216. var min = boundingBox.minimum;
  76217. var max = boundingBox.maximum;
  76218. var diff = max.subtract(min);
  76219. var median = min.add(diff.scale(0.5));
  76220. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76221. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76222. .multiply(boundingBox.getWorldMatrix());
  76223. // VBOs
  76224. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76225. if (this.showBackLines) {
  76226. // Back
  76227. engine.setDepthFunctionToGreaterOrEqual();
  76228. this._scene.resetCachedMaterial();
  76229. this._colorShader.setColor4("color", this.backColor.toColor4());
  76230. this._colorShader.bind(worldMatrix);
  76231. // Draw order
  76232. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76233. }
  76234. // Front
  76235. engine.setDepthFunctionToLess();
  76236. this._scene.resetCachedMaterial();
  76237. this._colorShader.setColor4("color", this.frontColor.toColor4());
  76238. this._colorShader.bind(worldMatrix);
  76239. // Draw order
  76240. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76241. }
  76242. this._colorShader.unbind();
  76243. engine.setDepthFunctionToLessOrEqual();
  76244. engine.setDepthWrite(true);
  76245. };
  76246. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  76247. this._prepareRessources();
  76248. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  76249. return;
  76250. }
  76251. var engine = this._scene.getEngine();
  76252. engine.setDepthWrite(false);
  76253. engine.setColorWrite(false);
  76254. this._colorShader._preBind();
  76255. var boundingBox = mesh._boundingInfo.boundingBox;
  76256. var min = boundingBox.minimum;
  76257. var max = boundingBox.maximum;
  76258. var diff = max.subtract(min);
  76259. var median = min.add(diff.scale(0.5));
  76260. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76261. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76262. .multiply(boundingBox.getWorldMatrix());
  76263. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76264. engine.setDepthFunctionToLess();
  76265. this._scene.resetCachedMaterial();
  76266. this._colorShader.bind(worldMatrix);
  76267. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76268. this._colorShader.unbind();
  76269. engine.setDepthFunctionToLessOrEqual();
  76270. engine.setDepthWrite(true);
  76271. engine.setColorWrite(true);
  76272. };
  76273. BoundingBoxRenderer.prototype.dispose = function () {
  76274. if (!this._colorShader) {
  76275. return;
  76276. }
  76277. this.renderList.dispose();
  76278. this._colorShader.dispose();
  76279. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76280. if (buffer) {
  76281. buffer.dispose();
  76282. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76283. }
  76284. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76285. };
  76286. return BoundingBoxRenderer;
  76287. }());
  76288. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  76289. })(BABYLON || (BABYLON = {}));
  76290. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  76291. var BABYLON;
  76292. (function (BABYLON) {
  76293. var MorphTarget = /** @class */ (function () {
  76294. function MorphTarget(name, influence) {
  76295. if (influence === void 0) { influence = 0; }
  76296. this.name = name;
  76297. this.animations = new Array();
  76298. this._positions = null;
  76299. this._normals = null;
  76300. this._tangents = null;
  76301. this.onInfluenceChanged = new BABYLON.Observable();
  76302. this.influence = influence;
  76303. }
  76304. Object.defineProperty(MorphTarget.prototype, "influence", {
  76305. get: function () {
  76306. return this._influence;
  76307. },
  76308. set: function (influence) {
  76309. if (this._influence === influence) {
  76310. return;
  76311. }
  76312. var previous = this._influence;
  76313. this._influence = influence;
  76314. if (this.onInfluenceChanged.hasObservers) {
  76315. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  76316. }
  76317. },
  76318. enumerable: true,
  76319. configurable: true
  76320. });
  76321. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  76322. get: function () {
  76323. return !!this._positions;
  76324. },
  76325. enumerable: true,
  76326. configurable: true
  76327. });
  76328. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  76329. get: function () {
  76330. return !!this._normals;
  76331. },
  76332. enumerable: true,
  76333. configurable: true
  76334. });
  76335. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  76336. get: function () {
  76337. return !!this._tangents;
  76338. },
  76339. enumerable: true,
  76340. configurable: true
  76341. });
  76342. MorphTarget.prototype.setPositions = function (data) {
  76343. this._positions = data;
  76344. };
  76345. MorphTarget.prototype.getPositions = function () {
  76346. return this._positions;
  76347. };
  76348. MorphTarget.prototype.setNormals = function (data) {
  76349. this._normals = data;
  76350. };
  76351. MorphTarget.prototype.getNormals = function () {
  76352. return this._normals;
  76353. };
  76354. MorphTarget.prototype.setTangents = function (data) {
  76355. this._tangents = data;
  76356. };
  76357. MorphTarget.prototype.getTangents = function () {
  76358. return this._tangents;
  76359. };
  76360. /**
  76361. * Serializes the current target into a Serialization object.
  76362. * Returns the serialized object.
  76363. */
  76364. MorphTarget.prototype.serialize = function () {
  76365. var serializationObject = {};
  76366. serializationObject.name = this.name;
  76367. serializationObject.influence = this.influence;
  76368. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  76369. if (this.hasNormals) {
  76370. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  76371. }
  76372. if (this.hasTangents) {
  76373. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  76374. }
  76375. // Animations
  76376. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  76377. return serializationObject;
  76378. };
  76379. // Statics
  76380. MorphTarget.Parse = function (serializationObject) {
  76381. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  76382. result.setPositions(serializationObject.positions);
  76383. if (serializationObject.normals) {
  76384. result.setNormals(serializationObject.normals);
  76385. }
  76386. if (serializationObject.tangents) {
  76387. result.setTangents(serializationObject.tangents);
  76388. }
  76389. // Animations
  76390. if (serializationObject.animations) {
  76391. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  76392. var parsedAnimation = serializationObject.animations[animationIndex];
  76393. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  76394. }
  76395. }
  76396. return result;
  76397. };
  76398. MorphTarget.FromMesh = function (mesh, name, influence) {
  76399. if (!name) {
  76400. name = mesh.name;
  76401. }
  76402. var result = new MorphTarget(name, influence);
  76403. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76404. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76405. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  76406. }
  76407. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  76408. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  76409. }
  76410. return result;
  76411. };
  76412. return MorphTarget;
  76413. }());
  76414. BABYLON.MorphTarget = MorphTarget;
  76415. })(BABYLON || (BABYLON = {}));
  76416. //# sourceMappingURL=babylon.morphTarget.js.map
  76417. var BABYLON;
  76418. (function (BABYLON) {
  76419. var MorphTargetManager = /** @class */ (function () {
  76420. function MorphTargetManager(scene) {
  76421. if (scene === void 0) { scene = null; }
  76422. this._targets = new Array();
  76423. this._targetObservable = new Array();
  76424. this._activeTargets = new BABYLON.SmartArray(16);
  76425. this._supportsNormals = false;
  76426. this._supportsTangents = false;
  76427. this._vertexCount = 0;
  76428. this._uniqueId = 0;
  76429. this._tempInfluences = new Array();
  76430. if (!scene) {
  76431. scene = BABYLON.Engine.LastCreatedScene;
  76432. }
  76433. this._scene = scene;
  76434. if (this._scene) {
  76435. this._scene.morphTargetManagers.push(this);
  76436. this._uniqueId = this._scene.getUniqueId();
  76437. }
  76438. }
  76439. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  76440. get: function () {
  76441. return this._uniqueId;
  76442. },
  76443. enumerable: true,
  76444. configurable: true
  76445. });
  76446. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  76447. get: function () {
  76448. return this._vertexCount;
  76449. },
  76450. enumerable: true,
  76451. configurable: true
  76452. });
  76453. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  76454. get: function () {
  76455. return this._supportsNormals;
  76456. },
  76457. enumerable: true,
  76458. configurable: true
  76459. });
  76460. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  76461. get: function () {
  76462. return this._supportsTangents;
  76463. },
  76464. enumerable: true,
  76465. configurable: true
  76466. });
  76467. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  76468. get: function () {
  76469. return this._targets.length;
  76470. },
  76471. enumerable: true,
  76472. configurable: true
  76473. });
  76474. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  76475. get: function () {
  76476. return this._activeTargets.length;
  76477. },
  76478. enumerable: true,
  76479. configurable: true
  76480. });
  76481. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  76482. get: function () {
  76483. return this._influences;
  76484. },
  76485. enumerable: true,
  76486. configurable: true
  76487. });
  76488. MorphTargetManager.prototype.getActiveTarget = function (index) {
  76489. return this._activeTargets.data[index];
  76490. };
  76491. MorphTargetManager.prototype.getTarget = function (index) {
  76492. return this._targets[index];
  76493. };
  76494. MorphTargetManager.prototype.addTarget = function (target) {
  76495. var _this = this;
  76496. this._targets.push(target);
  76497. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  76498. _this._syncActiveTargets(needUpdate);
  76499. }));
  76500. this._syncActiveTargets(true);
  76501. };
  76502. MorphTargetManager.prototype.removeTarget = function (target) {
  76503. var index = this._targets.indexOf(target);
  76504. if (index >= 0) {
  76505. this._targets.splice(index, 1);
  76506. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  76507. this._syncActiveTargets(true);
  76508. }
  76509. };
  76510. /**
  76511. * Serializes the current manager into a Serialization object.
  76512. * Returns the serialized object.
  76513. */
  76514. MorphTargetManager.prototype.serialize = function () {
  76515. var serializationObject = {};
  76516. serializationObject.id = this.uniqueId;
  76517. serializationObject.targets = [];
  76518. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  76519. var target = _a[_i];
  76520. serializationObject.targets.push(target.serialize());
  76521. }
  76522. return serializationObject;
  76523. };
  76524. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  76525. var influenceCount = 0;
  76526. this._activeTargets.reset();
  76527. this._supportsNormals = true;
  76528. this._supportsTangents = true;
  76529. this._vertexCount = 0;
  76530. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  76531. var target = _a[_i];
  76532. this._activeTargets.push(target);
  76533. this._tempInfluences[influenceCount++] = target.influence;
  76534. var positions = target.getPositions();
  76535. if (positions) {
  76536. this._supportsNormals = this._supportsNormals && target.hasNormals;
  76537. this._supportsTangents = this._supportsTangents && target.hasTangents;
  76538. var vertexCount = positions.length / 3;
  76539. if (this._vertexCount === 0) {
  76540. this._vertexCount = vertexCount;
  76541. }
  76542. else if (this._vertexCount !== vertexCount) {
  76543. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  76544. return;
  76545. }
  76546. }
  76547. }
  76548. if (!this._influences || this._influences.length !== influenceCount) {
  76549. this._influences = new Float32Array(influenceCount);
  76550. }
  76551. for (var index = 0; index < influenceCount; index++) {
  76552. this._influences[index] = this._tempInfluences[index];
  76553. }
  76554. if (needUpdate && this._scene) {
  76555. // Flag meshes as dirty to resync with the active targets
  76556. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  76557. var mesh = _c[_b];
  76558. if (mesh.morphTargetManager === this) {
  76559. mesh._syncGeometryWithMorphTargetManager();
  76560. }
  76561. }
  76562. }
  76563. };
  76564. // Statics
  76565. MorphTargetManager.Parse = function (serializationObject, scene) {
  76566. var result = new MorphTargetManager(scene);
  76567. result._uniqueId = serializationObject.id;
  76568. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  76569. var targetData = _a[_i];
  76570. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  76571. }
  76572. return result;
  76573. };
  76574. return MorphTargetManager;
  76575. }());
  76576. BABYLON.MorphTargetManager = MorphTargetManager;
  76577. })(BABYLON || (BABYLON = {}));
  76578. //# sourceMappingURL=babylon.morphTargetManager.js.map
  76579. var BABYLON;
  76580. (function (BABYLON) {
  76581. var Octree = /** @class */ (function () {
  76582. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  76583. if (maxDepth === void 0) { maxDepth = 2; }
  76584. this.maxDepth = maxDepth;
  76585. this.dynamicContent = new Array();
  76586. this._maxBlockCapacity = maxBlockCapacity || 64;
  76587. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  76588. this._creationFunc = creationFunc;
  76589. }
  76590. // Methods
  76591. Octree.prototype.update = function (worldMin, worldMax, entries) {
  76592. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  76593. };
  76594. Octree.prototype.addMesh = function (entry) {
  76595. for (var index = 0; index < this.blocks.length; index++) {
  76596. var block = this.blocks[index];
  76597. block.addEntry(entry);
  76598. }
  76599. };
  76600. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  76601. this._selectionContent.reset();
  76602. for (var index = 0; index < this.blocks.length; index++) {
  76603. var block = this.blocks[index];
  76604. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  76605. }
  76606. if (allowDuplicate) {
  76607. this._selectionContent.concat(this.dynamicContent);
  76608. }
  76609. else {
  76610. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  76611. }
  76612. return this._selectionContent;
  76613. };
  76614. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  76615. this._selectionContent.reset();
  76616. for (var index = 0; index < this.blocks.length; index++) {
  76617. var block = this.blocks[index];
  76618. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  76619. }
  76620. if (allowDuplicate) {
  76621. this._selectionContent.concat(this.dynamicContent);
  76622. }
  76623. else {
  76624. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  76625. }
  76626. return this._selectionContent;
  76627. };
  76628. Octree.prototype.intersectsRay = function (ray) {
  76629. this._selectionContent.reset();
  76630. for (var index = 0; index < this.blocks.length; index++) {
  76631. var block = this.blocks[index];
  76632. block.intersectsRay(ray, this._selectionContent);
  76633. }
  76634. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  76635. return this._selectionContent;
  76636. };
  76637. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  76638. target.blocks = new Array();
  76639. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  76640. // Segmenting space
  76641. for (var x = 0; x < 2; x++) {
  76642. for (var y = 0; y < 2; y++) {
  76643. for (var z = 0; z < 2; z++) {
  76644. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  76645. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  76646. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  76647. block.addEntries(entries);
  76648. target.blocks.push(block);
  76649. }
  76650. }
  76651. }
  76652. };
  76653. Octree.CreationFuncForMeshes = function (entry, block) {
  76654. var boundingInfo = entry.getBoundingInfo();
  76655. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  76656. block.entries.push(entry);
  76657. }
  76658. };
  76659. Octree.CreationFuncForSubMeshes = function (entry, block) {
  76660. var boundingInfo = entry.getBoundingInfo();
  76661. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  76662. block.entries.push(entry);
  76663. }
  76664. };
  76665. return Octree;
  76666. }());
  76667. BABYLON.Octree = Octree;
  76668. })(BABYLON || (BABYLON = {}));
  76669. //# sourceMappingURL=babylon.octree.js.map
  76670. var BABYLON;
  76671. (function (BABYLON) {
  76672. var OctreeBlock = /** @class */ (function () {
  76673. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  76674. this.entries = new Array();
  76675. this._boundingVectors = new Array();
  76676. this._capacity = capacity;
  76677. this._depth = depth;
  76678. this._maxDepth = maxDepth;
  76679. this._creationFunc = creationFunc;
  76680. this._minPoint = minPoint;
  76681. this._maxPoint = maxPoint;
  76682. this._boundingVectors.push(minPoint.clone());
  76683. this._boundingVectors.push(maxPoint.clone());
  76684. this._boundingVectors.push(minPoint.clone());
  76685. this._boundingVectors[2].x = maxPoint.x;
  76686. this._boundingVectors.push(minPoint.clone());
  76687. this._boundingVectors[3].y = maxPoint.y;
  76688. this._boundingVectors.push(minPoint.clone());
  76689. this._boundingVectors[4].z = maxPoint.z;
  76690. this._boundingVectors.push(maxPoint.clone());
  76691. this._boundingVectors[5].z = minPoint.z;
  76692. this._boundingVectors.push(maxPoint.clone());
  76693. this._boundingVectors[6].x = minPoint.x;
  76694. this._boundingVectors.push(maxPoint.clone());
  76695. this._boundingVectors[7].y = minPoint.y;
  76696. }
  76697. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  76698. // Property
  76699. get: function () {
  76700. return this._capacity;
  76701. },
  76702. enumerable: true,
  76703. configurable: true
  76704. });
  76705. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  76706. get: function () {
  76707. return this._minPoint;
  76708. },
  76709. enumerable: true,
  76710. configurable: true
  76711. });
  76712. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  76713. get: function () {
  76714. return this._maxPoint;
  76715. },
  76716. enumerable: true,
  76717. configurable: true
  76718. });
  76719. // Methods
  76720. OctreeBlock.prototype.addEntry = function (entry) {
  76721. if (this.blocks) {
  76722. for (var index = 0; index < this.blocks.length; index++) {
  76723. var block = this.blocks[index];
  76724. block.addEntry(entry);
  76725. }
  76726. return;
  76727. }
  76728. this._creationFunc(entry, this);
  76729. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  76730. this.createInnerBlocks();
  76731. }
  76732. };
  76733. OctreeBlock.prototype.addEntries = function (entries) {
  76734. for (var index = 0; index < entries.length; index++) {
  76735. var mesh = entries[index];
  76736. this.addEntry(mesh);
  76737. }
  76738. };
  76739. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  76740. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  76741. if (this.blocks) {
  76742. for (var index = 0; index < this.blocks.length; index++) {
  76743. var block = this.blocks[index];
  76744. block.select(frustumPlanes, selection, allowDuplicate);
  76745. }
  76746. return;
  76747. }
  76748. if (allowDuplicate) {
  76749. selection.concat(this.entries);
  76750. }
  76751. else {
  76752. selection.concatWithNoDuplicate(this.entries);
  76753. }
  76754. }
  76755. };
  76756. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  76757. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  76758. if (this.blocks) {
  76759. for (var index = 0; index < this.blocks.length; index++) {
  76760. var block = this.blocks[index];
  76761. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  76762. }
  76763. return;
  76764. }
  76765. if (allowDuplicate) {
  76766. selection.concat(this.entries);
  76767. }
  76768. else {
  76769. selection.concatWithNoDuplicate(this.entries);
  76770. }
  76771. }
  76772. };
  76773. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  76774. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  76775. if (this.blocks) {
  76776. for (var index = 0; index < this.blocks.length; index++) {
  76777. var block = this.blocks[index];
  76778. block.intersectsRay(ray, selection);
  76779. }
  76780. return;
  76781. }
  76782. selection.concatWithNoDuplicate(this.entries);
  76783. }
  76784. };
  76785. OctreeBlock.prototype.createInnerBlocks = function () {
  76786. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  76787. };
  76788. return OctreeBlock;
  76789. }());
  76790. BABYLON.OctreeBlock = OctreeBlock;
  76791. })(BABYLON || (BABYLON = {}));
  76792. //# sourceMappingURL=babylon.octreeBlock.js.map
  76793. var BABYLON;
  76794. (function (BABYLON) {
  76795. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  76796. __extends(VRDistortionCorrectionPostProcess, _super);
  76797. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  76798. var _this = _super.call(this, name, "vrDistortionCorrection", [
  76799. 'LensCenter',
  76800. 'Scale',
  76801. 'ScaleIn',
  76802. 'HmdWarpParam'
  76803. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  76804. _this._isRightEye = isRightEye;
  76805. _this._distortionFactors = vrMetrics.distortionK;
  76806. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  76807. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  76808. _this.adaptScaleToCurrentViewport = true;
  76809. _this.onSizeChangedObservable.add(function () {
  76810. _this.aspectRatio = _this.width * .5 / _this.height;
  76811. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  76812. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  76813. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  76814. });
  76815. _this.onApplyObservable.add(function (effect) {
  76816. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  76817. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  76818. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  76819. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  76820. });
  76821. return _this;
  76822. }
  76823. return VRDistortionCorrectionPostProcess;
  76824. }(BABYLON.PostProcess));
  76825. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  76826. })(BABYLON || (BABYLON = {}));
  76827. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  76828. var BABYLON;
  76829. (function (BABYLON) {
  76830. var AnaglyphPostProcess = /** @class */ (function (_super) {
  76831. __extends(AnaglyphPostProcess, _super);
  76832. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  76833. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  76834. _this._passedProcess = rigCameras[0]._rigPostProcess;
  76835. _this.onApplyObservable.add(function (effect) {
  76836. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  76837. });
  76838. return _this;
  76839. }
  76840. return AnaglyphPostProcess;
  76841. }(BABYLON.PostProcess));
  76842. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  76843. })(BABYLON || (BABYLON = {}));
  76844. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  76845. var BABYLON;
  76846. (function (BABYLON) {
  76847. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  76848. __extends(StereoscopicInterlacePostProcess, _super);
  76849. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  76850. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  76851. _this._passedProcess = rigCameras[0]._rigPostProcess;
  76852. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  76853. _this.onSizeChangedObservable.add(function () {
  76854. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  76855. });
  76856. _this.onApplyObservable.add(function (effect) {
  76857. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  76858. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  76859. });
  76860. return _this;
  76861. }
  76862. return StereoscopicInterlacePostProcess;
  76863. }(BABYLON.PostProcess));
  76864. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  76865. })(BABYLON || (BABYLON = {}));
  76866. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  76867. var BABYLON;
  76868. (function (BABYLON) {
  76869. /**
  76870. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  76871. * Screen rotation is taken into account.
  76872. */
  76873. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  76874. function FreeCameraDeviceOrientationInput() {
  76875. var _this = this;
  76876. this._screenOrientationAngle = 0;
  76877. this._screenQuaternion = new BABYLON.Quaternion();
  76878. this._alpha = 0;
  76879. this._beta = 0;
  76880. this._gamma = 0;
  76881. this._orientationChanged = function () {
  76882. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  76883. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  76884. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  76885. };
  76886. this._deviceOrientation = function (evt) {
  76887. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  76888. _this._beta = evt.beta !== null ? evt.beta : 0;
  76889. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  76890. };
  76891. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  76892. this._orientationChanged();
  76893. }
  76894. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  76895. get: function () {
  76896. return this._camera;
  76897. },
  76898. set: function (camera) {
  76899. this._camera = camera;
  76900. if (this._camera != null && !this._camera.rotationQuaternion) {
  76901. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  76902. }
  76903. },
  76904. enumerable: true,
  76905. configurable: true
  76906. });
  76907. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  76908. window.addEventListener("orientationchange", this._orientationChanged);
  76909. window.addEventListener("deviceorientation", this._deviceOrientation);
  76910. //In certain cases, the attach control is called AFTER orientation was changed,
  76911. //So this is needed.
  76912. this._orientationChanged();
  76913. };
  76914. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  76915. window.removeEventListener("orientationchange", this._orientationChanged);
  76916. window.removeEventListener("deviceorientation", this._deviceOrientation);
  76917. };
  76918. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  76919. //if no device orientation provided, don't update the rotation.
  76920. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  76921. if (!this._alpha)
  76922. return;
  76923. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  76924. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  76925. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  76926. //Mirror on XY Plane
  76927. this._camera.rotationQuaternion.z *= -1;
  76928. this._camera.rotationQuaternion.w *= -1;
  76929. };
  76930. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  76931. return "FreeCameraDeviceOrientationInput";
  76932. };
  76933. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  76934. return "deviceOrientation";
  76935. };
  76936. return FreeCameraDeviceOrientationInput;
  76937. }());
  76938. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  76939. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  76940. })(BABYLON || (BABYLON = {}));
  76941. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  76942. var BABYLON;
  76943. (function (BABYLON) {
  76944. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  76945. function ArcRotateCameraVRDeviceOrientationInput() {
  76946. this.alphaCorrection = 1;
  76947. this.betaCorrection = 1;
  76948. this.gammaCorrection = 1;
  76949. this._alpha = 0;
  76950. this._gamma = 0;
  76951. this._dirty = false;
  76952. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  76953. }
  76954. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  76955. this.camera.attachControl(element, noPreventDefault);
  76956. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  76957. };
  76958. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  76959. if (evt.alpha !== null) {
  76960. this._alpha = +evt.alpha | 0;
  76961. }
  76962. if (evt.gamma !== null) {
  76963. this._gamma = +evt.gamma | 0;
  76964. }
  76965. this._dirty = true;
  76966. };
  76967. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  76968. if (this._dirty) {
  76969. this._dirty = false;
  76970. if (this._gamma < 0) {
  76971. this._gamma = 180 + this._gamma;
  76972. }
  76973. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  76974. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  76975. }
  76976. };
  76977. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  76978. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  76979. };
  76980. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  76981. return "ArcRotateCameraVRDeviceOrientationInput";
  76982. };
  76983. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  76984. return "VRDeviceOrientation";
  76985. };
  76986. return ArcRotateCameraVRDeviceOrientationInput;
  76987. }());
  76988. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  76989. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  76990. })(BABYLON || (BABYLON = {}));
  76991. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  76992. var BABYLON;
  76993. (function (BABYLON) {
  76994. var VRCameraMetrics = /** @class */ (function () {
  76995. function VRCameraMetrics() {
  76996. this.compensateDistortion = true;
  76997. }
  76998. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  76999. get: function () {
  77000. return this.hResolution / (2 * this.vResolution);
  77001. },
  77002. enumerable: true,
  77003. configurable: true
  77004. });
  77005. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77006. get: function () {
  77007. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77008. },
  77009. enumerable: true,
  77010. configurable: true
  77011. });
  77012. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77013. get: function () {
  77014. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77015. var h = (4 * meters) / this.hScreenSize;
  77016. return BABYLON.Matrix.Translation(h, 0, 0);
  77017. },
  77018. enumerable: true,
  77019. configurable: true
  77020. });
  77021. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77022. get: function () {
  77023. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77024. var h = (4 * meters) / this.hScreenSize;
  77025. return BABYLON.Matrix.Translation(-h, 0, 0);
  77026. },
  77027. enumerable: true,
  77028. configurable: true
  77029. });
  77030. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77031. get: function () {
  77032. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77033. },
  77034. enumerable: true,
  77035. configurable: true
  77036. });
  77037. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77038. get: function () {
  77039. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77040. },
  77041. enumerable: true,
  77042. configurable: true
  77043. });
  77044. VRCameraMetrics.GetDefault = function () {
  77045. var result = new VRCameraMetrics();
  77046. result.hResolution = 1280;
  77047. result.vResolution = 800;
  77048. result.hScreenSize = 0.149759993;
  77049. result.vScreenSize = 0.0935999975;
  77050. result.vScreenCenter = 0.0467999987;
  77051. result.eyeToScreenDistance = 0.0410000011;
  77052. result.lensSeparationDistance = 0.0635000020;
  77053. result.interpupillaryDistance = 0.0640000030;
  77054. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77055. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77056. result.postProcessScaleFactor = 1.714605507808412;
  77057. result.lensCenterOffset = 0.151976421;
  77058. return result;
  77059. };
  77060. return VRCameraMetrics;
  77061. }());
  77062. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77063. })(BABYLON || (BABYLON = {}));
  77064. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77065. var BABYLON;
  77066. (function (BABYLON) {
  77067. /**
  77068. * This represents a WebVR camera.
  77069. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77070. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77071. */
  77072. var WebVRFreeCamera = /** @class */ (function (_super) {
  77073. __extends(WebVRFreeCamera, _super);
  77074. /**
  77075. * Instantiates a WebVRFreeCamera.
  77076. * @param name The name of the WebVRFreeCamera
  77077. * @param position The starting anchor position for the camera
  77078. * @param scene The scene the camera belongs to
  77079. * @param webVROptions a set of customizable options for the webVRCamera
  77080. */
  77081. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77082. if (webVROptions === void 0) { webVROptions = {}; }
  77083. var _this = _super.call(this, name, position, scene) || this;
  77084. _this.webVROptions = webVROptions;
  77085. /**
  77086. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77087. */
  77088. _this._vrDevice = null;
  77089. /**
  77090. * The rawPose of the vrDevice.
  77091. */
  77092. _this.rawPose = null;
  77093. _this._specsVersion = "1.1";
  77094. _this._attached = false;
  77095. _this._descendants = [];
  77096. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77097. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77098. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77099. _this._standingMatrix = null;
  77100. /**
  77101. * Represents device position in babylon space.
  77102. */
  77103. _this.devicePosition = BABYLON.Vector3.Zero();
  77104. /**
  77105. * Represents device rotation in babylon space.
  77106. */
  77107. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77108. /**
  77109. * The scale of the device to be used when translating from device space to babylon space.
  77110. */
  77111. _this.deviceScaleFactor = 1;
  77112. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77113. _this._worldToDevice = BABYLON.Matrix.Identity();
  77114. /**
  77115. * References to the webVR controllers for the vrDevice.
  77116. */
  77117. _this.controllers = [];
  77118. /**
  77119. * Emits an event when a controller is attached.
  77120. */
  77121. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77122. /**
  77123. * Emits an event when a controller's mesh has been loaded;
  77124. */
  77125. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77126. /**
  77127. * If the rig cameras be used as parent instead of this camera.
  77128. */
  77129. _this.rigParenting = true;
  77130. _this._defaultHeight = undefined;
  77131. _this._workingVector = BABYLON.Vector3.Zero();
  77132. _this._oneVector = BABYLON.Vector3.One();
  77133. _this._workingMatrix = BABYLON.Matrix.Identity();
  77134. _this._cache.position = BABYLON.Vector3.Zero();
  77135. if (webVROptions.defaultHeight) {
  77136. _this._defaultHeight = webVROptions.defaultHeight;
  77137. _this.position.y = _this._defaultHeight;
  77138. }
  77139. _this.minZ = 0.1;
  77140. //legacy support - the compensation boolean was removed.
  77141. if (arguments.length === 5) {
  77142. _this.webVROptions = arguments[4];
  77143. }
  77144. // default webVR options
  77145. if (_this.webVROptions.trackPosition == undefined) {
  77146. _this.webVROptions.trackPosition = true;
  77147. }
  77148. if (_this.webVROptions.controllerMeshes == undefined) {
  77149. _this.webVROptions.controllerMeshes = true;
  77150. }
  77151. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77152. _this.webVROptions.defaultLightingOnControllers = true;
  77153. }
  77154. _this.rotationQuaternion = new BABYLON.Quaternion();
  77155. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77156. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77157. }
  77158. //enable VR
  77159. var engine = _this.getEngine();
  77160. _this._onVREnabled = function (success) { if (success) {
  77161. _this.initControllers();
  77162. } };
  77163. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77164. engine.initWebVR().add(function (event) {
  77165. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77166. return;
  77167. }
  77168. _this._vrDevice = event.vrDisplay;
  77169. //reset the rig parameters.
  77170. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77171. if (_this._attached) {
  77172. _this.getEngine().enableVR();
  77173. }
  77174. });
  77175. if (typeof (VRFrameData) !== "undefined")
  77176. _this._frameData = new VRFrameData();
  77177. /**
  77178. * The idea behind the following lines:
  77179. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77180. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77181. * the second will not show it correctly.
  77182. *
  77183. * To solve this - each object that has the camera as parent will be added to a protected array.
  77184. * When the rig camera renders, it will take this array and set all of those to be its children.
  77185. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77186. * Amazing!
  77187. */
  77188. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77189. if (camera.parent === _this && _this.rigParenting) {
  77190. _this._descendants = _this.getDescendants(true, function (n) {
  77191. // don't take the cameras or the controllers!
  77192. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77193. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77194. return !isController && !isRigCamera;
  77195. });
  77196. _this._descendants.forEach(function (node) {
  77197. node.parent = camera;
  77198. });
  77199. }
  77200. });
  77201. scene.onAfterCameraRenderObservable.add(function (camera) {
  77202. if (camera.parent === _this && _this.rigParenting) {
  77203. _this._descendants.forEach(function (node) {
  77204. node.parent = _this;
  77205. });
  77206. }
  77207. });
  77208. return _this;
  77209. }
  77210. /**
  77211. * Gets the device distance from the ground.
  77212. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77213. */
  77214. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77215. if (this._standingMatrix && this._defaultHeight === undefined) {
  77216. // Add standing matrix offset to get real offset from ground in room
  77217. this._standingMatrix.getTranslationToRef(this._workingVector);
  77218. return this._deviceRoomPosition.y + this._workingVector.y;
  77219. }
  77220. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77221. return this._defaultHeight || 0;
  77222. };
  77223. /**
  77224. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77225. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77226. */
  77227. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77228. var _this = this;
  77229. if (callback === void 0) { callback = function (bool) { }; }
  77230. // Use standing matrix if available
  77231. if (!navigator || !navigator.getVRDisplays) {
  77232. callback(false);
  77233. }
  77234. else {
  77235. navigator.getVRDisplays().then(function (displays) {
  77236. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  77237. callback(false);
  77238. }
  77239. else {
  77240. _this._standingMatrix = new BABYLON.Matrix();
  77241. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  77242. if (!_this.getScene().useRightHandedSystem) {
  77243. [2, 6, 8, 9, 14].forEach(function (num) {
  77244. if (_this._standingMatrix) {
  77245. _this._standingMatrix.m[num] *= -1;
  77246. }
  77247. });
  77248. }
  77249. callback(true);
  77250. }
  77251. });
  77252. }
  77253. };
  77254. /**
  77255. * Disposes the camera
  77256. */
  77257. WebVRFreeCamera.prototype.dispose = function () {
  77258. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  77259. _super.prototype.dispose.call(this);
  77260. };
  77261. /**
  77262. * Gets a vrController by name.
  77263. * @param name The name of the controller to retreive
  77264. * @returns the controller matching the name specified or null if not found
  77265. */
  77266. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  77267. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  77268. var gp = _a[_i];
  77269. if (gp.hand === name) {
  77270. return gp;
  77271. }
  77272. }
  77273. return null;
  77274. };
  77275. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  77276. /**
  77277. * The controller corrisponding to the users left hand.
  77278. */
  77279. get: function () {
  77280. if (!this._leftController) {
  77281. this._leftController = this.getControllerByName("left");
  77282. }
  77283. return this._leftController;
  77284. },
  77285. enumerable: true,
  77286. configurable: true
  77287. });
  77288. ;
  77289. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  77290. /**
  77291. * The controller corrisponding to the users right hand.
  77292. */
  77293. get: function () {
  77294. if (!this._rightController) {
  77295. this._rightController = this.getControllerByName("right");
  77296. }
  77297. return this._rightController;
  77298. },
  77299. enumerable: true,
  77300. configurable: true
  77301. });
  77302. ;
  77303. /**
  77304. * Casts a ray forward from the vrCamera's gaze.
  77305. * @param length Length of the ray (default: 100)
  77306. * @returns the ray corrisponding to the gaze
  77307. */
  77308. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  77309. if (length === void 0) { length = 100; }
  77310. if (this.leftCamera) {
  77311. // Use left eye to avoid computation to compute center on every call
  77312. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  77313. }
  77314. else {
  77315. return _super.prototype.getForwardRay.call(this, length);
  77316. }
  77317. };
  77318. /**
  77319. * Updates the camera based on device's frame data
  77320. */
  77321. WebVRFreeCamera.prototype._checkInputs = function () {
  77322. if (this._vrDevice && this._vrDevice.isPresenting) {
  77323. this._vrDevice.getFrameData(this._frameData);
  77324. this.updateFromDevice(this._frameData.pose);
  77325. }
  77326. _super.prototype._checkInputs.call(this);
  77327. };
  77328. /**
  77329. * Updates the poseControlled values based on the input device pose.
  77330. * @param poseData Pose coming from the device
  77331. */
  77332. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  77333. if (poseData && poseData.orientation) {
  77334. this.rawPose = poseData;
  77335. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  77336. if (this.getScene().useRightHandedSystem) {
  77337. this._deviceRoomRotationQuaternion.z *= -1;
  77338. this._deviceRoomRotationQuaternion.w *= -1;
  77339. }
  77340. if (this.webVROptions.trackPosition && this.rawPose.position) {
  77341. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  77342. if (this.getScene().useRightHandedSystem) {
  77343. this._deviceRoomPosition.z *= -1;
  77344. }
  77345. }
  77346. }
  77347. };
  77348. /**
  77349. * WebVR's attach control will start broadcasting frames to the device.
  77350. * Note that in certain browsers (chrome for example) this function must be called
  77351. * within a user-interaction callback. Example:
  77352. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  77353. *
  77354. * @param element html element to attach the vrDevice to
  77355. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  77356. */
  77357. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  77358. _super.prototype.attachControl.call(this, element, noPreventDefault);
  77359. this._attached = true;
  77360. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  77361. if (this._vrDevice) {
  77362. this.getEngine().enableVR();
  77363. }
  77364. };
  77365. /**
  77366. * Detaches the camera from the html element and disables VR
  77367. *
  77368. * @param element html element to detach from
  77369. */
  77370. WebVRFreeCamera.prototype.detachControl = function (element) {
  77371. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77372. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77373. _super.prototype.detachControl.call(this, element);
  77374. this._attached = false;
  77375. this.getEngine().disableVR();
  77376. };
  77377. /**
  77378. * @returns the name of this class
  77379. */
  77380. WebVRFreeCamera.prototype.getClassName = function () {
  77381. return "WebVRFreeCamera";
  77382. };
  77383. /**
  77384. * Calls resetPose on the vrDisplay
  77385. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  77386. */
  77387. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  77388. //uses the vrDisplay's "resetPose()".
  77389. //pitch and roll won't be affected.
  77390. this._vrDevice.resetPose();
  77391. };
  77392. /**
  77393. * Updates the rig cameras (left and right eye)
  77394. */
  77395. WebVRFreeCamera.prototype._updateRigCameras = function () {
  77396. var camLeft = this._rigCameras[0];
  77397. var camRight = this._rigCameras[1];
  77398. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77399. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77400. camLeft.position.copyFrom(this._deviceRoomPosition);
  77401. camRight.position.copyFrom(this._deviceRoomPosition);
  77402. };
  77403. /**
  77404. * Updates the cached values of the camera
  77405. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  77406. */
  77407. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  77408. var _this = this;
  77409. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  77410. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  77411. if (!this.updateCacheCalled) {
  77412. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  77413. this.updateCacheCalled = true;
  77414. this.update();
  77415. }
  77416. // Set working vector to the device position in room space rotated by the new rotation
  77417. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  77418. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  77419. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  77420. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  77421. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  77422. // Add translation from anchor position
  77423. this._deviceToWorld.getTranslationToRef(this._workingVector);
  77424. this._workingVector.addInPlace(this.position);
  77425. this._workingVector.subtractInPlace(this._cache.position);
  77426. this._deviceToWorld.setTranslation(this._workingVector);
  77427. // Set an inverted matrix to be used when updating the camera
  77428. this._deviceToWorld.invertToRef(this._worldToDevice);
  77429. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  77430. this.controllers.forEach(function (controller) {
  77431. controller._deviceToWorld = _this._deviceToWorld;
  77432. controller.update();
  77433. });
  77434. }
  77435. if (!ignoreParentClass) {
  77436. _super.prototype._updateCache.call(this);
  77437. }
  77438. this.updateCacheCalled = false;
  77439. };
  77440. /**
  77441. * Updates the current device position and rotation in the babylon world
  77442. */
  77443. WebVRFreeCamera.prototype.update = function () {
  77444. // Get current device position in babylon world
  77445. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  77446. // Get current device rotation in babylon world
  77447. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  77448. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  77449. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  77450. _super.prototype.update.call(this);
  77451. };
  77452. /**
  77453. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  77454. * @returns an identity matrix
  77455. */
  77456. WebVRFreeCamera.prototype._getViewMatrix = function () {
  77457. return BABYLON.Matrix.Identity();
  77458. };
  77459. /**
  77460. * This function is called by the two RIG cameras.
  77461. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  77462. */
  77463. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  77464. var _this = this;
  77465. //WebVR 1.1
  77466. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  77467. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  77468. if (!this.getScene().useRightHandedSystem) {
  77469. [2, 6, 8, 9, 14].forEach(function (num) {
  77470. _this._webvrViewMatrix.m[num] *= -1;
  77471. });
  77472. }
  77473. // update the camera rotation matrix
  77474. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  77475. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  77476. // Computing target and final matrix
  77477. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  77478. var parentCamera = this._cameraRigParams["parentCamera"];
  77479. // should the view matrix be updated with scale and position offset?
  77480. if (parentCamera.deviceScaleFactor !== 1) {
  77481. this._webvrViewMatrix.invert();
  77482. // scale the position, if set
  77483. if (parentCamera.deviceScaleFactor) {
  77484. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  77485. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  77486. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  77487. }
  77488. this._webvrViewMatrix.invert();
  77489. }
  77490. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  77491. return this._webvrViewMatrix;
  77492. };
  77493. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  77494. var _this = this;
  77495. var parentCamera = this.parent;
  77496. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  77497. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  77498. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  77499. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  77500. //babylon compatible matrix
  77501. if (!this.getScene().useRightHandedSystem) {
  77502. [8, 9, 10, 11].forEach(function (num) {
  77503. _this._projectionMatrix.m[num] *= -1;
  77504. });
  77505. }
  77506. return this._projectionMatrix;
  77507. };
  77508. /**
  77509. * Initializes the controllers and their meshes
  77510. */
  77511. WebVRFreeCamera.prototype.initControllers = function () {
  77512. var _this = this;
  77513. this.controllers = [];
  77514. var manager = this.getScene().gamepadManager;
  77515. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77516. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  77517. var webVrController = gamepad;
  77518. if (webVrController.defaultModel) {
  77519. webVrController.defaultModel.setEnabled(false);
  77520. }
  77521. if (webVrController.hand === "right") {
  77522. _this._rightController = null;
  77523. }
  77524. if (webVrController.hand === "left") {
  77525. _this._rightController = null;
  77526. }
  77527. var controllerIndex = _this.controllers.indexOf(webVrController);
  77528. if (controllerIndex !== -1) {
  77529. _this.controllers.splice(controllerIndex, 1);
  77530. }
  77531. }
  77532. });
  77533. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77534. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  77535. var webVrController_1 = gamepad;
  77536. webVrController_1._deviceToWorld = _this._deviceToWorld;
  77537. if (_this.webVROptions.controllerMeshes) {
  77538. if (webVrController_1.defaultModel) {
  77539. webVrController_1.defaultModel.setEnabled(true);
  77540. }
  77541. else {
  77542. // Load the meshes
  77543. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  77544. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  77545. if (_this.webVROptions.defaultLightingOnControllers) {
  77546. if (!_this._lightOnControllers) {
  77547. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  77548. }
  77549. var activateLightOnSubMeshes_1 = function (mesh, light) {
  77550. var children = mesh.getChildren();
  77551. if (children.length !== 0) {
  77552. children.forEach(function (mesh) {
  77553. light.includedOnlyMeshes.push(mesh);
  77554. activateLightOnSubMeshes_1(mesh, light);
  77555. });
  77556. }
  77557. };
  77558. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  77559. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  77560. }
  77561. });
  77562. }
  77563. }
  77564. webVrController_1.attachToPoseControlledCamera(_this);
  77565. // since this is async - sanity check. Is the controller already stored?
  77566. if (_this.controllers.indexOf(webVrController_1) === -1) {
  77567. //add to the controllers array
  77568. _this.controllers.push(webVrController_1);
  77569. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  77570. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  77571. // So we're overriding setting left & right manually to be sure
  77572. var firstViveWandDetected = false;
  77573. for (var i = 0; i < _this.controllers.length; i++) {
  77574. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77575. if (!firstViveWandDetected) {
  77576. firstViveWandDetected = true;
  77577. _this.controllers[i].hand = "left";
  77578. }
  77579. else {
  77580. _this.controllers[i].hand = "right";
  77581. }
  77582. }
  77583. }
  77584. //did we find enough controllers? Great! let the developer know.
  77585. if (_this.controllers.length >= 2) {
  77586. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  77587. }
  77588. }
  77589. }
  77590. });
  77591. };
  77592. return WebVRFreeCamera;
  77593. }(BABYLON.FreeCamera));
  77594. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  77595. })(BABYLON || (BABYLON = {}));
  77596. //# sourceMappingURL=babylon.webVRCamera.js.map
  77597. var BABYLON;
  77598. (function (BABYLON) {
  77599. // We're mainly based on the logic defined into the FreeCamera code
  77600. /**
  77601. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  77602. * being tilted forward or back and left or right.
  77603. */
  77604. var DeviceOrientationCamera = /** @class */ (function (_super) {
  77605. __extends(DeviceOrientationCamera, _super);
  77606. /**
  77607. * Creates a new device orientation camera. @see DeviceOrientationCamera
  77608. * @param name The name of the camera
  77609. * @param position The start position camera
  77610. * @param scene The scene the camera belongs to
  77611. */
  77612. function DeviceOrientationCamera(name, position, scene) {
  77613. var _this = _super.call(this, name, position, scene) || this;
  77614. _this._quaternionCache = new BABYLON.Quaternion();
  77615. _this.inputs.addDeviceOrientation();
  77616. return _this;
  77617. }
  77618. /**
  77619. * Gets the current instance class name ("DeviceOrientationCamera").
  77620. * This helps avoiding instanceof at run time.
  77621. * @returns the class name
  77622. */
  77623. DeviceOrientationCamera.prototype.getClassName = function () {
  77624. return "DeviceOrientationCamera";
  77625. };
  77626. /**
  77627. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  77628. */
  77629. DeviceOrientationCamera.prototype._checkInputs = function () {
  77630. _super.prototype._checkInputs.call(this);
  77631. this._quaternionCache.copyFrom(this.rotationQuaternion);
  77632. if (this._initialQuaternion) {
  77633. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  77634. }
  77635. };
  77636. /**
  77637. * Reset the camera to its default orientation on the specified axis only.
  77638. * @param axis The axis to reset
  77639. */
  77640. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  77641. var _this = this;
  77642. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  77643. //can only work if this camera has a rotation quaternion already.
  77644. if (!this.rotationQuaternion)
  77645. return;
  77646. if (!this._initialQuaternion) {
  77647. this._initialQuaternion = new BABYLON.Quaternion();
  77648. }
  77649. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  77650. ['x', 'y', 'z'].forEach(function (axisName) {
  77651. if (!axis[axisName]) {
  77652. _this._initialQuaternion[axisName] = 0;
  77653. }
  77654. else {
  77655. _this._initialQuaternion[axisName] *= -1;
  77656. }
  77657. });
  77658. this._initialQuaternion.normalize();
  77659. //force rotation update
  77660. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  77661. };
  77662. return DeviceOrientationCamera;
  77663. }(BABYLON.FreeCamera));
  77664. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  77665. })(BABYLON || (BABYLON = {}));
  77666. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  77667. var BABYLON;
  77668. (function (BABYLON) {
  77669. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  77670. __extends(VRDeviceOrientationFreeCamera, _super);
  77671. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  77672. if (compensateDistortion === void 0) { compensateDistortion = true; }
  77673. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  77674. var _this = _super.call(this, name, position, scene) || this;
  77675. vrCameraMetrics.compensateDistortion = compensateDistortion;
  77676. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  77677. return _this;
  77678. }
  77679. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  77680. return "VRDeviceOrientationFreeCamera";
  77681. };
  77682. return VRDeviceOrientationFreeCamera;
  77683. }(BABYLON.DeviceOrientationCamera));
  77684. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  77685. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  77686. __extends(VRDeviceOrientationGamepadCamera, _super);
  77687. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  77688. if (compensateDistortion === void 0) { compensateDistortion = true; }
  77689. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  77690. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  77691. _this.inputs.addGamepad();
  77692. return _this;
  77693. }
  77694. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  77695. return "VRDeviceOrientationGamepadCamera";
  77696. };
  77697. return VRDeviceOrientationGamepadCamera;
  77698. }(VRDeviceOrientationFreeCamera));
  77699. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  77700. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  77701. __extends(VRDeviceOrientationArcRotateCamera, _super);
  77702. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  77703. if (compensateDistortion === void 0) { compensateDistortion = true; }
  77704. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  77705. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  77706. vrCameraMetrics.compensateDistortion = compensateDistortion;
  77707. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  77708. _this.inputs.addVRDeviceOrientation();
  77709. return _this;
  77710. }
  77711. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  77712. return "VRDeviceOrientationArcRotateCamera";
  77713. };
  77714. return VRDeviceOrientationArcRotateCamera;
  77715. }(BABYLON.ArcRotateCamera));
  77716. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  77717. })(BABYLON || (BABYLON = {}));
  77718. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  77719. var BABYLON;
  77720. (function (BABYLON) {
  77721. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  77722. __extends(AnaglyphFreeCamera, _super);
  77723. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  77724. var _this = _super.call(this, name, position, scene) || this;
  77725. _this.interaxialDistance = interaxialDistance;
  77726. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  77727. return _this;
  77728. }
  77729. AnaglyphFreeCamera.prototype.getClassName = function () {
  77730. return "AnaglyphFreeCamera";
  77731. };
  77732. return AnaglyphFreeCamera;
  77733. }(BABYLON.FreeCamera));
  77734. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  77735. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  77736. __extends(AnaglyphArcRotateCamera, _super);
  77737. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  77738. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  77739. _this.interaxialDistance = interaxialDistance;
  77740. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  77741. return _this;
  77742. }
  77743. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  77744. return "AnaglyphArcRotateCamera";
  77745. };
  77746. return AnaglyphArcRotateCamera;
  77747. }(BABYLON.ArcRotateCamera));
  77748. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  77749. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  77750. __extends(AnaglyphGamepadCamera, _super);
  77751. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  77752. var _this = _super.call(this, name, position, scene) || this;
  77753. _this.interaxialDistance = interaxialDistance;
  77754. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  77755. return _this;
  77756. }
  77757. AnaglyphGamepadCamera.prototype.getClassName = function () {
  77758. return "AnaglyphGamepadCamera";
  77759. };
  77760. return AnaglyphGamepadCamera;
  77761. }(BABYLON.GamepadCamera));
  77762. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  77763. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  77764. __extends(AnaglyphUniversalCamera, _super);
  77765. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  77766. var _this = _super.call(this, name, position, scene) || this;
  77767. _this.interaxialDistance = interaxialDistance;
  77768. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  77769. return _this;
  77770. }
  77771. AnaglyphUniversalCamera.prototype.getClassName = function () {
  77772. return "AnaglyphUniversalCamera";
  77773. };
  77774. return AnaglyphUniversalCamera;
  77775. }(BABYLON.UniversalCamera));
  77776. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  77777. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  77778. __extends(StereoscopicFreeCamera, _super);
  77779. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  77780. var _this = _super.call(this, name, position, scene) || this;
  77781. _this.interaxialDistance = interaxialDistance;
  77782. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  77783. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  77784. return _this;
  77785. }
  77786. StereoscopicFreeCamera.prototype.getClassName = function () {
  77787. return "StereoscopicFreeCamera";
  77788. };
  77789. return StereoscopicFreeCamera;
  77790. }(BABYLON.FreeCamera));
  77791. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  77792. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  77793. __extends(StereoscopicArcRotateCamera, _super);
  77794. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  77795. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  77796. _this.interaxialDistance = interaxialDistance;
  77797. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  77798. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  77799. return _this;
  77800. }
  77801. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  77802. return "StereoscopicArcRotateCamera";
  77803. };
  77804. return StereoscopicArcRotateCamera;
  77805. }(BABYLON.ArcRotateCamera));
  77806. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  77807. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  77808. __extends(StereoscopicGamepadCamera, _super);
  77809. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  77810. var _this = _super.call(this, name, position, scene) || this;
  77811. _this.interaxialDistance = interaxialDistance;
  77812. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  77813. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  77814. return _this;
  77815. }
  77816. StereoscopicGamepadCamera.prototype.getClassName = function () {
  77817. return "StereoscopicGamepadCamera";
  77818. };
  77819. return StereoscopicGamepadCamera;
  77820. }(BABYLON.GamepadCamera));
  77821. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  77822. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  77823. __extends(StereoscopicUniversalCamera, _super);
  77824. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  77825. var _this = _super.call(this, name, position, scene) || this;
  77826. _this.interaxialDistance = interaxialDistance;
  77827. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  77828. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  77829. return _this;
  77830. }
  77831. StereoscopicUniversalCamera.prototype.getClassName = function () {
  77832. return "StereoscopicUniversalCamera";
  77833. };
  77834. return StereoscopicUniversalCamera;
  77835. }(BABYLON.UniversalCamera));
  77836. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  77837. })(BABYLON || (BABYLON = {}));
  77838. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  77839. var BABYLON;
  77840. (function (BABYLON) {
  77841. /**
  77842. * Helps to quickly add VR support to an existing scene.
  77843. * See http://doc.babylonjs.com/how_to/webvr_helper
  77844. */
  77845. var VRExperienceHelper = /** @class */ (function () {
  77846. /**
  77847. * Instantiates a VRExperienceHelper.
  77848. * Helps to quickly add VR support to an existing scene.
  77849. * @param scene The scene the VRExperienceHelper belongs to.
  77850. * @param webVROptions Options to modify the vr experience helper's behavior.
  77851. */
  77852. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  77853. if (webVROptions === void 0) { webVROptions = {}; }
  77854. var _this = this;
  77855. this.webVROptions = webVROptions;
  77856. // Can the system support WebVR, even if a headset isn't plugged in?
  77857. this._webVRsupported = false;
  77858. // If WebVR is supported, is a headset plugged in and are we ready to present?
  77859. this._webVRready = false;
  77860. // Are we waiting for the requestPresent callback to complete?
  77861. this._webVRrequesting = false;
  77862. // Are we presenting to the headset right now?
  77863. this._webVRpresenting = false;
  77864. // Are we presenting in the fullscreen fallback?
  77865. this._fullscreenVRpresenting = false;
  77866. /**
  77867. * Observable raised when entering VR.
  77868. */
  77869. this.onEnteringVRObservable = new BABYLON.Observable();
  77870. /**
  77871. * Observable raised when exiting VR.
  77872. */
  77873. this.onExitingVRObservable = new BABYLON.Observable();
  77874. /**
  77875. * Observable raised when controller mesh is loaded.
  77876. */
  77877. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77878. this._useCustomVRButton = false;
  77879. this._teleportationRequested = false;
  77880. this._teleportationEnabledOnLeftController = false;
  77881. this._teleportationEnabledOnRightController = false;
  77882. this._interactionsEnabledOnLeftController = false;
  77883. this._interactionsEnabledOnRightController = false;
  77884. this._leftControllerReady = false;
  77885. this._rightControllerReady = false;
  77886. this._floorMeshesCollection = [];
  77887. this._teleportationAllowed = false;
  77888. this._rotationAllowed = true;
  77889. this._teleportationRequestInitiated = false;
  77890. this._teleportationBackRequestInitiated = false;
  77891. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  77892. this._rotationRightAsked = false;
  77893. this._rotationLeftAsked = false;
  77894. this._isDefaultTeleportationTarget = true;
  77895. this._teleportationFillColor = "#444444";
  77896. this._teleportationBorderColor = "#FFFFFF";
  77897. this._rotationAngle = 0;
  77898. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  77899. this._padSensibilityUp = 0.65;
  77900. this._padSensibilityDown = 0.35;
  77901. /**
  77902. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  77903. */
  77904. this.onNewMeshSelected = new BABYLON.Observable();
  77905. /**
  77906. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  77907. */
  77908. this.onNewMeshPicked = new BABYLON.Observable();
  77909. /**
  77910. * Observable raised before camera teleportation
  77911. */
  77912. this.onBeforeCameraTeleport = new BABYLON.Observable();
  77913. /**
  77914. * Observable raised after camera teleportation
  77915. */
  77916. this.onAfterCameraTeleport = new BABYLON.Observable();
  77917. /**
  77918. * Observable raised when current selected mesh gets unselected
  77919. */
  77920. this.onSelectedMeshUnselected = new BABYLON.Observable();
  77921. /**
  77922. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  77923. */
  77924. this.teleportationEnabled = true;
  77925. this._pointerDownOnMeshAsked = false;
  77926. this._isActionableMesh = false;
  77927. this._teleportationInitialized = false;
  77928. this._interactionsEnabled = false;
  77929. this._interactionsRequested = false;
  77930. this._displayGaze = true;
  77931. this._displayLaserPointer = true;
  77932. this._dpadPressed = true;
  77933. this._onResize = function () {
  77934. _this.moveButtonToBottomRight();
  77935. if (_this._fullscreenVRpresenting && _this._webVRready) {
  77936. _this.exitVR();
  77937. }
  77938. };
  77939. this._onFullscreenChange = function () {
  77940. if (document.fullscreen !== undefined) {
  77941. _this._fullscreenVRpresenting = document.fullscreen;
  77942. }
  77943. else if (document.mozFullScreen !== undefined) {
  77944. _this._fullscreenVRpresenting = document.mozFullScreen;
  77945. }
  77946. else if (document.webkitIsFullScreen !== undefined) {
  77947. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  77948. }
  77949. else if (document.msIsFullScreen !== undefined) {
  77950. _this._fullscreenVRpresenting = document.msIsFullScreen;
  77951. }
  77952. if (!_this._fullscreenVRpresenting && _this._canvas) {
  77953. _this.exitVR();
  77954. if (!_this._useCustomVRButton) {
  77955. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  77956. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  77957. }
  77958. }
  77959. };
  77960. this.beforeRender = function () {
  77961. _this._castRayAndSelectObject();
  77962. };
  77963. this._onNewGamepadConnected = function (gamepad) {
  77964. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77965. if (gamepad.leftStick) {
  77966. gamepad.onleftstickchanged(function (stickValues) {
  77967. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  77968. // Listening to classic/xbox gamepad only if no VR controller is active
  77969. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  77970. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  77971. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  77972. _this._checkTeleportWithRay(stickValues);
  77973. _this._checkTeleportBackwards(stickValues);
  77974. }
  77975. }
  77976. });
  77977. }
  77978. if (gamepad.rightStick) {
  77979. gamepad.onrightstickchanged(function (stickValues) {
  77980. if (_this._teleportationInitialized) {
  77981. _this._checkRotate(stickValues);
  77982. }
  77983. });
  77984. }
  77985. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  77986. gamepad.onbuttondown(function (buttonPressed) {
  77987. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  77988. _this._selectionPointerDown();
  77989. }
  77990. });
  77991. gamepad.onbuttonup(function (buttonPressed) {
  77992. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  77993. _this._selectionPointerUp();
  77994. }
  77995. });
  77996. }
  77997. }
  77998. else {
  77999. var webVRController = gamepad;
  78000. _this._tryEnableInteractionOnController(webVRController);
  78001. }
  78002. };
  78003. // 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
  78004. this._tryEnableInteractionOnController = function (webVRController) {
  78005. if (webVRController.hand === "left") {
  78006. _this._leftControllerReady = true;
  78007. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78008. _this._enableInteractionOnController(webVRController);
  78009. }
  78010. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78011. _this._enableTeleportationOnController(webVRController);
  78012. }
  78013. }
  78014. if (webVRController.hand === "right") {
  78015. _this._rightControllerReady = true;
  78016. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78017. _this._enableInteractionOnController(webVRController);
  78018. }
  78019. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78020. _this._enableTeleportationOnController(webVRController);
  78021. }
  78022. }
  78023. };
  78024. this._onNewGamepadDisconnected = function (gamepad) {
  78025. if (gamepad instanceof BABYLON.WebVRController) {
  78026. if (gamepad.hand === "left") {
  78027. _this._interactionsEnabledOnLeftController = false;
  78028. _this._teleportationEnabledOnLeftController = false;
  78029. _this._leftControllerReady = false;
  78030. if (_this._leftLaserPointer) {
  78031. _this._leftLaserPointer.dispose();
  78032. }
  78033. }
  78034. if (gamepad.hand === "right") {
  78035. _this._interactionsEnabledOnRightController = false;
  78036. _this._teleportationEnabledOnRightController = false;
  78037. _this._rightControllerReady = false;
  78038. if (_this._rightLaserPointer) {
  78039. _this._rightLaserPointer.dispose();
  78040. }
  78041. }
  78042. }
  78043. };
  78044. this._workingVector = BABYLON.Vector3.Zero();
  78045. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78046. this._workingMatrix = BABYLON.Matrix.Identity();
  78047. this._scene = scene;
  78048. this._canvas = scene.getEngine().getRenderingCanvas();
  78049. // Parse options
  78050. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78051. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78052. }
  78053. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78054. webVROptions.createDeviceOrientationCamera = true;
  78055. }
  78056. if (webVROptions.defaultHeight === undefined) {
  78057. webVROptions.defaultHeight = 1.7;
  78058. }
  78059. if (webVROptions.useCustomVRButton) {
  78060. this._useCustomVRButton = true;
  78061. if (webVROptions.customVRButton) {
  78062. this._btnVR = webVROptions.customVRButton;
  78063. }
  78064. }
  78065. if (webVROptions.rayLength) {
  78066. this._rayLength = webVROptions.rayLength;
  78067. }
  78068. this._defaultHeight = webVROptions.defaultHeight;
  78069. // Set position
  78070. if (this._scene.activeCamera) {
  78071. this._position = this._scene.activeCamera.position.clone();
  78072. }
  78073. else {
  78074. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78075. }
  78076. // Set non-vr camera
  78077. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78078. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78079. // Copy data from existing camera
  78080. if (this._scene.activeCamera) {
  78081. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78082. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78083. // Set rotation from previous camera
  78084. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78085. var targetCamera = this._scene.activeCamera;
  78086. if (targetCamera.rotationQuaternion) {
  78087. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78088. }
  78089. else {
  78090. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78091. }
  78092. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78093. }
  78094. }
  78095. this._scene.activeCamera = this._deviceOrientationCamera;
  78096. if (this._canvas) {
  78097. this._scene.activeCamera.attachControl(this._canvas);
  78098. }
  78099. }
  78100. else {
  78101. this._existingCamera = this._scene.activeCamera;
  78102. }
  78103. // Create VR cameras
  78104. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78105. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78106. }
  78107. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78108. this._webVRCamera.useStandingMatrix();
  78109. // Create default button
  78110. if (!this._useCustomVRButton) {
  78111. this._btnVR = document.createElement("BUTTON");
  78112. this._btnVR.className = "babylonVRicon";
  78113. this._btnVR.id = "babylonVRiconbtn";
  78114. this._btnVR.title = "Click to switch to VR";
  78115. 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) }";
  78116. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78117. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78118. // css += ".babylonVRicon.vrdisplaysupported { }";
  78119. // css += ".babylonVRicon.vrdisplayready { }";
  78120. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78121. var style = document.createElement('style');
  78122. style.appendChild(document.createTextNode(css));
  78123. document.getElementsByTagName('head')[0].appendChild(style);
  78124. this.moveButtonToBottomRight();
  78125. }
  78126. // VR button click event
  78127. if (this._btnVR) {
  78128. this._btnVR.addEventListener("click", function () {
  78129. if (!_this.isInVRMode) {
  78130. _this.enterVR();
  78131. }
  78132. else {
  78133. _this.exitVR();
  78134. }
  78135. });
  78136. }
  78137. // Window events
  78138. window.addEventListener("resize", this._onResize);
  78139. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78140. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78141. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78142. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78143. // Display vr button when headset is connected
  78144. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78145. this.displayVRButton();
  78146. }
  78147. else {
  78148. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78149. if (e.vrDisplay) {
  78150. _this.displayVRButton();
  78151. }
  78152. });
  78153. }
  78154. // Exiting VR mode using 'ESC' key on desktop
  78155. this._onKeyDown = function (event) {
  78156. if (event.keyCode === 27 && _this.isInVRMode) {
  78157. _this.exitVR();
  78158. }
  78159. };
  78160. document.addEventListener("keydown", this._onKeyDown);
  78161. // Exiting VR mode double tapping the touch screen
  78162. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78163. if (_this.isInVRMode) {
  78164. _this.exitVR();
  78165. if (_this._fullscreenVRpresenting) {
  78166. _this._scene.getEngine().switchFullscreen(true);
  78167. }
  78168. }
  78169. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78170. // Listen for WebVR display changes
  78171. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78172. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78173. this._onVRRequestPresentStart = function () {
  78174. _this._webVRrequesting = true;
  78175. _this.updateButtonVisibility();
  78176. };
  78177. this._onVRRequestPresentComplete = function (success) {
  78178. _this._webVRrequesting = false;
  78179. _this.updateButtonVisibility();
  78180. };
  78181. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78182. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78183. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78184. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78185. scene.onDisposeObservable.add(function () {
  78186. _this.dispose();
  78187. });
  78188. // Gamepad connection events
  78189. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78190. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78191. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78192. this.updateButtonVisibility();
  78193. //create easing functions
  78194. this._circleEase = new BABYLON.CircleEase();
  78195. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78196. }
  78197. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78198. /** Return this.onEnteringVRObservable
  78199. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78200. */
  78201. get: function () {
  78202. return this.onEnteringVRObservable;
  78203. },
  78204. enumerable: true,
  78205. configurable: true
  78206. });
  78207. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78208. /** Return this.onExitingVRObservable
  78209. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78210. */
  78211. get: function () {
  78212. return this.onExitingVRObservable;
  78213. },
  78214. enumerable: true,
  78215. configurable: true
  78216. });
  78217. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78218. /** Return this.onControllerMeshLoadedObservable
  78219. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78220. */
  78221. get: function () {
  78222. return this.onControllerMeshLoadedObservable;
  78223. },
  78224. enumerable: true,
  78225. configurable: true
  78226. });
  78227. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78228. /**
  78229. * The mesh used to display where the user is going to teleport.
  78230. */
  78231. get: function () {
  78232. return this._teleportationTarget;
  78233. },
  78234. /**
  78235. * Sets the mesh to be used to display where the user is going to teleport.
  78236. */
  78237. set: function (value) {
  78238. if (value) {
  78239. value.name = "teleportationTarget";
  78240. this._isDefaultTeleportationTarget = false;
  78241. this._teleportationTarget = value;
  78242. }
  78243. },
  78244. enumerable: true,
  78245. configurable: true
  78246. });
  78247. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  78248. /**
  78249. * If the ray of the gaze should be displayed.
  78250. */
  78251. get: function () {
  78252. return this._displayGaze;
  78253. },
  78254. /**
  78255. * Sets if the ray of the gaze should be displayed.
  78256. */
  78257. set: function (value) {
  78258. this._displayGaze = value;
  78259. if (!value) {
  78260. this._gazeTracker.isVisible = false;
  78261. }
  78262. },
  78263. enumerable: true,
  78264. configurable: true
  78265. });
  78266. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  78267. /**
  78268. * If the ray of the LaserPointer should be displayed.
  78269. */
  78270. get: function () {
  78271. return this._displayLaserPointer;
  78272. },
  78273. /**
  78274. * Sets if the ray of the LaserPointer should be displayed.
  78275. */
  78276. set: function (value) {
  78277. this._displayLaserPointer = value;
  78278. if (!value) {
  78279. if (this._rightLaserPointer) {
  78280. this._rightLaserPointer.isVisible = false;
  78281. }
  78282. if (this._leftLaserPointer) {
  78283. this._leftLaserPointer.isVisible = false;
  78284. }
  78285. }
  78286. else {
  78287. if (this._rightLaserPointer) {
  78288. this._rightLaserPointer.isVisible = true;
  78289. }
  78290. else if (this._leftLaserPointer) {
  78291. this._leftLaserPointer.isVisible = true;
  78292. }
  78293. }
  78294. },
  78295. enumerable: true,
  78296. configurable: true
  78297. });
  78298. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  78299. /**
  78300. * The deviceOrientationCamera used as the camera when not in VR.
  78301. */
  78302. get: function () {
  78303. return this._deviceOrientationCamera;
  78304. },
  78305. enumerable: true,
  78306. configurable: true
  78307. });
  78308. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  78309. /**
  78310. * Based on the current WebVR support, returns the current VR camera used.
  78311. */
  78312. get: function () {
  78313. if (this._webVRready) {
  78314. return this._webVRCamera;
  78315. }
  78316. else {
  78317. return this._scene.activeCamera;
  78318. }
  78319. },
  78320. enumerable: true,
  78321. configurable: true
  78322. });
  78323. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  78324. /**
  78325. * The webVRCamera which is used when in VR.
  78326. */
  78327. get: function () {
  78328. return this._webVRCamera;
  78329. },
  78330. enumerable: true,
  78331. configurable: true
  78332. });
  78333. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  78334. /**
  78335. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  78336. */
  78337. get: function () {
  78338. return this._vrDeviceOrientationCamera;
  78339. },
  78340. enumerable: true,
  78341. configurable: true
  78342. });
  78343. // Raised when one of the controller has loaded successfully its associated default mesh
  78344. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  78345. this._tryEnableInteractionOnController(webVRController);
  78346. try {
  78347. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  78348. }
  78349. catch (err) {
  78350. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  78351. }
  78352. };
  78353. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  78354. /**
  78355. * Gets a value indicating if we are currently in VR mode.
  78356. */
  78357. get: function () {
  78358. return this._webVRpresenting || this._fullscreenVRpresenting;
  78359. },
  78360. enumerable: true,
  78361. configurable: true
  78362. });
  78363. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  78364. var vrDisplay = this._scene.getEngine().getVRDevice();
  78365. if (vrDisplay) {
  78366. var wasPresenting = this._webVRpresenting;
  78367. // A VR display is connected
  78368. this._webVRpresenting = vrDisplay.isPresenting;
  78369. if (wasPresenting && !this._webVRpresenting)
  78370. this.exitVR();
  78371. }
  78372. else {
  78373. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  78374. }
  78375. this.updateButtonVisibility();
  78376. };
  78377. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  78378. this._webVRsupported = eventArgs.vrSupported;
  78379. this._webVRready = !!eventArgs.vrDisplay;
  78380. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  78381. this.updateButtonVisibility();
  78382. };
  78383. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  78384. if (this._canvas && !this._useCustomVRButton) {
  78385. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  78386. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  78387. }
  78388. };
  78389. VRExperienceHelper.prototype.displayVRButton = function () {
  78390. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  78391. document.body.appendChild(this._btnVR);
  78392. this._btnVRDisplayed = true;
  78393. }
  78394. };
  78395. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  78396. if (!this._btnVR || this._useCustomVRButton) {
  78397. return;
  78398. }
  78399. this._btnVR.className = "babylonVRicon";
  78400. if (this.isInVRMode) {
  78401. this._btnVR.className += " vrdisplaypresenting";
  78402. }
  78403. else {
  78404. if (this._webVRready)
  78405. this._btnVR.className += " vrdisplayready";
  78406. if (this._webVRsupported)
  78407. this._btnVR.className += " vrdisplaysupported";
  78408. if (this._webVRrequesting)
  78409. this._btnVR.className += " vrdisplayrequesting";
  78410. }
  78411. };
  78412. /**
  78413. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  78414. * Otherwise, will use the fullscreen API.
  78415. */
  78416. VRExperienceHelper.prototype.enterVR = function () {
  78417. if (this.onEnteringVRObservable) {
  78418. try {
  78419. this.onEnteringVRObservable.notifyObservers(this);
  78420. }
  78421. catch (err) {
  78422. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  78423. }
  78424. }
  78425. if (this._scene.activeCamera) {
  78426. this._position = this._scene.activeCamera.position.clone();
  78427. // make sure that we return to the last active camera
  78428. this._existingCamera = this._scene.activeCamera;
  78429. }
  78430. if (this._webVRrequesting)
  78431. return;
  78432. // If WebVR is supported and a headset is connected
  78433. if (this._webVRready) {
  78434. if (!this._webVRpresenting) {
  78435. this._webVRCamera.position = this._position;
  78436. this._scene.activeCamera = this._webVRCamera;
  78437. }
  78438. }
  78439. else if (this._vrDeviceOrientationCamera) {
  78440. this._vrDeviceOrientationCamera.position = this._position;
  78441. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  78442. this._scene.getEngine().switchFullscreen(true);
  78443. this.updateButtonVisibility();
  78444. }
  78445. if (this._scene.activeCamera && this._canvas) {
  78446. this._scene.activeCamera.attachControl(this._canvas);
  78447. }
  78448. if (this._interactionsEnabled) {
  78449. this._scene.registerBeforeRender(this.beforeRender);
  78450. }
  78451. };
  78452. /**
  78453. * Attempt to exit VR, or fullscreen.
  78454. */
  78455. VRExperienceHelper.prototype.exitVR = function () {
  78456. if (this.onExitingVRObservable) {
  78457. try {
  78458. this.onExitingVRObservable.notifyObservers(this);
  78459. }
  78460. catch (err) {
  78461. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  78462. }
  78463. }
  78464. if (this._webVRpresenting) {
  78465. this._scene.getEngine().disableVR();
  78466. }
  78467. if (this._scene.activeCamera) {
  78468. this._position = this._scene.activeCamera.position.clone();
  78469. }
  78470. if (this._deviceOrientationCamera) {
  78471. this._deviceOrientationCamera.position = this._position;
  78472. this._scene.activeCamera = this._deviceOrientationCamera;
  78473. if (this._canvas) {
  78474. this._scene.activeCamera.attachControl(this._canvas);
  78475. }
  78476. }
  78477. else if (this._existingCamera) {
  78478. this._existingCamera.position = this._position;
  78479. this._scene.activeCamera = this._existingCamera;
  78480. }
  78481. this.updateButtonVisibility();
  78482. if (this._interactionsEnabled) {
  78483. this._scene.unregisterBeforeRender(this.beforeRender);
  78484. }
  78485. };
  78486. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  78487. /**
  78488. * The position of the vr experience helper.
  78489. */
  78490. get: function () {
  78491. return this._position;
  78492. },
  78493. /**
  78494. * Sets the position of the vr experience helper.
  78495. */
  78496. set: function (value) {
  78497. this._position = value;
  78498. if (this._scene.activeCamera) {
  78499. this._scene.activeCamera.position = value;
  78500. }
  78501. },
  78502. enumerable: true,
  78503. configurable: true
  78504. });
  78505. /**
  78506. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  78507. */
  78508. VRExperienceHelper.prototype.enableInteractions = function () {
  78509. var _this = this;
  78510. if (!this._interactionsEnabled) {
  78511. this._interactionsRequested = true;
  78512. if (this._leftControllerReady && this._webVRCamera.leftController) {
  78513. this._enableInteractionOnController(this._webVRCamera.leftController);
  78514. }
  78515. if (this._rightControllerReady && this._webVRCamera.rightController) {
  78516. this._enableInteractionOnController(this._webVRCamera.rightController);
  78517. }
  78518. this._createGazeTracker();
  78519. this.raySelectionPredicate = function (mesh) {
  78520. return mesh.isVisible;
  78521. };
  78522. this.meshSelectionPredicate = function (mesh) {
  78523. return true;
  78524. };
  78525. this._raySelectionPredicate = function (mesh) {
  78526. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  78527. && mesh.name.indexOf("teleportationTarget") === -1
  78528. && mesh.name.indexOf("torusTeleportation") === -1
  78529. && mesh.name.indexOf("laserPointer") === -1)) {
  78530. return _this.raySelectionPredicate(mesh);
  78531. }
  78532. return false;
  78533. };
  78534. this._interactionsEnabled = true;
  78535. }
  78536. };
  78537. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  78538. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  78539. if (this._floorMeshesCollection[i].id === mesh.id) {
  78540. return true;
  78541. }
  78542. }
  78543. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  78544. return true;
  78545. }
  78546. return false;
  78547. };
  78548. /**
  78549. * Adds a floor mesh to be used for teleportation.
  78550. * @param floorMesh the mesh to be used for teleportation.
  78551. */
  78552. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  78553. if (!this._floorMeshesCollection) {
  78554. return;
  78555. }
  78556. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  78557. return;
  78558. }
  78559. this._floorMeshesCollection.push(floorMesh);
  78560. };
  78561. /**
  78562. * Removes a floor mesh from being used for teleportation.
  78563. * @param floorMesh the mesh to be removed.
  78564. */
  78565. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  78566. if (!this._floorMeshesCollection) {
  78567. return;
  78568. }
  78569. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  78570. if (meshIndex !== -1) {
  78571. this._floorMeshesCollection.splice(meshIndex, 1);
  78572. }
  78573. };
  78574. /**
  78575. * Enables interactions and teleportation using the VR controllers and gaze.
  78576. * @param vrTeleportationOptions options to modify teleportation behavior.
  78577. */
  78578. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  78579. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  78580. if (!this._teleportationInitialized) {
  78581. this._teleportationRequested = true;
  78582. this.enableInteractions();
  78583. if (vrTeleportationOptions.floorMeshName) {
  78584. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  78585. }
  78586. if (vrTeleportationOptions.floorMeshes) {
  78587. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  78588. }
  78589. if (this._leftControllerReady && this._webVRCamera.leftController) {
  78590. this._enableTeleportationOnController(this._webVRCamera.leftController);
  78591. }
  78592. if (this._rightControllerReady && this._webVRCamera.rightController) {
  78593. this._enableTeleportationOnController(this._webVRCamera.rightController);
  78594. }
  78595. // Creates an image processing post process for the vignette not relying
  78596. // on the main scene configuration for image processing to reduce setup and spaces
  78597. // (gamma/linear) conflicts.
  78598. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  78599. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78600. imageProcessingConfiguration.vignetteEnabled = true;
  78601. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  78602. this._webVRCamera.detachPostProcess(this._postProcessMove);
  78603. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  78604. this._teleportationInitialized = true;
  78605. if (this._isDefaultTeleportationTarget) {
  78606. this._createTeleportationCircles();
  78607. }
  78608. }
  78609. };
  78610. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  78611. var _this = this;
  78612. var controllerMesh = webVRController.mesh;
  78613. if (controllerMesh) {
  78614. var makeNotPick = function (root) {
  78615. root.name += " laserPointer";
  78616. root.getChildMeshes().forEach(function (c) {
  78617. makeNotPick(c);
  78618. });
  78619. };
  78620. makeNotPick(controllerMesh);
  78621. var childMeshes = controllerMesh.getChildMeshes();
  78622. for (var i = 0; i < childMeshes.length; i++) {
  78623. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  78624. controllerMesh = childMeshes[i];
  78625. break;
  78626. }
  78627. }
  78628. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  78629. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  78630. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  78631. laserPointerMaterial.alpha = 0.6;
  78632. laserPointer.material = laserPointerMaterial;
  78633. laserPointer.rotation.x = Math.PI / 2;
  78634. laserPointer.parent = controllerMesh;
  78635. laserPointer.position.z = -0.5;
  78636. laserPointer.isVisible = false;
  78637. if (webVRController.hand === "left") {
  78638. this._leftLaserPointer = laserPointer;
  78639. this._interactionsEnabledOnLeftController = true;
  78640. if (!this._rightLaserPointer) {
  78641. this._leftLaserPointer.isVisible = true;
  78642. }
  78643. }
  78644. else {
  78645. this._rightLaserPointer = laserPointer;
  78646. this._interactionsEnabledOnRightController = true;
  78647. if (!this._leftLaserPointer) {
  78648. this._rightLaserPointer.isVisible = true;
  78649. }
  78650. }
  78651. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  78652. // Enabling / disabling laserPointer
  78653. if (_this._displayLaserPointer && stateObject.value === 1) {
  78654. laserPointer.isVisible = !laserPointer.isVisible;
  78655. // Laser pointer can only be active on left or right, not both at the same time
  78656. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  78657. _this._rightLaserPointer.isVisible = false;
  78658. }
  78659. else if (_this._leftLaserPointer) {
  78660. _this._leftLaserPointer.isVisible = false;
  78661. }
  78662. }
  78663. });
  78664. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  78665. if (!_this._pointerDownOnMeshAsked) {
  78666. if (stateObject.value > _this._padSensibilityUp) {
  78667. _this._selectionPointerDown();
  78668. }
  78669. }
  78670. else if (stateObject.value < _this._padSensibilityDown) {
  78671. _this._selectionPointerUp();
  78672. }
  78673. });
  78674. }
  78675. };
  78676. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  78677. if (webVRController === void 0) { webVRController = null; }
  78678. if (!this._teleportationRequestInitiated) {
  78679. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  78680. if (webVRController) {
  78681. // If laser pointer wasn't enabled yet
  78682. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  78683. this._leftLaserPointer.isVisible = true;
  78684. if (this._rightLaserPointer) {
  78685. this._rightLaserPointer.isVisible = false;
  78686. }
  78687. }
  78688. else if (this._displayLaserPointer && this._rightLaserPointer) {
  78689. this._rightLaserPointer.isVisible = true;
  78690. if (this._leftLaserPointer) {
  78691. this._leftLaserPointer.isVisible = false;
  78692. }
  78693. }
  78694. }
  78695. this._teleportationRequestInitiated = true;
  78696. }
  78697. }
  78698. else {
  78699. // Listening to the proper controller values changes to confirm teleportation
  78700. if (webVRController == null
  78701. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  78702. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  78703. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  78704. if (this._teleportationAllowed) {
  78705. this._teleportationAllowed = false;
  78706. this._teleportCamera();
  78707. }
  78708. this._teleportationRequestInitiated = false;
  78709. }
  78710. }
  78711. }
  78712. };
  78713. VRExperienceHelper.prototype._selectionPointerDown = function () {
  78714. this._pointerDownOnMeshAsked = true;
  78715. if (this._currentMeshSelected && this._currentHit) {
  78716. this._scene.simulatePointerDown(this._currentHit);
  78717. }
  78718. };
  78719. VRExperienceHelper.prototype._selectionPointerUp = function () {
  78720. if (this._currentMeshSelected && this._currentHit) {
  78721. this._scene.simulatePointerUp(this._currentHit);
  78722. }
  78723. this._pointerDownOnMeshAsked = false;
  78724. };
  78725. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  78726. // Only rotate when user is not currently selecting a teleportation location
  78727. if (this._teleportationRequestInitiated) {
  78728. return;
  78729. }
  78730. if (!this._rotationLeftAsked) {
  78731. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  78732. this._rotationLeftAsked = true;
  78733. if (this._rotationAllowed) {
  78734. this._rotateCamera(false);
  78735. }
  78736. }
  78737. }
  78738. else {
  78739. if (stateObject.x > -this._padSensibilityDown) {
  78740. this._rotationLeftAsked = false;
  78741. }
  78742. }
  78743. if (!this._rotationRightAsked) {
  78744. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  78745. this._rotationRightAsked = true;
  78746. if (this._rotationAllowed) {
  78747. this._rotateCamera(true);
  78748. }
  78749. }
  78750. }
  78751. else {
  78752. if (stateObject.x < this._padSensibilityDown) {
  78753. this._rotationRightAsked = false;
  78754. }
  78755. }
  78756. };
  78757. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  78758. // Only teleport backwards when user is not currently selecting a teleportation location
  78759. if (this._teleportationRequestInitiated) {
  78760. return;
  78761. }
  78762. // Teleport backwards
  78763. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  78764. if (!this._teleportationBackRequestInitiated) {
  78765. if (!this.currentVRCamera) {
  78766. return;
  78767. }
  78768. // Get rotation and position of the current camera
  78769. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  78770. var position = this.currentVRCamera.position;
  78771. // If the camera has device position, use that instead
  78772. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  78773. rotation = this.currentVRCamera.deviceRotationQuaternion;
  78774. position = this.currentVRCamera.devicePosition;
  78775. }
  78776. // Get matrix with only the y rotation of the device rotation
  78777. rotation.toEulerAnglesToRef(this._workingVector);
  78778. this._workingVector.z = 0;
  78779. this._workingVector.x = 0;
  78780. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  78781. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  78782. // Rotate backwards ray by device rotation to cast at the ground behind the user
  78783. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  78784. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  78785. var ray = new BABYLON.Ray(position, this._workingVector);
  78786. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  78787. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  78788. this._teleportCamera(hit.pickedPoint);
  78789. }
  78790. this._teleportationBackRequestInitiated = true;
  78791. }
  78792. }
  78793. else {
  78794. this._teleportationBackRequestInitiated = false;
  78795. }
  78796. };
  78797. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  78798. var _this = this;
  78799. var controllerMesh = webVRController.mesh;
  78800. if (controllerMesh) {
  78801. if (webVRController.hand === "left") {
  78802. if (!this._interactionsEnabledOnLeftController) {
  78803. this._enableInteractionOnController(webVRController);
  78804. }
  78805. this._teleportationEnabledOnLeftController = true;
  78806. }
  78807. else {
  78808. if (!this._interactionsEnabledOnRightController) {
  78809. this._enableInteractionOnController(webVRController);
  78810. }
  78811. this._teleportationEnabledOnRightController = true;
  78812. }
  78813. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78814. this._dpadPressed = false;
  78815. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  78816. _this._dpadPressed = stateObject.pressed;
  78817. if (!_this._dpadPressed) {
  78818. _this._rotationLeftAsked = false;
  78819. _this._rotationRightAsked = false;
  78820. _this._teleportationBackRequestInitiated = false;
  78821. }
  78822. });
  78823. }
  78824. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  78825. if (_this.teleportationEnabled) {
  78826. _this._checkTeleportBackwards(stateObject);
  78827. _this._checkTeleportWithRay(stateObject, webVRController);
  78828. }
  78829. _this._checkRotate(stateObject);
  78830. });
  78831. }
  78832. };
  78833. // Gaze support used to point to teleport or to interact with an object
  78834. VRExperienceHelper.prototype._createGazeTracker = function () {
  78835. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  78836. this._gazeTracker.bakeCurrentTransformIntoVertices();
  78837. this._gazeTracker.isPickable = false;
  78838. this._gazeTracker.isVisible = false;
  78839. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  78840. targetMat.specularColor = BABYLON.Color3.Black();
  78841. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  78842. targetMat.backFaceCulling = false;
  78843. this._gazeTracker.material = targetMat;
  78844. };
  78845. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  78846. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  78847. this._teleportationTarget.isPickable = false;
  78848. var length = 512;
  78849. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  78850. dynamicTexture.hasAlpha = true;
  78851. var context = dynamicTexture.getContext();
  78852. var centerX = length / 2;
  78853. var centerY = length / 2;
  78854. var radius = 200;
  78855. context.beginPath();
  78856. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  78857. context.fillStyle = this._teleportationFillColor;
  78858. context.fill();
  78859. context.lineWidth = 10;
  78860. context.strokeStyle = this._teleportationBorderColor;
  78861. context.stroke();
  78862. context.closePath();
  78863. dynamicTexture.update();
  78864. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  78865. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  78866. this._teleportationTarget.material = teleportationCircleMaterial;
  78867. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  78868. torus.isPickable = false;
  78869. torus.parent = this._teleportationTarget;
  78870. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  78871. var keys = [];
  78872. keys.push({
  78873. frame: 0,
  78874. value: 0
  78875. });
  78876. keys.push({
  78877. frame: 30,
  78878. value: 0.4
  78879. });
  78880. keys.push({
  78881. frame: 60,
  78882. value: 0
  78883. });
  78884. animationInnerCircle.setKeys(keys);
  78885. var easingFunction = new BABYLON.SineEase();
  78886. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78887. animationInnerCircle.setEasingFunction(easingFunction);
  78888. torus.animations = [];
  78889. torus.animations.push(animationInnerCircle);
  78890. this._scene.beginAnimation(torus, 0, 60, true);
  78891. this._hideTeleportationTarget();
  78892. };
  78893. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  78894. if (this._teleportationInitialized) {
  78895. this._teleportationTarget.isVisible = true;
  78896. if (this._isDefaultTeleportationTarget) {
  78897. this._teleportationTarget.getChildren()[0].isVisible = true;
  78898. }
  78899. }
  78900. };
  78901. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  78902. if (this._teleportationInitialized) {
  78903. this._teleportationTarget.isVisible = false;
  78904. if (this._isDefaultTeleportationTarget) {
  78905. this._teleportationTarget.getChildren()[0].isVisible = false;
  78906. }
  78907. }
  78908. };
  78909. VRExperienceHelper.prototype._rotateCamera = function (right) {
  78910. var _this = this;
  78911. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  78912. return;
  78913. }
  78914. if (right) {
  78915. this._rotationAngle++;
  78916. }
  78917. else {
  78918. this._rotationAngle--;
  78919. }
  78920. this.currentVRCamera.animations = [];
  78921. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  78922. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78923. var animationRotationKeys = [];
  78924. animationRotationKeys.push({
  78925. frame: 0,
  78926. value: this.currentVRCamera.rotationQuaternion
  78927. });
  78928. animationRotationKeys.push({
  78929. frame: 6,
  78930. value: target
  78931. });
  78932. animationRotation.setKeys(animationRotationKeys);
  78933. animationRotation.setEasingFunction(this._circleEase);
  78934. this.currentVRCamera.animations.push(animationRotation);
  78935. this._postProcessMove.animations = [];
  78936. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78937. var vignetteWeightKeys = [];
  78938. vignetteWeightKeys.push({
  78939. frame: 0,
  78940. value: 0
  78941. });
  78942. vignetteWeightKeys.push({
  78943. frame: 3,
  78944. value: 4
  78945. });
  78946. vignetteWeightKeys.push({
  78947. frame: 6,
  78948. value: 0
  78949. });
  78950. animationPP.setKeys(vignetteWeightKeys);
  78951. animationPP.setEasingFunction(this._circleEase);
  78952. this._postProcessMove.animations.push(animationPP);
  78953. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78954. var vignetteStretchKeys = [];
  78955. vignetteStretchKeys.push({
  78956. frame: 0,
  78957. value: 0
  78958. });
  78959. vignetteStretchKeys.push({
  78960. frame: 3,
  78961. value: 10
  78962. });
  78963. vignetteStretchKeys.push({
  78964. frame: 6,
  78965. value: 0
  78966. });
  78967. animationPP2.setKeys(vignetteStretchKeys);
  78968. animationPP2.setEasingFunction(this._circleEase);
  78969. this._postProcessMove.animations.push(animationPP2);
  78970. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  78971. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  78972. this._webVRCamera.attachPostProcess(this._postProcessMove);
  78973. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  78974. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  78975. });
  78976. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  78977. };
  78978. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  78979. if (hit.pickedPoint) {
  78980. this._teleportationAllowed = true;
  78981. if (this._teleportationRequestInitiated) {
  78982. this._displayTeleportationTarget();
  78983. }
  78984. else {
  78985. this._hideTeleportationTarget();
  78986. }
  78987. this._haloCenter.copyFrom(hit.pickedPoint);
  78988. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  78989. var pickNormal = hit.getNormal(true, false);
  78990. if (pickNormal) {
  78991. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  78992. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  78993. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  78994. }
  78995. this._teleportationTarget.position.y += 0.1;
  78996. }
  78997. };
  78998. VRExperienceHelper.prototype._teleportCamera = function (location) {
  78999. var _this = this;
  79000. if (location === void 0) { location = null; }
  79001. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79002. return;
  79003. }
  79004. if (!location) {
  79005. location = this._haloCenter;
  79006. }
  79007. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79008. // offset of the headset from the anchor.
  79009. if (this.webVRCamera.leftCamera) {
  79010. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79011. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79012. location.subtractToRef(this._workingVector, this._workingVector);
  79013. }
  79014. else {
  79015. this._workingVector.copyFrom(location);
  79016. }
  79017. // Add height to account for user's height offset
  79018. if (this.isInVRMode) {
  79019. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79020. }
  79021. else {
  79022. this._workingVector.y += this._defaultHeight;
  79023. }
  79024. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79025. // Create animation from the camera's position to the new location
  79026. this.currentVRCamera.animations = [];
  79027. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79028. var animationCameraTeleportationKeys = [{
  79029. frame: 0,
  79030. value: this.currentVRCamera.position
  79031. },
  79032. {
  79033. frame: 11,
  79034. value: this._workingVector
  79035. }
  79036. ];
  79037. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79038. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79039. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79040. this._postProcessMove.animations = [];
  79041. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79042. var vignetteWeightKeys = [];
  79043. vignetteWeightKeys.push({
  79044. frame: 0,
  79045. value: 0
  79046. });
  79047. vignetteWeightKeys.push({
  79048. frame: 5,
  79049. value: 8
  79050. });
  79051. vignetteWeightKeys.push({
  79052. frame: 11,
  79053. value: 0
  79054. });
  79055. animationPP.setKeys(vignetteWeightKeys);
  79056. this._postProcessMove.animations.push(animationPP);
  79057. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79058. var vignetteStretchKeys = [];
  79059. vignetteStretchKeys.push({
  79060. frame: 0,
  79061. value: 0
  79062. });
  79063. vignetteStretchKeys.push({
  79064. frame: 5,
  79065. value: 10
  79066. });
  79067. vignetteStretchKeys.push({
  79068. frame: 11,
  79069. value: 0
  79070. });
  79071. animationPP2.setKeys(vignetteStretchKeys);
  79072. this._postProcessMove.animations.push(animationPP2);
  79073. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79074. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79075. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79076. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79077. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79078. });
  79079. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79080. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79081. });
  79082. };
  79083. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79084. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79085. return;
  79086. }
  79087. var ray;
  79088. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79089. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79090. }
  79091. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79092. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79093. }
  79094. else {
  79095. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79096. }
  79097. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79098. // Moving the gazeTracker on the mesh face targetted
  79099. if (hit && hit.pickedPoint) {
  79100. if (this._displayGaze) {
  79101. var multiplier = 1;
  79102. this._gazeTracker.isVisible = true;
  79103. if (this._isActionableMesh) {
  79104. multiplier = 3;
  79105. }
  79106. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79107. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79108. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79109. var pickNormal = hit.getNormal();
  79110. // To avoid z-fighting
  79111. var deltaFighting = 0.002;
  79112. if (pickNormal) {
  79113. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79114. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79115. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79116. }
  79117. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79118. if (this._gazeTracker.position.x < 0) {
  79119. this._gazeTracker.position.x += deltaFighting;
  79120. }
  79121. else {
  79122. this._gazeTracker.position.x -= deltaFighting;
  79123. }
  79124. if (this._gazeTracker.position.y < 0) {
  79125. this._gazeTracker.position.y += deltaFighting;
  79126. }
  79127. else {
  79128. this._gazeTracker.position.y -= deltaFighting;
  79129. }
  79130. if (this._gazeTracker.position.z < 0) {
  79131. this._gazeTracker.position.z += deltaFighting;
  79132. }
  79133. else {
  79134. this._gazeTracker.position.z -= deltaFighting;
  79135. }
  79136. }
  79137. // Changing the size of the laser pointer based on the distance from the targetted point
  79138. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79139. this._rightLaserPointer.scaling.y = hit.distance;
  79140. this._rightLaserPointer.position.z = -hit.distance / 2;
  79141. }
  79142. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79143. this._leftLaserPointer.scaling.y = hit.distance;
  79144. this._leftLaserPointer.position.z = -hit.distance / 2;
  79145. }
  79146. }
  79147. else {
  79148. this._gazeTracker.isVisible = false;
  79149. }
  79150. if (hit && hit.pickedMesh) {
  79151. this._currentHit = hit;
  79152. if (this._pointerDownOnMeshAsked) {
  79153. this._scene.simulatePointerMove(this._currentHit);
  79154. }
  79155. // The object selected is the floor, we're in a teleportation scenario
  79156. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79157. // Moving the teleportation area to this targetted point
  79158. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79159. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79160. this._notifySelectedMeshUnselected();
  79161. }
  79162. this._currentMeshSelected = null;
  79163. this._moveTeleportationSelectorTo(hit);
  79164. return;
  79165. }
  79166. // If not, we're in a selection scenario
  79167. this._hideTeleportationTarget();
  79168. this._teleportationAllowed = false;
  79169. if (hit.pickedMesh !== this._currentMeshSelected) {
  79170. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79171. this.onNewMeshPicked.notifyObservers(hit);
  79172. this._currentMeshSelected = hit.pickedMesh;
  79173. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79174. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79175. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79176. this._isActionableMesh = true;
  79177. }
  79178. else {
  79179. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79180. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79181. this._isActionableMesh = false;
  79182. }
  79183. try {
  79184. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79185. }
  79186. catch (err) {
  79187. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79188. }
  79189. }
  79190. else {
  79191. this._notifySelectedMeshUnselected();
  79192. this._currentMeshSelected = null;
  79193. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79194. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79195. }
  79196. }
  79197. }
  79198. else {
  79199. this._currentHit = null;
  79200. this._notifySelectedMeshUnselected();
  79201. this._currentMeshSelected = null;
  79202. this._teleportationAllowed = false;
  79203. this._hideTeleportationTarget();
  79204. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79205. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79206. }
  79207. };
  79208. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  79209. if (this._currentMeshSelected) {
  79210. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  79211. }
  79212. };
  79213. /**
  79214. * Sets the color of the laser ray from the vr controllers.
  79215. * @param color new color for the ray.
  79216. */
  79217. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  79218. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  79219. this._leftLaserPointer.material.emissiveColor = color;
  79220. }
  79221. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  79222. this._rightLaserPointer.material.emissiveColor = color;
  79223. }
  79224. };
  79225. /**
  79226. * Sets the color of the ray from the vr headsets gaze.
  79227. * @param color new color for the ray.
  79228. */
  79229. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  79230. if (this._gazeTracker.material) {
  79231. this._gazeTracker.material.emissiveColor = color;
  79232. }
  79233. };
  79234. /**
  79235. * Exits VR and disposes of the vr experience helper
  79236. */
  79237. VRExperienceHelper.prototype.dispose = function () {
  79238. if (this.isInVRMode) {
  79239. this.exitVR();
  79240. }
  79241. if (this._passProcessMove) {
  79242. this._passProcessMove.dispose();
  79243. }
  79244. if (this._postProcessMove) {
  79245. this._postProcessMove.dispose();
  79246. }
  79247. if (this._webVRCamera) {
  79248. this._webVRCamera.dispose();
  79249. }
  79250. if (this._vrDeviceOrientationCamera) {
  79251. this._vrDeviceOrientationCamera.dispose();
  79252. }
  79253. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  79254. document.body.removeChild(this._btnVR);
  79255. }
  79256. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  79257. this._deviceOrientationCamera.dispose();
  79258. }
  79259. if (this._gazeTracker) {
  79260. this._gazeTracker.dispose();
  79261. }
  79262. if (this._teleportationTarget) {
  79263. this._teleportationTarget.dispose();
  79264. }
  79265. this._floorMeshesCollection = [];
  79266. document.removeEventListener("keydown", this._onKeyDown);
  79267. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79268. window.removeEventListener("resize", this._onResize);
  79269. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  79270. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  79271. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  79272. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  79273. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  79274. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  79275. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  79276. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79277. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  79278. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  79279. this._scene.unregisterBeforeRender(this.beforeRender);
  79280. };
  79281. /**
  79282. * Gets the name of the VRExperienceHelper class
  79283. * @returns "VRExperienceHelper"
  79284. */
  79285. VRExperienceHelper.prototype.getClassName = function () {
  79286. return "VRExperienceHelper";
  79287. };
  79288. return VRExperienceHelper;
  79289. }());
  79290. BABYLON.VRExperienceHelper = VRExperienceHelper;
  79291. })(BABYLON || (BABYLON = {}));
  79292. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  79293. // Mainly based on these 2 articles :
  79294. // 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
  79295. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  79296. var BABYLON;
  79297. (function (BABYLON) {
  79298. var JoystickAxis;
  79299. (function (JoystickAxis) {
  79300. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  79301. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  79302. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  79303. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  79304. var VirtualJoystick = /** @class */ (function () {
  79305. function VirtualJoystick(leftJoystick) {
  79306. var _this = this;
  79307. if (leftJoystick) {
  79308. this._leftJoystick = true;
  79309. }
  79310. else {
  79311. this._leftJoystick = false;
  79312. }
  79313. VirtualJoystick._globalJoystickIndex++;
  79314. // By default left & right arrow keys are moving the X
  79315. // and up & down keys are moving the Y
  79316. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  79317. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  79318. this.reverseLeftRight = false;
  79319. this.reverseUpDown = false;
  79320. // collections of pointers
  79321. this._touches = new BABYLON.StringDictionary();
  79322. this.deltaPosition = BABYLON.Vector3.Zero();
  79323. this._joystickSensibility = 25;
  79324. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79325. this._onResize = function (evt) {
  79326. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79327. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79328. if (VirtualJoystick.vjCanvas) {
  79329. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  79330. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  79331. }
  79332. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  79333. };
  79334. // injecting a canvas element on top of the canvas 3D game
  79335. if (!VirtualJoystick.vjCanvas) {
  79336. window.addEventListener("resize", this._onResize, false);
  79337. VirtualJoystick.vjCanvas = document.createElement("canvas");
  79338. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79339. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79340. VirtualJoystick.vjCanvas.width = window.innerWidth;
  79341. VirtualJoystick.vjCanvas.height = window.innerHeight;
  79342. VirtualJoystick.vjCanvas.style.width = "100%";
  79343. VirtualJoystick.vjCanvas.style.height = "100%";
  79344. VirtualJoystick.vjCanvas.style.position = "absolute";
  79345. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  79346. VirtualJoystick.vjCanvas.style.top = "0px";
  79347. VirtualJoystick.vjCanvas.style.left = "0px";
  79348. VirtualJoystick.vjCanvas.style.zIndex = "5";
  79349. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  79350. // Support for jQuery PEP polyfill
  79351. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  79352. var context = VirtualJoystick.vjCanvas.getContext('2d');
  79353. if (!context) {
  79354. throw new Error("Unable to create canvas for virtual joystick");
  79355. }
  79356. VirtualJoystick.vjCanvasContext = context;
  79357. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  79358. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  79359. document.body.appendChild(VirtualJoystick.vjCanvas);
  79360. }
  79361. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  79362. this.pressed = false;
  79363. // default joystick color
  79364. this._joystickColor = "cyan";
  79365. this._joystickPointerID = -1;
  79366. // current joystick position
  79367. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  79368. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  79369. // origin joystick position
  79370. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  79371. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  79372. this._onPointerDownHandlerRef = function (evt) {
  79373. _this._onPointerDown(evt);
  79374. };
  79375. this._onPointerMoveHandlerRef = function (evt) {
  79376. _this._onPointerMove(evt);
  79377. };
  79378. this._onPointerUpHandlerRef = function (evt) {
  79379. _this._onPointerUp(evt);
  79380. };
  79381. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  79382. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  79383. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  79384. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  79385. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  79386. evt.preventDefault(); // Disables system menu
  79387. }, false);
  79388. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  79389. }
  79390. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  79391. this._joystickSensibility = newJoystickSensibility;
  79392. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79393. };
  79394. VirtualJoystick.prototype._onPointerDown = function (e) {
  79395. var positionOnScreenCondition;
  79396. e.preventDefault();
  79397. if (this._leftJoystick === true) {
  79398. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  79399. }
  79400. else {
  79401. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  79402. }
  79403. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  79404. // First contact will be dedicated to the virtual joystick
  79405. this._joystickPointerID = e.pointerId;
  79406. this._joystickPointerStartPos.x = e.clientX;
  79407. this._joystickPointerStartPos.y = e.clientY;
  79408. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  79409. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  79410. this._deltaJoystickVector.x = 0;
  79411. this._deltaJoystickVector.y = 0;
  79412. this.pressed = true;
  79413. this._touches.add(e.pointerId.toString(), e);
  79414. }
  79415. else {
  79416. // You can only trigger the action buttons with a joystick declared
  79417. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  79418. this._action();
  79419. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  79420. }
  79421. }
  79422. };
  79423. VirtualJoystick.prototype._onPointerMove = function (e) {
  79424. // If the current pointer is the one associated to the joystick (first touch contact)
  79425. if (this._joystickPointerID == e.pointerId) {
  79426. this._joystickPointerPos.x = e.clientX;
  79427. this._joystickPointerPos.y = e.clientY;
  79428. this._deltaJoystickVector = this._joystickPointerPos.clone();
  79429. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  79430. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  79431. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  79432. switch (this._axisTargetedByLeftAndRight) {
  79433. case JoystickAxis.X:
  79434. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  79435. break;
  79436. case JoystickAxis.Y:
  79437. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  79438. break;
  79439. case JoystickAxis.Z:
  79440. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  79441. break;
  79442. }
  79443. var directionUpDown = this.reverseUpDown ? 1 : -1;
  79444. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  79445. switch (this._axisTargetedByUpAndDown) {
  79446. case JoystickAxis.X:
  79447. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  79448. break;
  79449. case JoystickAxis.Y:
  79450. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  79451. break;
  79452. case JoystickAxis.Z:
  79453. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  79454. break;
  79455. }
  79456. }
  79457. else {
  79458. var data = this._touches.get(e.pointerId.toString());
  79459. if (data) {
  79460. data.x = e.clientX;
  79461. data.y = e.clientY;
  79462. }
  79463. }
  79464. };
  79465. VirtualJoystick.prototype._onPointerUp = function (e) {
  79466. if (this._joystickPointerID == e.pointerId) {
  79467. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  79468. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  79469. this._joystickPointerID = -1;
  79470. this.pressed = false;
  79471. }
  79472. else {
  79473. var touch = this._touches.get(e.pointerId.toString());
  79474. if (touch) {
  79475. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  79476. }
  79477. }
  79478. this._deltaJoystickVector.x = 0;
  79479. this._deltaJoystickVector.y = 0;
  79480. this._touches.remove(e.pointerId.toString());
  79481. };
  79482. /**
  79483. * Change the color of the virtual joystick
  79484. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  79485. */
  79486. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  79487. this._joystickColor = newColor;
  79488. };
  79489. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  79490. this._action = action;
  79491. };
  79492. // Define which axis you'd like to control for left & right
  79493. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  79494. switch (axis) {
  79495. case JoystickAxis.X:
  79496. case JoystickAxis.Y:
  79497. case JoystickAxis.Z:
  79498. this._axisTargetedByLeftAndRight = axis;
  79499. break;
  79500. default:
  79501. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  79502. break;
  79503. }
  79504. };
  79505. // Define which axis you'd like to control for up & down
  79506. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  79507. switch (axis) {
  79508. case JoystickAxis.X:
  79509. case JoystickAxis.Y:
  79510. case JoystickAxis.Z:
  79511. this._axisTargetedByUpAndDown = axis;
  79512. break;
  79513. default:
  79514. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  79515. break;
  79516. }
  79517. };
  79518. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  79519. var _this = this;
  79520. if (this.pressed) {
  79521. this._touches.forEach(function (key, touch) {
  79522. if (touch.pointerId === _this._joystickPointerID) {
  79523. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  79524. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  79525. VirtualJoystick.vjCanvasContext.beginPath();
  79526. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  79527. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  79528. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  79529. VirtualJoystick.vjCanvasContext.stroke();
  79530. VirtualJoystick.vjCanvasContext.closePath();
  79531. VirtualJoystick.vjCanvasContext.beginPath();
  79532. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  79533. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  79534. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  79535. VirtualJoystick.vjCanvasContext.stroke();
  79536. VirtualJoystick.vjCanvasContext.closePath();
  79537. VirtualJoystick.vjCanvasContext.beginPath();
  79538. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  79539. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  79540. VirtualJoystick.vjCanvasContext.stroke();
  79541. VirtualJoystick.vjCanvasContext.closePath();
  79542. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  79543. }
  79544. else {
  79545. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  79546. VirtualJoystick.vjCanvasContext.beginPath();
  79547. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  79548. VirtualJoystick.vjCanvasContext.beginPath();
  79549. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  79550. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  79551. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  79552. VirtualJoystick.vjCanvasContext.stroke();
  79553. VirtualJoystick.vjCanvasContext.closePath();
  79554. touch.prevX = touch.x;
  79555. touch.prevY = touch.y;
  79556. }
  79557. ;
  79558. });
  79559. }
  79560. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  79561. };
  79562. VirtualJoystick.prototype.releaseCanvas = function () {
  79563. if (VirtualJoystick.vjCanvas) {
  79564. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  79565. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  79566. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  79567. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  79568. window.removeEventListener("resize", this._onResize);
  79569. document.body.removeChild(VirtualJoystick.vjCanvas);
  79570. VirtualJoystick.vjCanvas = null;
  79571. }
  79572. };
  79573. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  79574. VirtualJoystick._globalJoystickIndex = 0;
  79575. return VirtualJoystick;
  79576. }());
  79577. BABYLON.VirtualJoystick = VirtualJoystick;
  79578. })(BABYLON || (BABYLON = {}));
  79579. //# sourceMappingURL=babylon.virtualJoystick.js.map
  79580. var BABYLON;
  79581. (function (BABYLON) {
  79582. // We're mainly based on the logic defined into the FreeCamera code
  79583. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  79584. __extends(VirtualJoysticksCamera, _super);
  79585. function VirtualJoysticksCamera(name, position, scene) {
  79586. var _this = _super.call(this, name, position, scene) || this;
  79587. _this.inputs.addVirtualJoystick();
  79588. return _this;
  79589. }
  79590. VirtualJoysticksCamera.prototype.getClassName = function () {
  79591. return "VirtualJoysticksCamera";
  79592. };
  79593. return VirtualJoysticksCamera;
  79594. }(BABYLON.FreeCamera));
  79595. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  79596. })(BABYLON || (BABYLON = {}));
  79597. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  79598. var BABYLON;
  79599. (function (BABYLON) {
  79600. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  79601. function FreeCameraVirtualJoystickInput() {
  79602. }
  79603. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  79604. return this._leftjoystick;
  79605. };
  79606. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  79607. return this._rightjoystick;
  79608. };
  79609. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  79610. if (this._leftjoystick) {
  79611. var camera = this.camera;
  79612. var speed = camera._computeLocalCameraSpeed() * 50;
  79613. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  79614. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  79615. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  79616. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  79617. if (!this._leftjoystick.pressed) {
  79618. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  79619. }
  79620. if (!this._rightjoystick.pressed) {
  79621. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  79622. }
  79623. }
  79624. };
  79625. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  79626. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  79627. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  79628. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  79629. this._leftjoystick.setJoystickSensibility(0.15);
  79630. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  79631. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  79632. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  79633. this._rightjoystick.reverseUpDown = true;
  79634. this._rightjoystick.setJoystickSensibility(0.05);
  79635. this._rightjoystick.setJoystickColor("yellow");
  79636. };
  79637. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  79638. this._leftjoystick.releaseCanvas();
  79639. this._rightjoystick.releaseCanvas();
  79640. };
  79641. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  79642. return "FreeCameraVirtualJoystickInput";
  79643. };
  79644. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  79645. return "virtualJoystick";
  79646. };
  79647. return FreeCameraVirtualJoystickInput;
  79648. }());
  79649. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  79650. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  79651. })(BABYLON || (BABYLON = {}));
  79652. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  79653. var BABYLON;
  79654. (function (BABYLON) {
  79655. var SimplificationSettings = /** @class */ (function () {
  79656. function SimplificationSettings(quality, distance, optimizeMesh) {
  79657. this.quality = quality;
  79658. this.distance = distance;
  79659. this.optimizeMesh = optimizeMesh;
  79660. }
  79661. return SimplificationSettings;
  79662. }());
  79663. BABYLON.SimplificationSettings = SimplificationSettings;
  79664. var SimplificationQueue = /** @class */ (function () {
  79665. function SimplificationQueue() {
  79666. this.running = false;
  79667. this._simplificationArray = [];
  79668. }
  79669. SimplificationQueue.prototype.addTask = function (task) {
  79670. this._simplificationArray.push(task);
  79671. };
  79672. SimplificationQueue.prototype.executeNext = function () {
  79673. var task = this._simplificationArray.pop();
  79674. if (task) {
  79675. this.running = true;
  79676. this.runSimplification(task);
  79677. }
  79678. else {
  79679. this.running = false;
  79680. }
  79681. };
  79682. SimplificationQueue.prototype.runSimplification = function (task) {
  79683. var _this = this;
  79684. if (task.parallelProcessing) {
  79685. //parallel simplifier
  79686. task.settings.forEach(function (setting) {
  79687. var simplifier = _this.getSimplifier(task);
  79688. simplifier.simplify(setting, function (newMesh) {
  79689. task.mesh.addLODLevel(setting.distance, newMesh);
  79690. newMesh.isVisible = true;
  79691. //check if it is the last
  79692. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  79693. //all done, run the success callback.
  79694. task.successCallback();
  79695. }
  79696. _this.executeNext();
  79697. });
  79698. });
  79699. }
  79700. else {
  79701. //single simplifier.
  79702. var simplifier = this.getSimplifier(task);
  79703. var runDecimation = function (setting, callback) {
  79704. simplifier.simplify(setting, function (newMesh) {
  79705. task.mesh.addLODLevel(setting.distance, newMesh);
  79706. newMesh.isVisible = true;
  79707. //run the next quality level
  79708. callback();
  79709. });
  79710. };
  79711. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  79712. runDecimation(task.settings[loop.index], function () {
  79713. loop.executeNext();
  79714. });
  79715. }, function () {
  79716. //execution ended, run the success callback.
  79717. if (task.successCallback) {
  79718. task.successCallback();
  79719. }
  79720. _this.executeNext();
  79721. });
  79722. }
  79723. };
  79724. SimplificationQueue.prototype.getSimplifier = function (task) {
  79725. switch (task.simplificationType) {
  79726. case SimplificationType.QUADRATIC:
  79727. default:
  79728. return new QuadraticErrorSimplification(task.mesh);
  79729. }
  79730. };
  79731. return SimplificationQueue;
  79732. }());
  79733. BABYLON.SimplificationQueue = SimplificationQueue;
  79734. /**
  79735. * The implemented types of simplification.
  79736. * At the moment only Quadratic Error Decimation is implemented.
  79737. */
  79738. var SimplificationType;
  79739. (function (SimplificationType) {
  79740. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  79741. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  79742. var DecimationTriangle = /** @class */ (function () {
  79743. function DecimationTriangle(vertices) {
  79744. this.vertices = vertices;
  79745. this.error = new Array(4);
  79746. this.deleted = false;
  79747. this.isDirty = false;
  79748. this.deletePending = false;
  79749. this.borderFactor = 0;
  79750. }
  79751. return DecimationTriangle;
  79752. }());
  79753. BABYLON.DecimationTriangle = DecimationTriangle;
  79754. var DecimationVertex = /** @class */ (function () {
  79755. function DecimationVertex(position, id) {
  79756. this.position = position;
  79757. this.id = id;
  79758. this.isBorder = true;
  79759. this.q = new QuadraticMatrix();
  79760. this.triangleCount = 0;
  79761. this.triangleStart = 0;
  79762. this.originalOffsets = [];
  79763. }
  79764. DecimationVertex.prototype.updatePosition = function (newPosition) {
  79765. this.position.copyFrom(newPosition);
  79766. };
  79767. return DecimationVertex;
  79768. }());
  79769. BABYLON.DecimationVertex = DecimationVertex;
  79770. var QuadraticMatrix = /** @class */ (function () {
  79771. function QuadraticMatrix(data) {
  79772. this.data = new Array(10);
  79773. for (var i = 0; i < 10; ++i) {
  79774. if (data && data[i]) {
  79775. this.data[i] = data[i];
  79776. }
  79777. else {
  79778. this.data[i] = 0;
  79779. }
  79780. }
  79781. }
  79782. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  79783. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  79784. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  79785. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  79786. return det;
  79787. };
  79788. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  79789. for (var i = 0; i < 10; ++i) {
  79790. this.data[i] += matrix.data[i];
  79791. }
  79792. };
  79793. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  79794. for (var i = 0; i < 10; ++i) {
  79795. this.data[i] += data[i];
  79796. }
  79797. };
  79798. QuadraticMatrix.prototype.add = function (matrix) {
  79799. var m = new QuadraticMatrix();
  79800. for (var i = 0; i < 10; ++i) {
  79801. m.data[i] = this.data[i] + matrix.data[i];
  79802. }
  79803. return m;
  79804. };
  79805. QuadraticMatrix.FromData = function (a, b, c, d) {
  79806. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  79807. };
  79808. //returning an array to avoid garbage collection
  79809. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  79810. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  79811. };
  79812. return QuadraticMatrix;
  79813. }());
  79814. BABYLON.QuadraticMatrix = QuadraticMatrix;
  79815. var Reference = /** @class */ (function () {
  79816. function Reference(vertexId, triangleId) {
  79817. this.vertexId = vertexId;
  79818. this.triangleId = triangleId;
  79819. }
  79820. return Reference;
  79821. }());
  79822. BABYLON.Reference = Reference;
  79823. /**
  79824. * An implementation of the Quadratic Error simplification algorithm.
  79825. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  79826. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  79827. * @author RaananW
  79828. */
  79829. var QuadraticErrorSimplification = /** @class */ (function () {
  79830. function QuadraticErrorSimplification(_mesh) {
  79831. this._mesh = _mesh;
  79832. this.syncIterations = 5000;
  79833. this.aggressiveness = 7;
  79834. this.decimationIterations = 100;
  79835. this.boundingBoxEpsilon = BABYLON.Epsilon;
  79836. }
  79837. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  79838. var _this = this;
  79839. this.initDecimatedMesh();
  79840. //iterating through the submeshes array, one after the other.
  79841. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  79842. _this.initWithMesh(loop.index, function () {
  79843. _this.runDecimation(settings, loop.index, function () {
  79844. loop.executeNext();
  79845. });
  79846. }, settings.optimizeMesh);
  79847. }, function () {
  79848. setTimeout(function () {
  79849. successCallback(_this._reconstructedMesh);
  79850. }, 0);
  79851. });
  79852. };
  79853. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  79854. var _this = this;
  79855. var targetCount = ~~(this.triangles.length * settings.quality);
  79856. var deletedTriangles = 0;
  79857. var triangleCount = this.triangles.length;
  79858. var iterationFunction = function (iteration, callback) {
  79859. setTimeout(function () {
  79860. if (iteration % 5 === 0) {
  79861. _this.updateMesh(iteration === 0);
  79862. }
  79863. for (var i = 0; i < _this.triangles.length; ++i) {
  79864. _this.triangles[i].isDirty = false;
  79865. }
  79866. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  79867. var trianglesIterator = function (i) {
  79868. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  79869. var t = _this.triangles[tIdx];
  79870. if (!t)
  79871. return;
  79872. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  79873. return;
  79874. }
  79875. for (var j = 0; j < 3; ++j) {
  79876. if (t.error[j] < threshold) {
  79877. var deleted0 = [];
  79878. var deleted1 = [];
  79879. var v0 = t.vertices[j];
  79880. var v1 = t.vertices[(j + 1) % 3];
  79881. if (v0.isBorder || v1.isBorder)
  79882. continue;
  79883. var p = BABYLON.Vector3.Zero();
  79884. var n = BABYLON.Vector3.Zero();
  79885. var uv = BABYLON.Vector2.Zero();
  79886. var color = new BABYLON.Color4(0, 0, 0, 1);
  79887. _this.calculateError(v0, v1, p, n, uv, color);
  79888. var delTr = new Array();
  79889. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  79890. continue;
  79891. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  79892. continue;
  79893. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  79894. continue;
  79895. var uniqueArray = new Array();
  79896. delTr.forEach(function (deletedT) {
  79897. if (uniqueArray.indexOf(deletedT) === -1) {
  79898. deletedT.deletePending = true;
  79899. uniqueArray.push(deletedT);
  79900. }
  79901. });
  79902. if (uniqueArray.length % 2 !== 0) {
  79903. continue;
  79904. }
  79905. v0.q = v1.q.add(v0.q);
  79906. v0.updatePosition(p);
  79907. var tStart = _this.references.length;
  79908. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  79909. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  79910. var tCount = _this.references.length - tStart;
  79911. if (tCount <= v0.triangleCount) {
  79912. if (tCount) {
  79913. for (var c = 0; c < tCount; c++) {
  79914. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  79915. }
  79916. }
  79917. }
  79918. else {
  79919. v0.triangleStart = tStart;
  79920. }
  79921. v0.triangleCount = tCount;
  79922. break;
  79923. }
  79924. }
  79925. };
  79926. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  79927. }, 0);
  79928. };
  79929. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  79930. if (triangleCount - deletedTriangles <= targetCount)
  79931. loop.breakLoop();
  79932. else {
  79933. iterationFunction(loop.index, function () {
  79934. loop.executeNext();
  79935. });
  79936. }
  79937. }, function () {
  79938. setTimeout(function () {
  79939. //reconstruct this part of the mesh
  79940. _this.reconstructMesh(submeshIndex);
  79941. successCallback();
  79942. }, 0);
  79943. });
  79944. };
  79945. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  79946. var _this = this;
  79947. this.vertices = [];
  79948. this.triangles = [];
  79949. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  79950. var indices = this._mesh.getIndices();
  79951. var submesh = this._mesh.subMeshes[submeshIndex];
  79952. var findInVertices = function (positionToSearch) {
  79953. if (optimizeMesh) {
  79954. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  79955. if (_this.vertices[ii].position.equals(positionToSearch)) {
  79956. return _this.vertices[ii];
  79957. }
  79958. }
  79959. }
  79960. return null;
  79961. };
  79962. var vertexReferences = [];
  79963. var vertexInit = function (i) {
  79964. if (!positionData) {
  79965. return;
  79966. }
  79967. var offset = i + submesh.verticesStart;
  79968. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  79969. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  79970. vertex.originalOffsets.push(offset);
  79971. if (vertex.id === _this.vertices.length) {
  79972. _this.vertices.push(vertex);
  79973. }
  79974. vertexReferences.push(vertex.id);
  79975. };
  79976. //var totalVertices = mesh.getTotalVertices();
  79977. var totalVertices = submesh.verticesCount;
  79978. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  79979. var indicesInit = function (i) {
  79980. if (!indices) {
  79981. return;
  79982. }
  79983. var offset = (submesh.indexStart / 3) + i;
  79984. var pos = (offset * 3);
  79985. var i0 = indices[pos + 0];
  79986. var i1 = indices[pos + 1];
  79987. var i2 = indices[pos + 2];
  79988. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  79989. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  79990. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  79991. var triangle = new DecimationTriangle([v0, v1, v2]);
  79992. triangle.originalOffset = pos;
  79993. _this.triangles.push(triangle);
  79994. };
  79995. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  79996. _this.init(callback);
  79997. });
  79998. });
  79999. };
  80000. QuadraticErrorSimplification.prototype.init = function (callback) {
  80001. var _this = this;
  80002. var triangleInit1 = function (i) {
  80003. var t = _this.triangles[i];
  80004. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80005. for (var j = 0; j < 3; j++) {
  80006. 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))));
  80007. }
  80008. };
  80009. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80010. var triangleInit2 = function (i) {
  80011. var t = _this.triangles[i];
  80012. for (var j = 0; j < 3; ++j) {
  80013. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80014. }
  80015. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80016. };
  80017. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80018. callback();
  80019. });
  80020. });
  80021. };
  80022. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80023. var newTriangles = [];
  80024. var i;
  80025. for (i = 0; i < this.vertices.length; ++i) {
  80026. this.vertices[i].triangleCount = 0;
  80027. }
  80028. var t;
  80029. var j;
  80030. for (i = 0; i < this.triangles.length; ++i) {
  80031. if (!this.triangles[i].deleted) {
  80032. t = this.triangles[i];
  80033. for (j = 0; j < 3; ++j) {
  80034. t.vertices[j].triangleCount = 1;
  80035. }
  80036. newTriangles.push(t);
  80037. }
  80038. }
  80039. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80040. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80041. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80042. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80043. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80044. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80045. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80046. var vertexCount = 0;
  80047. for (i = 0; i < this.vertices.length; ++i) {
  80048. var vertex = this.vertices[i];
  80049. vertex.id = vertexCount;
  80050. if (vertex.triangleCount) {
  80051. vertex.originalOffsets.forEach(function (originalOffset) {
  80052. if (!normalData) {
  80053. return;
  80054. }
  80055. newPositionData.push(vertex.position.x);
  80056. newPositionData.push(vertex.position.y);
  80057. newPositionData.push(vertex.position.z);
  80058. newNormalData.push(normalData[originalOffset * 3]);
  80059. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80060. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80061. if (uvs && uvs.length) {
  80062. newUVsData.push(uvs[(originalOffset * 2)]);
  80063. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80064. }
  80065. else if (colorsData && colorsData.length) {
  80066. newColorsData.push(colorsData[(originalOffset * 4)]);
  80067. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80068. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80069. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80070. }
  80071. ++vertexCount;
  80072. });
  80073. }
  80074. }
  80075. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80076. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80077. var submeshesArray = this._reconstructedMesh.subMeshes;
  80078. this._reconstructedMesh.subMeshes = [];
  80079. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80080. var originalIndices = this._mesh.getIndices();
  80081. for (i = 0; i < newTriangles.length; ++i) {
  80082. t = newTriangles[i]; //now get the new referencing point for each vertex
  80083. [0, 1, 2].forEach(function (idx) {
  80084. var id = originalIndices[t.originalOffset + idx];
  80085. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80086. if (offset < 0)
  80087. offset = 0;
  80088. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80089. });
  80090. }
  80091. //overwriting the old vertex buffers and indices.
  80092. this._reconstructedMesh.setIndices(newIndicesArray);
  80093. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80094. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80095. if (newUVsData.length > 0)
  80096. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80097. if (newColorsData.length > 0)
  80098. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80099. //create submesh
  80100. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80101. if (submeshIndex > 0) {
  80102. this._reconstructedMesh.subMeshes = [];
  80103. submeshesArray.forEach(function (submesh) {
  80104. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80105. });
  80106. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80107. }
  80108. };
  80109. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80110. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80111. this._reconstructedMesh.material = this._mesh.material;
  80112. this._reconstructedMesh.parent = this._mesh.parent;
  80113. this._reconstructedMesh.isVisible = false;
  80114. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80115. };
  80116. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80117. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80118. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80119. if (t.deleted)
  80120. continue;
  80121. var s = this.references[vertex1.triangleStart + i].vertexId;
  80122. var v1 = t.vertices[(s + 1) % 3];
  80123. var v2 = t.vertices[(s + 2) % 3];
  80124. if ((v1 === vertex2 || v2 === vertex2)) {
  80125. deletedArray[i] = true;
  80126. delTr.push(t);
  80127. continue;
  80128. }
  80129. var d1 = v1.position.subtract(point);
  80130. d1 = d1.normalize();
  80131. var d2 = v2.position.subtract(point);
  80132. d2 = d2.normalize();
  80133. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80134. return true;
  80135. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80136. deletedArray[i] = false;
  80137. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80138. return true;
  80139. }
  80140. return false;
  80141. };
  80142. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80143. var newDeleted = deletedTriangles;
  80144. for (var i = 0; i < vertex.triangleCount; ++i) {
  80145. var ref = this.references[vertex.triangleStart + i];
  80146. var t = this.triangles[ref.triangleId];
  80147. if (t.deleted)
  80148. continue;
  80149. if (deletedArray[i] && t.deletePending) {
  80150. t.deleted = true;
  80151. newDeleted++;
  80152. continue;
  80153. }
  80154. t.vertices[ref.vertexId] = origVertex;
  80155. t.isDirty = true;
  80156. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80157. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80158. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80159. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80160. this.references.push(ref);
  80161. }
  80162. return newDeleted;
  80163. };
  80164. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80165. for (var i = 0; i < this.vertices.length; ++i) {
  80166. var vCount = [];
  80167. var vId = [];
  80168. var v = this.vertices[i];
  80169. var j;
  80170. for (j = 0; j < v.triangleCount; ++j) {
  80171. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80172. for (var ii = 0; ii < 3; ii++) {
  80173. var ofs = 0;
  80174. var vv = triangle.vertices[ii];
  80175. while (ofs < vCount.length) {
  80176. if (vId[ofs] === vv.id)
  80177. break;
  80178. ++ofs;
  80179. }
  80180. if (ofs === vCount.length) {
  80181. vCount.push(1);
  80182. vId.push(vv.id);
  80183. }
  80184. else {
  80185. vCount[ofs]++;
  80186. }
  80187. }
  80188. }
  80189. for (j = 0; j < vCount.length; ++j) {
  80190. if (vCount[j] === 1) {
  80191. this.vertices[vId[j]].isBorder = true;
  80192. }
  80193. else {
  80194. this.vertices[vId[j]].isBorder = false;
  80195. }
  80196. }
  80197. }
  80198. };
  80199. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80200. if (identifyBorders === void 0) { identifyBorders = false; }
  80201. var i;
  80202. if (!identifyBorders) {
  80203. var newTrianglesVector = [];
  80204. for (i = 0; i < this.triangles.length; ++i) {
  80205. if (!this.triangles[i].deleted) {
  80206. newTrianglesVector.push(this.triangles[i]);
  80207. }
  80208. }
  80209. this.triangles = newTrianglesVector;
  80210. }
  80211. for (i = 0; i < this.vertices.length; ++i) {
  80212. this.vertices[i].triangleCount = 0;
  80213. this.vertices[i].triangleStart = 0;
  80214. }
  80215. var t;
  80216. var j;
  80217. var v;
  80218. for (i = 0; i < this.triangles.length; ++i) {
  80219. t = this.triangles[i];
  80220. for (j = 0; j < 3; ++j) {
  80221. v = t.vertices[j];
  80222. v.triangleCount++;
  80223. }
  80224. }
  80225. var tStart = 0;
  80226. for (i = 0; i < this.vertices.length; ++i) {
  80227. this.vertices[i].triangleStart = tStart;
  80228. tStart += this.vertices[i].triangleCount;
  80229. this.vertices[i].triangleCount = 0;
  80230. }
  80231. var newReferences = new Array(this.triangles.length * 3);
  80232. for (i = 0; i < this.triangles.length; ++i) {
  80233. t = this.triangles[i];
  80234. for (j = 0; j < 3; ++j) {
  80235. v = t.vertices[j];
  80236. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  80237. v.triangleCount++;
  80238. }
  80239. }
  80240. this.references = newReferences;
  80241. if (identifyBorders) {
  80242. this.identifyBorder();
  80243. }
  80244. };
  80245. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  80246. var x = point.x;
  80247. var y = point.y;
  80248. var z = point.z;
  80249. 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
  80250. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  80251. };
  80252. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  80253. var q = vertex1.q.add(vertex2.q);
  80254. var border = vertex1.isBorder && vertex2.isBorder;
  80255. var error = 0;
  80256. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  80257. if (qDet !== 0 && !border) {
  80258. if (!pointResult) {
  80259. pointResult = BABYLON.Vector3.Zero();
  80260. }
  80261. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  80262. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  80263. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  80264. error = this.vertexError(q, pointResult);
  80265. }
  80266. else {
  80267. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  80268. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  80269. var error1 = this.vertexError(q, vertex1.position);
  80270. var error2 = this.vertexError(q, vertex2.position);
  80271. var error3 = this.vertexError(q, p3);
  80272. error = Math.min(error1, error2, error3);
  80273. if (error === error1) {
  80274. if (pointResult) {
  80275. pointResult.copyFrom(vertex1.position);
  80276. }
  80277. }
  80278. else if (error === error2) {
  80279. if (pointResult) {
  80280. pointResult.copyFrom(vertex2.position);
  80281. }
  80282. }
  80283. else {
  80284. if (pointResult) {
  80285. pointResult.copyFrom(p3);
  80286. }
  80287. }
  80288. }
  80289. return error;
  80290. };
  80291. return QuadraticErrorSimplification;
  80292. }());
  80293. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  80294. })(BABYLON || (BABYLON = {}));
  80295. //# sourceMappingURL=babylon.meshSimplification.js.map
  80296. var BABYLON;
  80297. (function (BABYLON) {
  80298. var MeshLODLevel = /** @class */ (function () {
  80299. function MeshLODLevel(distance, mesh) {
  80300. this.distance = distance;
  80301. this.mesh = mesh;
  80302. }
  80303. return MeshLODLevel;
  80304. }());
  80305. BABYLON.MeshLODLevel = MeshLODLevel;
  80306. })(BABYLON || (BABYLON = {}));
  80307. //# sourceMappingURL=babylon.meshLODLevel.js.map
  80308. var BABYLON;
  80309. (function (BABYLON) {
  80310. /**
  80311. * Defines the root class used to create scene optimization to use with SceneOptimizer
  80312. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80313. */
  80314. var SceneOptimization = /** @class */ (function () {
  80315. /**
  80316. * Creates the SceneOptimization object
  80317. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80318. * @param desc defines the description associated with the optimization
  80319. */
  80320. function SceneOptimization(
  80321. /**
  80322. * Defines the priority of this optimization (0 by default which means first in the list)
  80323. */
  80324. priority) {
  80325. if (priority === void 0) { priority = 0; }
  80326. this.priority = priority;
  80327. }
  80328. /**
  80329. * Gets a string describing the action executed by the current optimization
  80330. * @returns description string
  80331. */
  80332. SceneOptimization.prototype.getDescription = function () {
  80333. return "";
  80334. };
  80335. /**
  80336. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80337. * @param scene defines the current scene where to apply this optimization
  80338. * @param optimizer defines the current optimizer
  80339. * @returns true if everything that can be done was applied
  80340. */
  80341. SceneOptimization.prototype.apply = function (scene, optimizer) {
  80342. return true;
  80343. };
  80344. ;
  80345. return SceneOptimization;
  80346. }());
  80347. BABYLON.SceneOptimization = SceneOptimization;
  80348. /**
  80349. * Defines an optimization used to reduce the size of render target textures
  80350. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80351. */
  80352. var TextureOptimization = /** @class */ (function (_super) {
  80353. __extends(TextureOptimization, _super);
  80354. /**
  80355. * Creates the TextureOptimization object
  80356. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80357. * @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
  80358. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80359. */
  80360. function TextureOptimization(
  80361. /**
  80362. * Defines the priority of this optimization (0 by default which means first in the list)
  80363. */
  80364. priority,
  80365. /**
  80366. * 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
  80367. */
  80368. maximumSize,
  80369. /**
  80370. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80371. */
  80372. step) {
  80373. if (priority === void 0) { priority = 0; }
  80374. if (maximumSize === void 0) { maximumSize = 1024; }
  80375. if (step === void 0) { step = 0.5; }
  80376. var _this = _super.call(this, priority) || this;
  80377. _this.priority = priority;
  80378. _this.maximumSize = maximumSize;
  80379. _this.step = step;
  80380. return _this;
  80381. }
  80382. /**
  80383. * Gets a string describing the action executed by the current optimization
  80384. * @returns description string
  80385. */
  80386. TextureOptimization.prototype.getDescription = function () {
  80387. return "Reducing render target texture size to " + this.maximumSize;
  80388. };
  80389. /**
  80390. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80391. * @param scene defines the current scene where to apply this optimization
  80392. * @param optimizer defines the current optimizer
  80393. * @returns true if everything that can be done was applied
  80394. */
  80395. TextureOptimization.prototype.apply = function (scene, optimizer) {
  80396. var allDone = true;
  80397. for (var index = 0; index < scene.textures.length; index++) {
  80398. var texture = scene.textures[index];
  80399. if (!texture.canRescale || texture.getContext) {
  80400. continue;
  80401. }
  80402. var currentSize = texture.getSize();
  80403. var maxDimension = Math.max(currentSize.width, currentSize.height);
  80404. if (maxDimension > this.maximumSize) {
  80405. texture.scale(this.step);
  80406. allDone = false;
  80407. }
  80408. }
  80409. return allDone;
  80410. };
  80411. return TextureOptimization;
  80412. }(SceneOptimization));
  80413. BABYLON.TextureOptimization = TextureOptimization;
  80414. /**
  80415. * Defines an optimization used to increase or decrease the rendering resolution
  80416. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80417. */
  80418. var HardwareScalingOptimization = /** @class */ (function (_super) {
  80419. __extends(HardwareScalingOptimization, _super);
  80420. /**
  80421. * Creates the HardwareScalingOptimization object
  80422. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80423. * @param maximumScale defines the maximum scale to use (2 by default)
  80424. * @param step defines the step to use between two passes (0.5 by default)
  80425. */
  80426. function HardwareScalingOptimization(
  80427. /**
  80428. * Defines the priority of this optimization (0 by default which means first in the list)
  80429. */
  80430. priority,
  80431. /**
  80432. * Defines the maximum scale to use (2 by default)
  80433. */
  80434. maximumScale,
  80435. /**
  80436. * Defines the step to use between two passes (0.5 by default)
  80437. */
  80438. step) {
  80439. if (priority === void 0) { priority = 0; }
  80440. if (maximumScale === void 0) { maximumScale = 2; }
  80441. if (step === void 0) { step = 0.25; }
  80442. var _this = _super.call(this, priority) || this;
  80443. _this.priority = priority;
  80444. _this.maximumScale = maximumScale;
  80445. _this.step = step;
  80446. _this._currentScale = -1;
  80447. _this._directionOffset = 1;
  80448. return _this;
  80449. }
  80450. /**
  80451. * Gets a string describing the action executed by the current optimization
  80452. * @return description string
  80453. */
  80454. HardwareScalingOptimization.prototype.getDescription = function () {
  80455. return "Setting hardware scaling level to " + this._currentScale;
  80456. };
  80457. /**
  80458. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80459. * @param scene defines the current scene where to apply this optimization
  80460. * @param optimizer defines the current optimizer
  80461. * @returns true if everything that can be done was applied
  80462. */
  80463. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  80464. if (this._currentScale === -1) {
  80465. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  80466. if (this._currentScale > this.maximumScale) {
  80467. this._directionOffset = -1;
  80468. }
  80469. }
  80470. this._currentScale += this._directionOffset * this.step;
  80471. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  80472. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  80473. };
  80474. ;
  80475. return HardwareScalingOptimization;
  80476. }(SceneOptimization));
  80477. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  80478. /**
  80479. * Defines an optimization used to remove shadows
  80480. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80481. */
  80482. var ShadowsOptimization = /** @class */ (function (_super) {
  80483. __extends(ShadowsOptimization, _super);
  80484. function ShadowsOptimization() {
  80485. return _super !== null && _super.apply(this, arguments) || this;
  80486. }
  80487. /**
  80488. * Gets a string describing the action executed by the current optimization
  80489. * @return description string
  80490. */
  80491. ShadowsOptimization.prototype.getDescription = function () {
  80492. return "Turning shadows on/off";
  80493. };
  80494. /**
  80495. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80496. * @param scene defines the current scene where to apply this optimization
  80497. * @param optimizer defines the current optimizer
  80498. * @returns true if everything that can be done was applied
  80499. */
  80500. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  80501. scene.shadowsEnabled = optimizer.isInImprovementMode;
  80502. return true;
  80503. };
  80504. ;
  80505. return ShadowsOptimization;
  80506. }(SceneOptimization));
  80507. BABYLON.ShadowsOptimization = ShadowsOptimization;
  80508. /**
  80509. * Defines an optimization used to turn post-processes off
  80510. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80511. */
  80512. var PostProcessesOptimization = /** @class */ (function (_super) {
  80513. __extends(PostProcessesOptimization, _super);
  80514. function PostProcessesOptimization() {
  80515. return _super !== null && _super.apply(this, arguments) || this;
  80516. }
  80517. /**
  80518. * Gets a string describing the action executed by the current optimization
  80519. * @return description string
  80520. */
  80521. PostProcessesOptimization.prototype.getDescription = function () {
  80522. return "Turning post-processes on/off";
  80523. };
  80524. /**
  80525. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80526. * @param scene defines the current scene where to apply this optimization
  80527. * @param optimizer defines the current optimizer
  80528. * @returns true if everything that can be done was applied
  80529. */
  80530. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  80531. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  80532. return true;
  80533. };
  80534. ;
  80535. return PostProcessesOptimization;
  80536. }(SceneOptimization));
  80537. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  80538. /**
  80539. * Defines an optimization used to turn lens flares off
  80540. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80541. */
  80542. var LensFlaresOptimization = /** @class */ (function (_super) {
  80543. __extends(LensFlaresOptimization, _super);
  80544. function LensFlaresOptimization() {
  80545. return _super !== null && _super.apply(this, arguments) || this;
  80546. }
  80547. /**
  80548. * Gets a string describing the action executed by the current optimization
  80549. * @return description string
  80550. */
  80551. LensFlaresOptimization.prototype.getDescription = function () {
  80552. return "Turning lens flares on/off";
  80553. };
  80554. /**
  80555. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80556. * @param scene defines the current scene where to apply this optimization
  80557. * @param optimizer defines the current optimizer
  80558. * @returns true if everything that can be done was applied
  80559. */
  80560. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  80561. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  80562. return true;
  80563. };
  80564. ;
  80565. return LensFlaresOptimization;
  80566. }(SceneOptimization));
  80567. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  80568. /**
  80569. * Defines an optimization based on user defined callback.
  80570. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80571. */
  80572. var CustomOptimization = /** @class */ (function (_super) {
  80573. __extends(CustomOptimization, _super);
  80574. function CustomOptimization() {
  80575. return _super !== null && _super.apply(this, arguments) || this;
  80576. }
  80577. /**
  80578. * Gets a string describing the action executed by the current optimization
  80579. * @returns description string
  80580. */
  80581. CustomOptimization.prototype.getDescription = function () {
  80582. if (this.onGetDescription) {
  80583. return this.onGetDescription();
  80584. }
  80585. return "Running user defined callback";
  80586. };
  80587. /**
  80588. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80589. * @param scene defines the current scene where to apply this optimization
  80590. * @param optimizer defines the current optimizer
  80591. * @returns true if everything that can be done was applied
  80592. */
  80593. CustomOptimization.prototype.apply = function (scene, optimizer) {
  80594. if (this.onApply) {
  80595. return this.onApply(scene, optimizer);
  80596. }
  80597. return true;
  80598. };
  80599. ;
  80600. return CustomOptimization;
  80601. }(SceneOptimization));
  80602. BABYLON.CustomOptimization = CustomOptimization;
  80603. /**
  80604. * Defines an optimization used to turn particles off
  80605. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80606. */
  80607. var ParticlesOptimization = /** @class */ (function (_super) {
  80608. __extends(ParticlesOptimization, _super);
  80609. function ParticlesOptimization() {
  80610. return _super !== null && _super.apply(this, arguments) || this;
  80611. }
  80612. /**
  80613. * Gets a string describing the action executed by the current optimization
  80614. * @return description string
  80615. */
  80616. ParticlesOptimization.prototype.getDescription = function () {
  80617. return "Turning particles on/off";
  80618. };
  80619. /**
  80620. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80621. * @param scene defines the current scene where to apply this optimization
  80622. * @param optimizer defines the current optimizer
  80623. * @returns true if everything that can be done was applied
  80624. */
  80625. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  80626. scene.particlesEnabled = optimizer.isInImprovementMode;
  80627. return true;
  80628. };
  80629. ;
  80630. return ParticlesOptimization;
  80631. }(SceneOptimization));
  80632. BABYLON.ParticlesOptimization = ParticlesOptimization;
  80633. /**
  80634. * Defines an optimization used to turn render targets off
  80635. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80636. */
  80637. var RenderTargetsOptimization = /** @class */ (function (_super) {
  80638. __extends(RenderTargetsOptimization, _super);
  80639. function RenderTargetsOptimization() {
  80640. return _super !== null && _super.apply(this, arguments) || this;
  80641. }
  80642. /**
  80643. * Gets a string describing the action executed by the current optimization
  80644. * @return description string
  80645. */
  80646. RenderTargetsOptimization.prototype.getDescription = function () {
  80647. return "Turning render targets off";
  80648. };
  80649. /**
  80650. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80651. * @param scene defines the current scene where to apply this optimization
  80652. * @param optimizer defines the current optimizer
  80653. * @returns true if everything that can be done was applied
  80654. */
  80655. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  80656. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  80657. return true;
  80658. };
  80659. ;
  80660. return RenderTargetsOptimization;
  80661. }(SceneOptimization));
  80662. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  80663. /**
  80664. * Defines an optimization used to merge meshes with compatible materials
  80665. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80666. */
  80667. var MergeMeshesOptimization = /** @class */ (function (_super) {
  80668. __extends(MergeMeshesOptimization, _super);
  80669. function MergeMeshesOptimization() {
  80670. var _this = _super !== null && _super.apply(this, arguments) || this;
  80671. _this._canBeMerged = function (abstractMesh) {
  80672. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  80673. return false;
  80674. }
  80675. var mesh = abstractMesh;
  80676. if (!mesh.isVisible || !mesh.isEnabled()) {
  80677. return false;
  80678. }
  80679. if (mesh.instances.length > 0) {
  80680. return false;
  80681. }
  80682. if (mesh.skeleton || mesh.hasLODLevels) {
  80683. return false;
  80684. }
  80685. if (mesh.parent) {
  80686. return false;
  80687. }
  80688. return true;
  80689. };
  80690. return _this;
  80691. }
  80692. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  80693. /**
  80694. * Gets or sets a boolean which defines if optimization octree has to be updated
  80695. */
  80696. get: function () {
  80697. return MergeMeshesOptimization._UpdateSelectionTree;
  80698. },
  80699. /**
  80700. * Gets or sets a boolean which defines if optimization octree has to be updated
  80701. */
  80702. set: function (value) {
  80703. MergeMeshesOptimization._UpdateSelectionTree = value;
  80704. },
  80705. enumerable: true,
  80706. configurable: true
  80707. });
  80708. /**
  80709. * Gets a string describing the action executed by the current optimization
  80710. * @return description string
  80711. */
  80712. MergeMeshesOptimization.prototype.getDescription = function () {
  80713. return "Merging similar meshes together";
  80714. };
  80715. /**
  80716. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80717. * @param scene defines the current scene where to apply this optimization
  80718. * @param optimizer defines the current optimizer
  80719. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  80720. * @returns true if everything that can be done was applied
  80721. */
  80722. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  80723. var globalPool = scene.meshes.slice(0);
  80724. var globalLength = globalPool.length;
  80725. for (var index = 0; index < globalLength; index++) {
  80726. var currentPool = new Array();
  80727. var current = globalPool[index];
  80728. // Checks
  80729. if (!this._canBeMerged(current)) {
  80730. continue;
  80731. }
  80732. currentPool.push(current);
  80733. // Find compatible meshes
  80734. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  80735. var otherMesh = globalPool[subIndex];
  80736. if (!this._canBeMerged(otherMesh)) {
  80737. continue;
  80738. }
  80739. if (otherMesh.material !== current.material) {
  80740. continue;
  80741. }
  80742. if (otherMesh.checkCollisions !== current.checkCollisions) {
  80743. continue;
  80744. }
  80745. currentPool.push(otherMesh);
  80746. globalLength--;
  80747. globalPool.splice(subIndex, 1);
  80748. subIndex--;
  80749. }
  80750. if (currentPool.length < 2) {
  80751. continue;
  80752. }
  80753. // Merge meshes
  80754. BABYLON.Mesh.MergeMeshes(currentPool);
  80755. }
  80756. if (updateSelectionTree != undefined) {
  80757. if (updateSelectionTree) {
  80758. scene.createOrUpdateSelectionOctree();
  80759. }
  80760. }
  80761. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  80762. scene.createOrUpdateSelectionOctree();
  80763. }
  80764. return true;
  80765. };
  80766. ;
  80767. MergeMeshesOptimization._UpdateSelectionTree = false;
  80768. return MergeMeshesOptimization;
  80769. }(SceneOptimization));
  80770. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  80771. /**
  80772. * Defines a list of options used by SceneOptimizer
  80773. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80774. */
  80775. var SceneOptimizerOptions = /** @class */ (function () {
  80776. /**
  80777. * Creates a new list of options used by SceneOptimizer
  80778. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  80779. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  80780. */
  80781. function SceneOptimizerOptions(
  80782. /**
  80783. * Defines the target frame rate to reach (60 by default)
  80784. */
  80785. targetFrameRate,
  80786. /**
  80787. * Defines the interval between two checkes (2000ms by default)
  80788. */
  80789. trackerDuration) {
  80790. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  80791. if (trackerDuration === void 0) { trackerDuration = 2000; }
  80792. this.targetFrameRate = targetFrameRate;
  80793. this.trackerDuration = trackerDuration;
  80794. /**
  80795. * Gets the list of optimizations to apply
  80796. */
  80797. this.optimizations = new Array();
  80798. }
  80799. /**
  80800. * Add a new optimization
  80801. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  80802. * @returns the current SceneOptimizerOptions
  80803. */
  80804. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  80805. this.optimizations.push(optimization);
  80806. return this;
  80807. };
  80808. /**
  80809. * Add a new custom optimization
  80810. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  80811. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  80812. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80813. * @returns the current SceneOptimizerOptions
  80814. */
  80815. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  80816. if (priority === void 0) { priority = 0; }
  80817. var optimization = new CustomOptimization(priority);
  80818. optimization.onApply = onApply;
  80819. optimization.onGetDescription = onGetDescription;
  80820. this.optimizations.push(optimization);
  80821. return this;
  80822. };
  80823. /**
  80824. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  80825. * @param targetFrameRate defines the target frame rate (60 by default)
  80826. * @returns a SceneOptimizerOptions object
  80827. */
  80828. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  80829. var result = new SceneOptimizerOptions(targetFrameRate);
  80830. var priority = 0;
  80831. result.addOptimization(new MergeMeshesOptimization(priority));
  80832. result.addOptimization(new ShadowsOptimization(priority));
  80833. result.addOptimization(new LensFlaresOptimization(priority));
  80834. // Next priority
  80835. priority++;
  80836. result.addOptimization(new PostProcessesOptimization(priority));
  80837. result.addOptimization(new ParticlesOptimization(priority));
  80838. // Next priority
  80839. priority++;
  80840. result.addOptimization(new TextureOptimization(priority, 1024));
  80841. return result;
  80842. };
  80843. /**
  80844. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  80845. * @param targetFrameRate defines the target frame rate (60 by default)
  80846. * @returns a SceneOptimizerOptions object
  80847. */
  80848. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  80849. var result = new SceneOptimizerOptions(targetFrameRate);
  80850. var priority = 0;
  80851. result.addOptimization(new MergeMeshesOptimization(priority));
  80852. result.addOptimization(new ShadowsOptimization(priority));
  80853. result.addOptimization(new LensFlaresOptimization(priority));
  80854. // Next priority
  80855. priority++;
  80856. result.addOptimization(new PostProcessesOptimization(priority));
  80857. result.addOptimization(new ParticlesOptimization(priority));
  80858. // Next priority
  80859. priority++;
  80860. result.addOptimization(new TextureOptimization(priority, 512));
  80861. // Next priority
  80862. priority++;
  80863. result.addOptimization(new RenderTargetsOptimization(priority));
  80864. // Next priority
  80865. priority++;
  80866. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  80867. return result;
  80868. };
  80869. /**
  80870. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  80871. * @param targetFrameRate defines the target frame rate (60 by default)
  80872. * @returns a SceneOptimizerOptions object
  80873. */
  80874. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  80875. var result = new SceneOptimizerOptions(targetFrameRate);
  80876. var priority = 0;
  80877. result.addOptimization(new MergeMeshesOptimization(priority));
  80878. result.addOptimization(new ShadowsOptimization(priority));
  80879. result.addOptimization(new LensFlaresOptimization(priority));
  80880. // Next priority
  80881. priority++;
  80882. result.addOptimization(new PostProcessesOptimization(priority));
  80883. result.addOptimization(new ParticlesOptimization(priority));
  80884. // Next priority
  80885. priority++;
  80886. result.addOptimization(new TextureOptimization(priority, 256));
  80887. // Next priority
  80888. priority++;
  80889. result.addOptimization(new RenderTargetsOptimization(priority));
  80890. // Next priority
  80891. priority++;
  80892. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  80893. return result;
  80894. };
  80895. return SceneOptimizerOptions;
  80896. }());
  80897. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  80898. /**
  80899. * Class used to run optimizations in order to reach a target frame rate
  80900. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80901. */
  80902. var SceneOptimizer = /** @class */ (function () {
  80903. /**
  80904. * Creates a new SceneOptimizer
  80905. * @param scene defines the scene to work on
  80906. * @param options defines the options to use with the SceneOptimizer
  80907. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  80908. * @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)
  80909. */
  80910. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  80911. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  80912. if (improvementMode === void 0) { improvementMode = false; }
  80913. var _this = this;
  80914. this._isRunning = false;
  80915. this._currentPriorityLevel = 0;
  80916. this._targetFrameRate = 60;
  80917. this._trackerDuration = 2000;
  80918. this._currentFrameRate = 0;
  80919. this._improvementMode = false;
  80920. /**
  80921. * Defines an observable called when the optimizer reaches the target frame rate
  80922. */
  80923. this.onSuccessObservable = new BABYLON.Observable();
  80924. /**
  80925. * Defines an observable called when the optimizer enables an optimization
  80926. */
  80927. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  80928. /**
  80929. * Defines an observable called when the optimizer is not able to reach the target frame rate
  80930. */
  80931. this.onFailureObservable = new BABYLON.Observable();
  80932. if (!options) {
  80933. this._options = new SceneOptimizerOptions();
  80934. }
  80935. else {
  80936. this._options = options;
  80937. }
  80938. if (this._options.targetFrameRate) {
  80939. this._targetFrameRate = this._options.targetFrameRate;
  80940. }
  80941. if (this._options.trackerDuration) {
  80942. this._trackerDuration = this._options.trackerDuration;
  80943. }
  80944. if (autoGeneratePriorities) {
  80945. var priority = 0;
  80946. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  80947. var optim = _a[_i];
  80948. optim.priority = priority++;
  80949. }
  80950. }
  80951. this._improvementMode = improvementMode;
  80952. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80953. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  80954. _this._sceneDisposeObserver = null;
  80955. _this.dispose();
  80956. });
  80957. }
  80958. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  80959. /**
  80960. * Gets a boolean indicating if the optimizer is in improvement mode
  80961. */
  80962. get: function () {
  80963. return this._improvementMode;
  80964. },
  80965. enumerable: true,
  80966. configurable: true
  80967. });
  80968. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  80969. /**
  80970. * Gets the current priority level (0 at start)
  80971. */
  80972. get: function () {
  80973. return this._currentPriorityLevel;
  80974. },
  80975. enumerable: true,
  80976. configurable: true
  80977. });
  80978. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  80979. /**
  80980. * Gets the current frame rate checked by the SceneOptimizer
  80981. */
  80982. get: function () {
  80983. return this._currentFrameRate;
  80984. },
  80985. enumerable: true,
  80986. configurable: true
  80987. });
  80988. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  80989. /**
  80990. * Gets or sets the current target frame rate (60 by default)
  80991. */
  80992. get: function () {
  80993. return this._targetFrameRate;
  80994. },
  80995. /**
  80996. * Gets or sets the current target frame rate (60 by default)
  80997. */
  80998. set: function (value) {
  80999. this._targetFrameRate = value;
  81000. },
  81001. enumerable: true,
  81002. configurable: true
  81003. });
  81004. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81005. /**
  81006. * Gets or sets the current interval between two checks (every 2000ms by default)
  81007. */
  81008. get: function () {
  81009. return this._trackerDuration;
  81010. },
  81011. /**
  81012. * Gets or sets the current interval between two checks (every 2000ms by default)
  81013. */
  81014. set: function (value) {
  81015. this._trackerDuration = value;
  81016. },
  81017. enumerable: true,
  81018. configurable: true
  81019. });
  81020. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81021. /**
  81022. * Gets the list of active optimizations
  81023. */
  81024. get: function () {
  81025. return this._options.optimizations;
  81026. },
  81027. enumerable: true,
  81028. configurable: true
  81029. });
  81030. /**
  81031. * Stops the current optimizer
  81032. */
  81033. SceneOptimizer.prototype.stop = function () {
  81034. this._isRunning = false;
  81035. };
  81036. /**
  81037. * Reset the optimizer to initial step (current priority level = 0)
  81038. */
  81039. SceneOptimizer.prototype.reset = function () {
  81040. this._currentPriorityLevel = 0;
  81041. };
  81042. /**
  81043. * Start the optimizer. By default it will try to reach a specific framerate
  81044. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81045. */
  81046. SceneOptimizer.prototype.start = function () {
  81047. var _this = this;
  81048. if (this._isRunning) {
  81049. return;
  81050. }
  81051. this._isRunning = true;
  81052. // Let's wait for the scene to be ready before running our check
  81053. this._scene.executeWhenReady(function () {
  81054. setTimeout(function () {
  81055. _this._checkCurrentState();
  81056. }, _this._trackerDuration);
  81057. });
  81058. };
  81059. SceneOptimizer.prototype._checkCurrentState = function () {
  81060. var _this = this;
  81061. if (!this._isRunning) {
  81062. return;
  81063. }
  81064. var scene = this._scene;
  81065. var options = this._options;
  81066. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81067. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81068. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81069. this._isRunning = false;
  81070. this.onSuccessObservable.notifyObservers(this);
  81071. return;
  81072. }
  81073. // Apply current level of optimizations
  81074. var allDone = true;
  81075. var noOptimizationApplied = true;
  81076. for (var index = 0; index < options.optimizations.length; index++) {
  81077. var optimization = options.optimizations[index];
  81078. if (optimization.priority === this._currentPriorityLevel) {
  81079. noOptimizationApplied = false;
  81080. allDone = allDone && optimization.apply(scene, this);
  81081. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81082. }
  81083. }
  81084. // If no optimization was applied, this is a failure :(
  81085. if (noOptimizationApplied) {
  81086. this._isRunning = false;
  81087. this.onFailureObservable.notifyObservers(this);
  81088. return;
  81089. }
  81090. // If all optimizations were done, move to next level
  81091. if (allDone) {
  81092. this._currentPriorityLevel++;
  81093. }
  81094. // Let's the system running for a specific amount of time before checking FPS
  81095. scene.executeWhenReady(function () {
  81096. setTimeout(function () {
  81097. _this._checkCurrentState();
  81098. }, _this._trackerDuration);
  81099. });
  81100. };
  81101. /**
  81102. * Release all resources
  81103. */
  81104. SceneOptimizer.prototype.dispose = function () {
  81105. this.stop();
  81106. this.onSuccessObservable.clear();
  81107. this.onFailureObservable.clear();
  81108. this.onNewOptimizationAppliedObservable.clear();
  81109. if (this._sceneDisposeObserver) {
  81110. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81111. }
  81112. };
  81113. /**
  81114. * Helper function to create a SceneOptimizer with one single line of code
  81115. * @param scene defines the scene to work on
  81116. * @param options defines the options to use with the SceneOptimizer
  81117. * @param onSuccess defines a callback to call on success
  81118. * @param onFailure defines a callback to call on failure
  81119. * @returns the new SceneOptimizer object
  81120. */
  81121. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81122. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81123. if (onSuccess) {
  81124. optimizer.onSuccessObservable.add(function () {
  81125. onSuccess();
  81126. });
  81127. }
  81128. if (onFailure) {
  81129. optimizer.onFailureObservable.add(function () {
  81130. onFailure();
  81131. });
  81132. }
  81133. optimizer.start();
  81134. return optimizer;
  81135. };
  81136. return SceneOptimizer;
  81137. }());
  81138. BABYLON.SceneOptimizer = SceneOptimizer;
  81139. })(BABYLON || (BABYLON = {}));
  81140. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81141. var BABYLON;
  81142. (function (BABYLON) {
  81143. var OutlineRenderer = /** @class */ (function () {
  81144. function OutlineRenderer(scene) {
  81145. this.zOffset = 1;
  81146. this._scene = scene;
  81147. }
  81148. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81149. var _this = this;
  81150. if (useOverlay === void 0) { useOverlay = false; }
  81151. var scene = this._scene;
  81152. var engine = this._scene.getEngine();
  81153. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81154. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81155. return;
  81156. }
  81157. var mesh = subMesh.getRenderingMesh();
  81158. var material = subMesh.getMaterial();
  81159. if (!material || !scene.activeCamera) {
  81160. return;
  81161. }
  81162. engine.enableEffect(this._effect);
  81163. // Logarithmic depth
  81164. if (material.useLogarithmicDepth) {
  81165. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81166. }
  81167. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81168. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81169. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81170. // Bones
  81171. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81172. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81173. }
  81174. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81175. // Alpha test
  81176. if (material && material.needAlphaTesting()) {
  81177. var alphaTexture = material.getAlphaTestTexture();
  81178. if (alphaTexture) {
  81179. this._effect.setTexture("diffuseSampler", alphaTexture);
  81180. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81181. }
  81182. }
  81183. engine.setZOffset(-this.zOffset);
  81184. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81185. engine.setZOffset(0);
  81186. };
  81187. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81188. var defines = [];
  81189. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81190. var mesh = subMesh.getMesh();
  81191. var material = subMesh.getMaterial();
  81192. if (material) {
  81193. // Alpha test
  81194. if (material.needAlphaTesting()) {
  81195. defines.push("#define ALPHATEST");
  81196. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81197. attribs.push(BABYLON.VertexBuffer.UVKind);
  81198. defines.push("#define UV1");
  81199. }
  81200. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81201. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81202. defines.push("#define UV2");
  81203. }
  81204. }
  81205. //Logarithmic depth
  81206. if (material.useLogarithmicDepth) {
  81207. defines.push("#define LOGARITHMICDEPTH");
  81208. }
  81209. }
  81210. // Bones
  81211. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81212. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81213. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81214. if (mesh.numBoneInfluencers > 4) {
  81215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81217. }
  81218. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81219. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81220. }
  81221. else {
  81222. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81223. }
  81224. // Instances
  81225. if (useInstances) {
  81226. defines.push("#define INSTANCES");
  81227. attribs.push("world0");
  81228. attribs.push("world1");
  81229. attribs.push("world2");
  81230. attribs.push("world3");
  81231. }
  81232. // Get correct effect
  81233. var join = defines.join("\n");
  81234. if (this._cachedDefines !== join) {
  81235. this._cachedDefines = join;
  81236. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  81237. }
  81238. return this._effect.isReady();
  81239. };
  81240. return OutlineRenderer;
  81241. }());
  81242. BABYLON.OutlineRenderer = OutlineRenderer;
  81243. })(BABYLON || (BABYLON = {}));
  81244. //# sourceMappingURL=babylon.outlineRenderer.js.map
  81245. var BABYLON;
  81246. (function (BABYLON) {
  81247. var FaceAdjacencies = /** @class */ (function () {
  81248. function FaceAdjacencies() {
  81249. this.edges = new Array();
  81250. this.edgesConnectedCount = 0;
  81251. }
  81252. return FaceAdjacencies;
  81253. }());
  81254. var EdgesRenderer = /** @class */ (function () {
  81255. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  81256. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  81257. if (epsilon === void 0) { epsilon = 0.95; }
  81258. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  81259. this.edgesWidthScalerForOrthographic = 1000.0;
  81260. this.edgesWidthScalerForPerspective = 50.0;
  81261. this._linesPositions = new Array();
  81262. this._linesNormals = new Array();
  81263. this._linesIndices = new Array();
  81264. this._buffers = {};
  81265. this._checkVerticesInsteadOfIndices = false;
  81266. this._source = source;
  81267. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  81268. this._epsilon = epsilon;
  81269. this._prepareRessources();
  81270. this._generateEdgesLines();
  81271. }
  81272. EdgesRenderer.prototype._prepareRessources = function () {
  81273. if (this._lineShader) {
  81274. return;
  81275. }
  81276. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  81277. attributes: ["position", "normal"],
  81278. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  81279. });
  81280. this._lineShader.disableDepthWrite = true;
  81281. this._lineShader.backFaceCulling = false;
  81282. };
  81283. EdgesRenderer.prototype._rebuild = function () {
  81284. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81285. if (buffer) {
  81286. buffer._rebuild();
  81287. }
  81288. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81289. if (buffer) {
  81290. buffer._rebuild();
  81291. }
  81292. var scene = this._source.getScene();
  81293. var engine = scene.getEngine();
  81294. this._ib = engine.createIndexBuffer(this._linesIndices);
  81295. };
  81296. EdgesRenderer.prototype.dispose = function () {
  81297. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81298. if (buffer) {
  81299. buffer.dispose();
  81300. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  81301. }
  81302. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81303. if (buffer) {
  81304. buffer.dispose();
  81305. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  81306. }
  81307. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  81308. this._lineShader.dispose();
  81309. };
  81310. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  81311. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  81312. return 0;
  81313. }
  81314. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  81315. return 1;
  81316. }
  81317. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  81318. return 2;
  81319. }
  81320. return -1;
  81321. };
  81322. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  81323. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  81324. return 0;
  81325. }
  81326. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  81327. return 1;
  81328. }
  81329. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  81330. return 2;
  81331. }
  81332. return -1;
  81333. };
  81334. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  81335. var needToCreateLine;
  81336. if (edge === undefined) {
  81337. needToCreateLine = true;
  81338. }
  81339. else {
  81340. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  81341. needToCreateLine = dotProduct < this._epsilon;
  81342. }
  81343. if (needToCreateLine) {
  81344. var offset = this._linesPositions.length / 3;
  81345. var normal = p0.subtract(p1);
  81346. normal.normalize();
  81347. // Positions
  81348. this._linesPositions.push(p0.x);
  81349. this._linesPositions.push(p0.y);
  81350. this._linesPositions.push(p0.z);
  81351. this._linesPositions.push(p0.x);
  81352. this._linesPositions.push(p0.y);
  81353. this._linesPositions.push(p0.z);
  81354. this._linesPositions.push(p1.x);
  81355. this._linesPositions.push(p1.y);
  81356. this._linesPositions.push(p1.z);
  81357. this._linesPositions.push(p1.x);
  81358. this._linesPositions.push(p1.y);
  81359. this._linesPositions.push(p1.z);
  81360. // Normals
  81361. this._linesNormals.push(p1.x);
  81362. this._linesNormals.push(p1.y);
  81363. this._linesNormals.push(p1.z);
  81364. this._linesNormals.push(-1);
  81365. this._linesNormals.push(p1.x);
  81366. this._linesNormals.push(p1.y);
  81367. this._linesNormals.push(p1.z);
  81368. this._linesNormals.push(1);
  81369. this._linesNormals.push(p0.x);
  81370. this._linesNormals.push(p0.y);
  81371. this._linesNormals.push(p0.z);
  81372. this._linesNormals.push(-1);
  81373. this._linesNormals.push(p0.x);
  81374. this._linesNormals.push(p0.y);
  81375. this._linesNormals.push(p0.z);
  81376. this._linesNormals.push(1);
  81377. // Indices
  81378. this._linesIndices.push(offset);
  81379. this._linesIndices.push(offset + 1);
  81380. this._linesIndices.push(offset + 2);
  81381. this._linesIndices.push(offset);
  81382. this._linesIndices.push(offset + 2);
  81383. this._linesIndices.push(offset + 3);
  81384. }
  81385. };
  81386. EdgesRenderer.prototype._generateEdgesLines = function () {
  81387. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81388. var indices = this._source.getIndices();
  81389. if (!indices || !positions) {
  81390. return;
  81391. }
  81392. // First let's find adjacencies
  81393. var adjacencies = new Array();
  81394. var faceNormals = new Array();
  81395. var index;
  81396. var faceAdjacencies;
  81397. // Prepare faces
  81398. for (index = 0; index < indices.length; index += 3) {
  81399. faceAdjacencies = new FaceAdjacencies();
  81400. var p0Index = indices[index];
  81401. var p1Index = indices[index + 1];
  81402. var p2Index = indices[index + 2];
  81403. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  81404. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  81405. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  81406. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  81407. faceNormal.normalize();
  81408. faceNormals.push(faceNormal);
  81409. adjacencies.push(faceAdjacencies);
  81410. }
  81411. // Scan
  81412. for (index = 0; index < adjacencies.length; index++) {
  81413. faceAdjacencies = adjacencies[index];
  81414. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  81415. var otherFaceAdjacencies = adjacencies[otherIndex];
  81416. if (faceAdjacencies.edgesConnectedCount === 3) {
  81417. break;
  81418. }
  81419. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  81420. continue;
  81421. }
  81422. var otherP0 = indices[otherIndex * 3];
  81423. var otherP1 = indices[otherIndex * 3 + 1];
  81424. var otherP2 = indices[otherIndex * 3 + 2];
  81425. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  81426. var otherEdgeIndex = 0;
  81427. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  81428. continue;
  81429. }
  81430. switch (edgeIndex) {
  81431. case 0:
  81432. if (this._checkVerticesInsteadOfIndices) {
  81433. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81434. }
  81435. else {
  81436. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  81437. }
  81438. break;
  81439. case 1:
  81440. if (this._checkVerticesInsteadOfIndices) {
  81441. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81442. }
  81443. else {
  81444. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  81445. }
  81446. break;
  81447. case 2:
  81448. if (this._checkVerticesInsteadOfIndices) {
  81449. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81450. }
  81451. else {
  81452. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  81453. }
  81454. break;
  81455. }
  81456. if (otherEdgeIndex === -1) {
  81457. continue;
  81458. }
  81459. faceAdjacencies.edges[edgeIndex] = otherIndex;
  81460. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  81461. faceAdjacencies.edgesConnectedCount++;
  81462. otherFaceAdjacencies.edgesConnectedCount++;
  81463. if (faceAdjacencies.edgesConnectedCount === 3) {
  81464. break;
  81465. }
  81466. }
  81467. }
  81468. }
  81469. // Create lines
  81470. for (index = 0; index < adjacencies.length; index++) {
  81471. // 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
  81472. var current = adjacencies[index];
  81473. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  81474. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  81475. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  81476. }
  81477. // Merge into a single mesh
  81478. var engine = this._source.getScene().getEngine();
  81479. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  81480. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  81481. this._ib = engine.createIndexBuffer(this._linesIndices);
  81482. this._indicesCount = this._linesIndices.length;
  81483. };
  81484. EdgesRenderer.prototype.render = function () {
  81485. var scene = this._source.getScene();
  81486. if (!this._lineShader.isReady() || !scene.activeCamera) {
  81487. return;
  81488. }
  81489. var engine = scene.getEngine();
  81490. this._lineShader._preBind();
  81491. // VBOs
  81492. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  81493. scene.resetCachedMaterial();
  81494. this._lineShader.setColor4("color", this._source.edgesColor);
  81495. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  81496. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  81497. }
  81498. else {
  81499. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  81500. }
  81501. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  81502. this._lineShader.bind(this._source.getWorldMatrix());
  81503. // Draw order
  81504. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  81505. this._lineShader.unbind();
  81506. engine.setDepthWrite(true);
  81507. };
  81508. return EdgesRenderer;
  81509. }());
  81510. BABYLON.EdgesRenderer = EdgesRenderer;
  81511. })(BABYLON || (BABYLON = {}));
  81512. //# sourceMappingURL=babylon.edgesRenderer.js.map
  81513. var BABYLON;
  81514. (function (BABYLON) {
  81515. /**
  81516. * Special Glow Blur post process only blurring the alpha channel
  81517. * It enforces keeping the most luminous color in the color channel.
  81518. */
  81519. var GlowBlurPostProcess = /** @class */ (function (_super) {
  81520. __extends(GlowBlurPostProcess, _super);
  81521. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  81522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81523. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  81524. _this.direction = direction;
  81525. _this.kernel = kernel;
  81526. _this.onApplyObservable.add(function (effect) {
  81527. effect.setFloat2("screenSize", _this.width, _this.height);
  81528. effect.setVector2("direction", _this.direction);
  81529. effect.setFloat("blurWidth", _this.kernel);
  81530. });
  81531. return _this;
  81532. }
  81533. return GlowBlurPostProcess;
  81534. }(BABYLON.PostProcess));
  81535. /**
  81536. * The highlight layer Helps adding a glow effect around a mesh.
  81537. *
  81538. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  81539. * glowy meshes to your scene.
  81540. *
  81541. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  81542. */
  81543. var HighlightLayer = /** @class */ (function () {
  81544. /**
  81545. * Instantiates a new highlight Layer and references it to the scene..
  81546. * @param name The name of the layer
  81547. * @param scene The scene to use the layer in
  81548. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  81549. */
  81550. function HighlightLayer(name, scene, options) {
  81551. this.name = name;
  81552. this._vertexBuffers = {};
  81553. this._mainTextureDesiredSize = { width: 0, height: 0 };
  81554. this._meshes = {};
  81555. this._maxSize = 0;
  81556. this._shouldRender = false;
  81557. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  81558. this._excludedMeshes = {};
  81559. /**
  81560. * Specifies whether or not the inner glow is ACTIVE in the layer.
  81561. */
  81562. this.innerGlow = true;
  81563. /**
  81564. * Specifies whether or not the outer glow is ACTIVE in the layer.
  81565. */
  81566. this.outerGlow = true;
  81567. /**
  81568. * Specifies wether the highlight layer is enabled or not.
  81569. */
  81570. this.isEnabled = true;
  81571. /**
  81572. * An event triggered when the highlight layer has been disposed.
  81573. * @type {BABYLON.Observable}
  81574. */
  81575. this.onDisposeObservable = new BABYLON.Observable();
  81576. /**
  81577. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  81578. * @type {BABYLON.Observable}
  81579. */
  81580. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  81581. /**
  81582. * An event triggered when the highlight layer is being blurred.
  81583. * @type {BABYLON.Observable}
  81584. */
  81585. this.onBeforeBlurObservable = new BABYLON.Observable();
  81586. /**
  81587. * An event triggered when the highlight layer has been blurred.
  81588. * @type {BABYLON.Observable}
  81589. */
  81590. this.onAfterBlurObservable = new BABYLON.Observable();
  81591. /**
  81592. * An event triggered when the glowing blurred texture is being merged in the scene.
  81593. * @type {BABYLON.Observable}
  81594. */
  81595. this.onBeforeComposeObservable = new BABYLON.Observable();
  81596. /**
  81597. * An event triggered when the glowing blurred texture has been merged in the scene.
  81598. * @type {BABYLON.Observable}
  81599. */
  81600. this.onAfterComposeObservable = new BABYLON.Observable();
  81601. /**
  81602. * An event triggered when the highlight layer changes its size.
  81603. * @type {BABYLON.Observable}
  81604. */
  81605. this.onSizeChangedObservable = new BABYLON.Observable();
  81606. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81607. var engine = scene.getEngine();
  81608. this._engine = engine;
  81609. this._maxSize = this._engine.getCaps().maxTextureSize;
  81610. this._scene.highlightLayers.push(this);
  81611. // Warn on stencil.
  81612. if (!this._engine.isStencilEnable) {
  81613. 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 }");
  81614. }
  81615. // Adapt options
  81616. this._options = options || {
  81617. mainTextureRatio: 0.5,
  81618. blurTextureSizeRatio: 0.5,
  81619. blurHorizontalSize: 1.0,
  81620. blurVerticalSize: 1.0,
  81621. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  81622. camera: null
  81623. };
  81624. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  81625. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  81626. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  81627. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  81628. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  81629. // VBO
  81630. var vertices = [];
  81631. vertices.push(1, 1);
  81632. vertices.push(-1, 1);
  81633. vertices.push(-1, -1);
  81634. vertices.push(1, -1);
  81635. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81636. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  81637. this._createIndexBuffer();
  81638. // Effect
  81639. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  81640. // Render target
  81641. this.setMainTextureSize();
  81642. // Create Textures and post processes
  81643. this.createTextureAndPostProcesses();
  81644. }
  81645. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  81646. /**
  81647. * Gets the horizontal size of the blur.
  81648. */
  81649. get: function () {
  81650. return this._horizontalBlurPostprocess.kernel;
  81651. },
  81652. /**
  81653. * Specifies the horizontal size of the blur.
  81654. */
  81655. set: function (value) {
  81656. this._horizontalBlurPostprocess.kernel = value;
  81657. },
  81658. enumerable: true,
  81659. configurable: true
  81660. });
  81661. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  81662. /**
  81663. * Gets the vertical size of the blur.
  81664. */
  81665. get: function () {
  81666. return this._verticalBlurPostprocess.kernel;
  81667. },
  81668. /**
  81669. * Specifies the vertical size of the blur.
  81670. */
  81671. set: function (value) {
  81672. this._verticalBlurPostprocess.kernel = value;
  81673. },
  81674. enumerable: true,
  81675. configurable: true
  81676. });
  81677. Object.defineProperty(HighlightLayer.prototype, "camera", {
  81678. /**
  81679. * Gets the camera attached to the layer.
  81680. */
  81681. get: function () {
  81682. return this._options.camera;
  81683. },
  81684. enumerable: true,
  81685. configurable: true
  81686. });
  81687. HighlightLayer.prototype._createIndexBuffer = function () {
  81688. var engine = this._scene.getEngine();
  81689. // Indices
  81690. var indices = [];
  81691. indices.push(0);
  81692. indices.push(1);
  81693. indices.push(2);
  81694. indices.push(0);
  81695. indices.push(2);
  81696. indices.push(3);
  81697. this._indexBuffer = engine.createIndexBuffer(indices);
  81698. };
  81699. HighlightLayer.prototype._rebuild = function () {
  81700. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81701. if (vb) {
  81702. vb._rebuild();
  81703. }
  81704. this._createIndexBuffer();
  81705. };
  81706. /**
  81707. * Creates the render target textures and post processes used in the highlight layer.
  81708. */
  81709. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  81710. var _this = this;
  81711. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  81712. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  81713. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  81714. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  81715. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  81716. width: this._mainTextureDesiredSize.width,
  81717. height: this._mainTextureDesiredSize.height
  81718. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81719. this._mainTexture.activeCamera = this._options.camera;
  81720. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81721. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81722. this._mainTexture.anisotropicFilteringLevel = 1;
  81723. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81724. this._mainTexture.renderParticles = false;
  81725. this._mainTexture.renderList = null;
  81726. this._mainTexture.ignoreCameraViewport = true;
  81727. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  81728. width: blurTextureWidth,
  81729. height: blurTextureHeight
  81730. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81731. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81732. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81733. this._blurTexture.anisotropicFilteringLevel = 16;
  81734. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81735. this._blurTexture.renderParticles = false;
  81736. this._blurTexture.ignoreCameraViewport = true;
  81737. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81738. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  81739. effect.setTexture("textureSampler", _this._mainTexture);
  81740. });
  81741. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  81742. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81743. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  81744. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  81745. });
  81746. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81747. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  81748. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  81749. });
  81750. }
  81751. else {
  81752. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81753. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  81754. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  81755. });
  81756. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81757. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  81758. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  81759. });
  81760. }
  81761. this._mainTexture.onAfterUnbindObservable.add(function () {
  81762. _this.onBeforeBlurObservable.notifyObservers(_this);
  81763. var internalTexture = _this._blurTexture.getInternalTexture();
  81764. if (internalTexture) {
  81765. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  81766. }
  81767. _this.onAfterBlurObservable.notifyObservers(_this);
  81768. });
  81769. // Custom render function
  81770. var renderSubMesh = function (subMesh) {
  81771. if (!_this._meshes) {
  81772. return;
  81773. }
  81774. var material = subMesh.getMaterial();
  81775. var mesh = subMesh.getRenderingMesh();
  81776. var scene = _this._scene;
  81777. var engine = scene.getEngine();
  81778. if (!material) {
  81779. return;
  81780. }
  81781. // Do not block in blend mode.
  81782. if (material.needAlphaBlendingForMesh(mesh)) {
  81783. return;
  81784. }
  81785. // Culling
  81786. engine.setState(material.backFaceCulling);
  81787. // Managing instances
  81788. var batch = mesh._getInstancesRenderList(subMesh._id);
  81789. if (batch.mustReturn) {
  81790. return;
  81791. }
  81792. // Excluded Mesh
  81793. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  81794. return;
  81795. }
  81796. ;
  81797. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81798. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  81799. var emissiveTexture = null;
  81800. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  81801. emissiveTexture = material.emissiveTexture;
  81802. }
  81803. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  81804. engine.enableEffect(_this._glowMapGenerationEffect);
  81805. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  81806. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  81807. if (highlightLayerMesh) {
  81808. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  81809. }
  81810. else {
  81811. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  81812. }
  81813. // Alpha test
  81814. if (material && material.needAlphaTesting()) {
  81815. var alphaTexture = material.getAlphaTestTexture();
  81816. if (alphaTexture) {
  81817. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  81818. var textureMatrix = alphaTexture.getTextureMatrix();
  81819. if (textureMatrix) {
  81820. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  81821. }
  81822. }
  81823. }
  81824. // Glow emissive only
  81825. if (emissiveTexture) {
  81826. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  81827. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  81828. }
  81829. // Bones
  81830. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81831. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81832. }
  81833. // Draw
  81834. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  81835. }
  81836. else {
  81837. // Need to reset refresh rate of the shadowMap
  81838. _this._mainTexture.resetRefreshCounter();
  81839. }
  81840. };
  81841. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81842. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  81843. var index;
  81844. var engine = _this._scene.getEngine();
  81845. if (depthOnlySubMeshes.length) {
  81846. engine.setColorWrite(false);
  81847. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81848. renderSubMesh(depthOnlySubMeshes.data[index]);
  81849. }
  81850. engine.setColorWrite(true);
  81851. }
  81852. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81853. renderSubMesh(opaqueSubMeshes.data[index]);
  81854. }
  81855. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81856. renderSubMesh(alphaTestSubMeshes.data[index]);
  81857. }
  81858. for (index = 0; index < transparentSubMeshes.length; index++) {
  81859. renderSubMesh(transparentSubMeshes.data[index]);
  81860. }
  81861. };
  81862. this._mainTexture.onClearObservable.add(function (engine) {
  81863. engine.clear(HighlightLayer.neutralColor, true, true, true);
  81864. });
  81865. };
  81866. /**
  81867. * Checks for the readiness of the element composing the layer.
  81868. * @param subMesh the mesh to check for
  81869. * @param useInstances specify wether or not to use instances to render the mesh
  81870. * @param emissiveTexture the associated emissive texture used to generate the glow
  81871. * @return true if ready otherwise, false
  81872. */
  81873. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  81874. var material = subMesh.getMaterial();
  81875. var mesh = subMesh.getRenderingMesh();
  81876. if (!material || !mesh || !this._meshes) {
  81877. return false;
  81878. }
  81879. var emissiveTexture = null;
  81880. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  81881. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  81882. emissiveTexture = material.emissiveTexture;
  81883. }
  81884. return this._isReady(subMesh, useInstances, emissiveTexture);
  81885. };
  81886. /**
  81887. * Checks for the readiness of the element composing the layer.
  81888. * @param subMesh the mesh to check for
  81889. * @param useInstances specify wether or not to use instances to render the mesh
  81890. * @param emissiveTexture the associated emissive texture used to generate the glow
  81891. * @return true if ready otherwise, false
  81892. */
  81893. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  81894. var material = subMesh.getMaterial();
  81895. if (!material) {
  81896. return false;
  81897. }
  81898. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  81899. return false;
  81900. }
  81901. var defines = [];
  81902. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81903. var mesh = subMesh.getMesh();
  81904. var uv1 = false;
  81905. var uv2 = false;
  81906. // Alpha test
  81907. if (material && material.needAlphaTesting()) {
  81908. var alphaTexture = material.getAlphaTestTexture();
  81909. if (alphaTexture) {
  81910. defines.push("#define ALPHATEST");
  81911. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  81912. alphaTexture.coordinatesIndex === 1) {
  81913. defines.push("#define DIFFUSEUV2");
  81914. uv2 = true;
  81915. }
  81916. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81917. defines.push("#define DIFFUSEUV1");
  81918. uv1 = true;
  81919. }
  81920. }
  81921. }
  81922. // Emissive
  81923. if (emissiveTexture) {
  81924. defines.push("#define EMISSIVE");
  81925. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  81926. emissiveTexture.coordinatesIndex === 1) {
  81927. defines.push("#define EMISSIVEUV2");
  81928. uv2 = true;
  81929. }
  81930. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81931. defines.push("#define EMISSIVEUV1");
  81932. uv1 = true;
  81933. }
  81934. }
  81935. if (uv1) {
  81936. attribs.push(BABYLON.VertexBuffer.UVKind);
  81937. defines.push("#define UV1");
  81938. }
  81939. if (uv2) {
  81940. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81941. defines.push("#define UV2");
  81942. }
  81943. // Bones
  81944. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81945. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81946. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81947. if (mesh.numBoneInfluencers > 4) {
  81948. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81949. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81950. }
  81951. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81952. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81953. }
  81954. else {
  81955. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81956. }
  81957. // Instances
  81958. if (useInstances) {
  81959. defines.push("#define INSTANCES");
  81960. attribs.push("world0");
  81961. attribs.push("world1");
  81962. attribs.push("world2");
  81963. attribs.push("world3");
  81964. }
  81965. // Get correct effect
  81966. var join = defines.join("\n");
  81967. if (this._cachedDefines !== join) {
  81968. this._cachedDefines = join;
  81969. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  81970. }
  81971. return this._glowMapGenerationEffect.isReady();
  81972. };
  81973. /**
  81974. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  81975. */
  81976. HighlightLayer.prototype.render = function () {
  81977. var currentEffect = this._glowMapMergeEffect;
  81978. // Check
  81979. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  81980. return;
  81981. var engine = this._scene.getEngine();
  81982. this.onBeforeComposeObservable.notifyObservers(this);
  81983. // Render
  81984. engine.enableEffect(currentEffect);
  81985. engine.setState(false);
  81986. // Cache
  81987. var previousStencilBuffer = engine.getStencilBuffer();
  81988. var previousStencilFunction = engine.getStencilFunction();
  81989. var previousStencilMask = engine.getStencilMask();
  81990. var previousStencilOperationPass = engine.getStencilOperationPass();
  81991. var previousStencilOperationFail = engine.getStencilOperationFail();
  81992. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  81993. var previousAlphaMode = engine.getAlphaMode();
  81994. // Texture
  81995. currentEffect.setTexture("textureSampler", this._blurTexture);
  81996. // VBOs
  81997. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81998. // Stencil operations
  81999. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  82000. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  82001. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  82002. // Draw order
  82003. engine.setAlphaMode(this._options.alphaBlendingMode);
  82004. engine.setStencilMask(0x00);
  82005. engine.setStencilBuffer(true);
  82006. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  82007. if (this.outerGlow) {
  82008. currentEffect.setFloat("offset", 0);
  82009. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  82010. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82011. }
  82012. if (this.innerGlow) {
  82013. currentEffect.setFloat("offset", 1);
  82014. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  82015. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82016. }
  82017. // Restore Cache
  82018. engine.setStencilFunction(previousStencilFunction);
  82019. engine.setStencilMask(previousStencilMask);
  82020. engine.setAlphaMode(previousAlphaMode);
  82021. engine.setStencilBuffer(previousStencilBuffer);
  82022. engine.setStencilOperationPass(previousStencilOperationPass);
  82023. engine.setStencilOperationFail(previousStencilOperationFail);
  82024. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  82025. engine._stencilState.reset();
  82026. this.onAfterComposeObservable.notifyObservers(this);
  82027. // Handle size changes.
  82028. var size = this._mainTexture.getSize();
  82029. this.setMainTextureSize();
  82030. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82031. // Recreate RTT and post processes on size change.
  82032. this.onSizeChangedObservable.notifyObservers(this);
  82033. this.disposeTextureAndPostProcesses();
  82034. this.createTextureAndPostProcesses();
  82035. }
  82036. };
  82037. /**
  82038. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  82039. * @param mesh The mesh to exclude from the highlight layer
  82040. */
  82041. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  82042. if (!this._excludedMeshes) {
  82043. return;
  82044. }
  82045. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82046. if (!meshExcluded) {
  82047. this._excludedMeshes[mesh.uniqueId] = {
  82048. mesh: mesh,
  82049. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  82050. mesh.getEngine().setStencilBuffer(false);
  82051. }),
  82052. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  82053. mesh.getEngine().setStencilBuffer(true);
  82054. }),
  82055. };
  82056. }
  82057. };
  82058. /**
  82059. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  82060. * @param mesh The mesh to highlight
  82061. */
  82062. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  82063. if (!this._excludedMeshes) {
  82064. return;
  82065. }
  82066. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82067. if (meshExcluded) {
  82068. if (meshExcluded.beforeRender) {
  82069. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  82070. }
  82071. if (meshExcluded.afterRender) {
  82072. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  82073. }
  82074. }
  82075. this._excludedMeshes[mesh.uniqueId] = null;
  82076. };
  82077. /**
  82078. * Determine if a given mesh will be highlighted by the current HighlightLayer
  82079. * @param mesh mesh to test
  82080. * @returns true if the mesh will be highlighted by the current HighlightLayer
  82081. */
  82082. HighlightLayer.prototype.hasMesh = function (mesh) {
  82083. if (!this._meshes) {
  82084. return false;
  82085. }
  82086. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  82087. };
  82088. /**
  82089. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  82090. * @param mesh The mesh to highlight
  82091. * @param color The color of the highlight
  82092. * @param glowEmissiveOnly Extract the glow from the emissive texture
  82093. */
  82094. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  82095. var _this = this;
  82096. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  82097. if (!this._meshes) {
  82098. return;
  82099. }
  82100. var meshHighlight = this._meshes[mesh.uniqueId];
  82101. if (meshHighlight) {
  82102. meshHighlight.color = color;
  82103. }
  82104. else {
  82105. this._meshes[mesh.uniqueId] = {
  82106. mesh: mesh,
  82107. color: color,
  82108. // Lambda required for capture due to Observable this context
  82109. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  82110. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  82111. _this.defaultStencilReference(mesh);
  82112. }
  82113. else {
  82114. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  82115. }
  82116. }),
  82117. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  82118. glowEmissiveOnly: glowEmissiveOnly
  82119. };
  82120. }
  82121. this._shouldRender = true;
  82122. };
  82123. /**
  82124. * Remove a mesh from the highlight layer in order to make it stop glowing.
  82125. * @param mesh The mesh to highlight
  82126. */
  82127. HighlightLayer.prototype.removeMesh = function (mesh) {
  82128. if (!this._meshes) {
  82129. return;
  82130. }
  82131. var meshHighlight = this._meshes[mesh.uniqueId];
  82132. if (meshHighlight) {
  82133. if (meshHighlight.observerHighlight) {
  82134. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82135. }
  82136. if (meshHighlight.observerDefault) {
  82137. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82138. }
  82139. delete this._meshes[mesh.uniqueId];
  82140. }
  82141. this._shouldRender = false;
  82142. for (var meshHighlightToCheck in this._meshes) {
  82143. if (this._meshes[meshHighlightToCheck]) {
  82144. this._shouldRender = true;
  82145. break;
  82146. }
  82147. }
  82148. };
  82149. /**
  82150. * Returns true if the layer contains information to display, otherwise false.
  82151. */
  82152. HighlightLayer.prototype.shouldRender = function () {
  82153. return this.isEnabled && this._shouldRender;
  82154. };
  82155. /**
  82156. * Sets the main texture desired size which is the closest power of two
  82157. * of the engine canvas size.
  82158. */
  82159. HighlightLayer.prototype.setMainTextureSize = function () {
  82160. if (this._options.mainTextureFixedSize) {
  82161. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  82162. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  82163. }
  82164. else {
  82165. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  82166. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  82167. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82168. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82169. }
  82170. };
  82171. /**
  82172. * Force the stencil to the normal expected value for none glowing parts
  82173. */
  82174. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  82175. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  82176. };
  82177. /**
  82178. * Dispose only the render target textures and post process.
  82179. */
  82180. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  82181. this._blurTexture.dispose();
  82182. this._mainTexture.dispose();
  82183. this._downSamplePostprocess.dispose();
  82184. this._horizontalBlurPostprocess.dispose();
  82185. this._verticalBlurPostprocess.dispose();
  82186. };
  82187. /**
  82188. * Dispose the highlight layer and free resources.
  82189. */
  82190. HighlightLayer.prototype.dispose = function () {
  82191. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82192. if (vertexBuffer) {
  82193. vertexBuffer.dispose();
  82194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82195. }
  82196. if (this._indexBuffer) {
  82197. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82198. this._indexBuffer = null;
  82199. }
  82200. // Clean textures and post processes
  82201. this.disposeTextureAndPostProcesses();
  82202. if (this._meshes) {
  82203. // Clean mesh references
  82204. for (var id in this._meshes) {
  82205. var meshHighlight = this._meshes[id];
  82206. if (meshHighlight && meshHighlight.mesh) {
  82207. if (meshHighlight.observerHighlight) {
  82208. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82209. }
  82210. if (meshHighlight.observerDefault) {
  82211. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82212. }
  82213. }
  82214. }
  82215. this._meshes = null;
  82216. }
  82217. if (this._excludedMeshes) {
  82218. for (var id in this._excludedMeshes) {
  82219. var meshHighlight = this._excludedMeshes[id];
  82220. if (meshHighlight) {
  82221. if (meshHighlight.beforeRender) {
  82222. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  82223. }
  82224. if (meshHighlight.afterRender) {
  82225. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  82226. }
  82227. }
  82228. }
  82229. this._excludedMeshes = null;
  82230. }
  82231. // Remove from scene
  82232. var index = this._scene.highlightLayers.indexOf(this, 0);
  82233. if (index > -1) {
  82234. this._scene.highlightLayers.splice(index, 1);
  82235. }
  82236. // Callback
  82237. this.onDisposeObservable.notifyObservers(this);
  82238. this.onDisposeObservable.clear();
  82239. this.onBeforeRenderMainTextureObservable.clear();
  82240. this.onBeforeBlurObservable.clear();
  82241. this.onBeforeComposeObservable.clear();
  82242. this.onAfterComposeObservable.clear();
  82243. this.onSizeChangedObservable.clear();
  82244. };
  82245. /**
  82246. * The neutral color used during the preparation of the glow effect.
  82247. * This is black by default as the blend operation is a blend operation.
  82248. */
  82249. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  82250. /**
  82251. * Stencil value used for glowing meshes.
  82252. */
  82253. HighlightLayer.glowingMeshStencilReference = 0x02;
  82254. /**
  82255. * Stencil value used for the other meshes in the scene.
  82256. */
  82257. HighlightLayer.normalMeshStencilReference = 0x01;
  82258. return HighlightLayer;
  82259. }());
  82260. BABYLON.HighlightLayer = HighlightLayer;
  82261. })(BABYLON || (BABYLON = {}));
  82262. //# sourceMappingURL=babylon.highlightlayer.js.map
  82263. var BABYLON;
  82264. (function (BABYLON) {
  82265. /**
  82266. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  82267. */
  82268. var AssetTaskState;
  82269. (function (AssetTaskState) {
  82270. /**
  82271. * Initialization
  82272. */
  82273. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  82274. /**
  82275. * Running
  82276. */
  82277. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  82278. /**
  82279. * Done
  82280. */
  82281. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  82282. /**
  82283. * Error
  82284. */
  82285. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  82286. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  82287. /**
  82288. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  82289. */
  82290. var AbstractAssetTask = /** @class */ (function () {
  82291. /**
  82292. * Creates a new {BABYLON.AssetsManager}
  82293. * @param name defines the name of the task
  82294. */
  82295. function AbstractAssetTask(
  82296. /**
  82297. * Task name
  82298. */ name) {
  82299. this.name = name;
  82300. this._isCompleted = false;
  82301. this._taskState = AssetTaskState.INIT;
  82302. }
  82303. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  82304. /**
  82305. * Get if the task is completed
  82306. */
  82307. get: function () {
  82308. return this._isCompleted;
  82309. },
  82310. enumerable: true,
  82311. configurable: true
  82312. });
  82313. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  82314. /**
  82315. * Gets the current state of the task
  82316. */
  82317. get: function () {
  82318. return this._taskState;
  82319. },
  82320. enumerable: true,
  82321. configurable: true
  82322. });
  82323. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  82324. /**
  82325. * Gets the current error object (if task is in error)
  82326. */
  82327. get: function () {
  82328. return this._errorObject;
  82329. },
  82330. enumerable: true,
  82331. configurable: true
  82332. });
  82333. /**
  82334. * Internal only
  82335. * @ignore
  82336. */
  82337. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  82338. if (this._errorObject) {
  82339. return;
  82340. }
  82341. this._errorObject = {
  82342. message: message,
  82343. exception: exception
  82344. };
  82345. };
  82346. /**
  82347. * Execute the current task
  82348. * @param scene defines the scene where you want your assets to be loaded
  82349. * @param onSuccess is a callback called when the task is successfully executed
  82350. * @param onError is a callback called if an error occurs
  82351. */
  82352. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  82353. var _this = this;
  82354. this._taskState = AssetTaskState.RUNNING;
  82355. this.runTask(scene, function () {
  82356. _this.onDoneCallback(onSuccess, onError);
  82357. }, function (msg, exception) {
  82358. _this.onErrorCallback(onError, msg, exception);
  82359. });
  82360. };
  82361. /**
  82362. * Execute the current task
  82363. * @param scene defines the scene where you want your assets to be loaded
  82364. * @param onSuccess is a callback called when the task is successfully executed
  82365. * @param onError is a callback called if an error occurs
  82366. */
  82367. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82368. throw new Error("runTask is not implemented");
  82369. };
  82370. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  82371. this._taskState = AssetTaskState.ERROR;
  82372. this._errorObject = {
  82373. message: message,
  82374. exception: exception
  82375. };
  82376. if (this.onError) {
  82377. this.onError(this, message, exception);
  82378. }
  82379. onError();
  82380. };
  82381. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  82382. try {
  82383. this._taskState = AssetTaskState.DONE;
  82384. this._isCompleted = true;
  82385. if (this.onSuccess) {
  82386. this.onSuccess(this);
  82387. }
  82388. onSuccess();
  82389. }
  82390. catch (e) {
  82391. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  82392. }
  82393. };
  82394. return AbstractAssetTask;
  82395. }());
  82396. BABYLON.AbstractAssetTask = AbstractAssetTask;
  82397. /**
  82398. * Class used to share progress information about assets loading
  82399. */
  82400. var AssetsProgressEvent = /** @class */ (function () {
  82401. /**
  82402. * Creates a {BABYLON.AssetsProgressEvent}
  82403. * @param remainingCount defines the number of remaining tasks to process
  82404. * @param totalCount defines the total number of tasks
  82405. * @param task defines the task that was just processed
  82406. */
  82407. function AssetsProgressEvent(remainingCount, totalCount, task) {
  82408. this.remainingCount = remainingCount;
  82409. this.totalCount = totalCount;
  82410. this.task = task;
  82411. }
  82412. return AssetsProgressEvent;
  82413. }());
  82414. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  82415. /**
  82416. * Define a task used by {BABYLON.AssetsManager} to load meshes
  82417. */
  82418. var MeshAssetTask = /** @class */ (function (_super) {
  82419. __extends(MeshAssetTask, _super);
  82420. /**
  82421. * Creates a new {BABYLON.MeshAssetTask}
  82422. * @param name defines the name of the task
  82423. * @param meshesNames defines the list of mesh's names you want to load
  82424. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  82425. * @param sceneFilename defines the filename of the scene to load from
  82426. */
  82427. function MeshAssetTask(
  82428. /**
  82429. * Defines the name of the task
  82430. */
  82431. name,
  82432. /**
  82433. * Defines the list of mesh's names you want to load
  82434. */
  82435. meshesNames,
  82436. /**
  82437. * Defines the root url to use as a base to load your meshes and associated resources
  82438. */
  82439. rootUrl,
  82440. /**
  82441. * Defines the filename of the scene to load from
  82442. */
  82443. sceneFilename) {
  82444. var _this = _super.call(this, name) || this;
  82445. _this.name = name;
  82446. _this.meshesNames = meshesNames;
  82447. _this.rootUrl = rootUrl;
  82448. _this.sceneFilename = sceneFilename;
  82449. return _this;
  82450. }
  82451. /**
  82452. * Execute the current task
  82453. * @param scene defines the scene where you want your assets to be loaded
  82454. * @param onSuccess is a callback called when the task is successfully executed
  82455. * @param onError is a callback called if an error occurs
  82456. */
  82457. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82458. var _this = this;
  82459. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  82460. _this.loadedMeshes = meshes;
  82461. _this.loadedParticleSystems = particleSystems;
  82462. _this.loadedSkeletons = skeletons;
  82463. onSuccess();
  82464. }, null, function (scene, message, exception) {
  82465. onError(message, exception);
  82466. });
  82467. };
  82468. return MeshAssetTask;
  82469. }(AbstractAssetTask));
  82470. BABYLON.MeshAssetTask = MeshAssetTask;
  82471. /**
  82472. * Define a task used by {BABYLON.AssetsManager} to load text content
  82473. */
  82474. var TextFileAssetTask = /** @class */ (function (_super) {
  82475. __extends(TextFileAssetTask, _super);
  82476. /**
  82477. * Creates a new TextFileAssetTask object
  82478. * @param name defines the name of the task
  82479. * @param url defines the location of the file to load
  82480. */
  82481. function TextFileAssetTask(
  82482. /**
  82483. * Defines the name of the task
  82484. */
  82485. name,
  82486. /**
  82487. * Defines the location of the file to load
  82488. */
  82489. url) {
  82490. var _this = _super.call(this, name) || this;
  82491. _this.name = name;
  82492. _this.url = url;
  82493. return _this;
  82494. }
  82495. /**
  82496. * Execute the current task
  82497. * @param scene defines the scene where you want your assets to be loaded
  82498. * @param onSuccess is a callback called when the task is successfully executed
  82499. * @param onError is a callback called if an error occurs
  82500. */
  82501. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82502. var _this = this;
  82503. scene._loadFile(this.url, function (data) {
  82504. _this.text = data;
  82505. onSuccess();
  82506. }, undefined, false, true, function (request, exception) {
  82507. if (request) {
  82508. onError(request.status + " " + request.statusText, exception);
  82509. }
  82510. });
  82511. };
  82512. return TextFileAssetTask;
  82513. }(AbstractAssetTask));
  82514. BABYLON.TextFileAssetTask = TextFileAssetTask;
  82515. /**
  82516. * Define a task used by {BABYLON.AssetsManager} to load binary data
  82517. */
  82518. var BinaryFileAssetTask = /** @class */ (function (_super) {
  82519. __extends(BinaryFileAssetTask, _super);
  82520. /**
  82521. * Creates a new BinaryFileAssetTask object
  82522. * @param name defines the name of the new task
  82523. * @param url defines the location of the file to load
  82524. */
  82525. function BinaryFileAssetTask(
  82526. /**
  82527. * Defines the name of the task
  82528. */
  82529. name,
  82530. /**
  82531. * Defines the location of the file to load
  82532. */
  82533. url) {
  82534. var _this = _super.call(this, name) || this;
  82535. _this.name = name;
  82536. _this.url = url;
  82537. return _this;
  82538. }
  82539. /**
  82540. * Execute the current task
  82541. * @param scene defines the scene where you want your assets to be loaded
  82542. * @param onSuccess is a callback called when the task is successfully executed
  82543. * @param onError is a callback called if an error occurs
  82544. */
  82545. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82546. var _this = this;
  82547. scene._loadFile(this.url, function (data) {
  82548. _this.data = data;
  82549. onSuccess();
  82550. }, undefined, true, true, function (request, exception) {
  82551. if (request) {
  82552. onError(request.status + " " + request.statusText, exception);
  82553. }
  82554. });
  82555. };
  82556. return BinaryFileAssetTask;
  82557. }(AbstractAssetTask));
  82558. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  82559. /**
  82560. * Define a task used by {BABYLON.AssetsManager} to load images
  82561. */
  82562. var ImageAssetTask = /** @class */ (function (_super) {
  82563. __extends(ImageAssetTask, _super);
  82564. /**
  82565. * Creates a new ImageAssetTask
  82566. * @param name defines the name of the task
  82567. * @param url defines the location of the image to load
  82568. */
  82569. function ImageAssetTask(
  82570. /**
  82571. * Defines the name of the task
  82572. */
  82573. name,
  82574. /**
  82575. * Defines the location of the image to load
  82576. */
  82577. url) {
  82578. var _this = _super.call(this, name) || this;
  82579. _this.name = name;
  82580. _this.url = url;
  82581. return _this;
  82582. }
  82583. /**
  82584. * Execute the current task
  82585. * @param scene defines the scene where you want your assets to be loaded
  82586. * @param onSuccess is a callback called when the task is successfully executed
  82587. * @param onError is a callback called if an error occurs
  82588. */
  82589. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82590. var _this = this;
  82591. var img = new Image();
  82592. BABYLON.Tools.SetCorsBehavior(this.url, img);
  82593. img.onload = function () {
  82594. _this.image = img;
  82595. onSuccess();
  82596. };
  82597. img.onerror = function (err) {
  82598. onError("Error loading image", err);
  82599. };
  82600. img.src = this.url;
  82601. };
  82602. return ImageAssetTask;
  82603. }(AbstractAssetTask));
  82604. BABYLON.ImageAssetTask = ImageAssetTask;
  82605. /**
  82606. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  82607. */
  82608. var TextureAssetTask = /** @class */ (function (_super) {
  82609. __extends(TextureAssetTask, _super);
  82610. /**
  82611. * Creates a new TextureAssetTask object
  82612. * @param name defines the name of the task
  82613. * @param url defines the location of the file to load
  82614. * @param noMipmap defines if mipmap should not be generated (default is false)
  82615. * @param invertY defines if texture must be inverted on Y axis (default is false)
  82616. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  82617. */
  82618. function TextureAssetTask(
  82619. /**
  82620. * Defines the name of the task
  82621. */
  82622. name,
  82623. /**
  82624. * Defines the location of the file to load
  82625. */
  82626. url,
  82627. /**
  82628. * Defines if mipmap should not be generated (default is false)
  82629. */
  82630. noMipmap,
  82631. /**
  82632. * Defines if texture must be inverted on Y axis (default is false)
  82633. */
  82634. invertY,
  82635. /**
  82636. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  82637. */
  82638. samplingMode) {
  82639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  82640. var _this = _super.call(this, name) || this;
  82641. _this.name = name;
  82642. _this.url = url;
  82643. _this.noMipmap = noMipmap;
  82644. _this.invertY = invertY;
  82645. _this.samplingMode = samplingMode;
  82646. return _this;
  82647. }
  82648. /**
  82649. * Execute the current task
  82650. * @param scene defines the scene where you want your assets to be loaded
  82651. * @param onSuccess is a callback called when the task is successfully executed
  82652. * @param onError is a callback called if an error occurs
  82653. */
  82654. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82655. var onload = function () {
  82656. onSuccess();
  82657. };
  82658. var onerror = function (message, exception) {
  82659. onError(message, exception);
  82660. };
  82661. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  82662. };
  82663. return TextureAssetTask;
  82664. }(AbstractAssetTask));
  82665. BABYLON.TextureAssetTask = TextureAssetTask;
  82666. /**
  82667. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  82668. */
  82669. var CubeTextureAssetTask = /** @class */ (function (_super) {
  82670. __extends(CubeTextureAssetTask, _super);
  82671. /**
  82672. * Creates a new CubeTextureAssetTask
  82673. * @param name defines the name of the task
  82674. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  82675. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  82676. * @param noMipmap defines if mipmaps should not be generated (default is false)
  82677. * @param files defines the explicit list of files (undefined by default)
  82678. */
  82679. function CubeTextureAssetTask(
  82680. /**
  82681. * Defines the name of the task
  82682. */
  82683. name,
  82684. /**
  82685. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  82686. */
  82687. url,
  82688. /**
  82689. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  82690. */
  82691. extensions,
  82692. /**
  82693. * Defines if mipmaps should not be generated (default is false)
  82694. */
  82695. noMipmap,
  82696. /**
  82697. * Defines the explicit list of files (undefined by default)
  82698. */
  82699. files) {
  82700. var _this = _super.call(this, name) || this;
  82701. _this.name = name;
  82702. _this.url = url;
  82703. _this.extensions = extensions;
  82704. _this.noMipmap = noMipmap;
  82705. _this.files = files;
  82706. return _this;
  82707. }
  82708. /**
  82709. * Execute the current task
  82710. * @param scene defines the scene where you want your assets to be loaded
  82711. * @param onSuccess is a callback called when the task is successfully executed
  82712. * @param onError is a callback called if an error occurs
  82713. */
  82714. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82715. var onload = function () {
  82716. onSuccess();
  82717. };
  82718. var onerror = function (message, exception) {
  82719. onError(message, exception);
  82720. };
  82721. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  82722. };
  82723. return CubeTextureAssetTask;
  82724. }(AbstractAssetTask));
  82725. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  82726. /**
  82727. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  82728. */
  82729. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  82730. __extends(HDRCubeTextureAssetTask, _super);
  82731. /**
  82732. * Creates a new HDRCubeTextureAssetTask object
  82733. * @param name defines the name of the task
  82734. * @param url defines the location of the file to load
  82735. * @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.
  82736. * @param noMipmap defines if mipmaps should not be generated (default is false)
  82737. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  82738. * @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)
  82739. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  82740. */
  82741. function HDRCubeTextureAssetTask(
  82742. /**
  82743. * Defines the name of the task
  82744. */
  82745. name,
  82746. /**
  82747. * Defines the location of the file to load
  82748. */
  82749. url,
  82750. /**
  82751. * 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.
  82752. */
  82753. size,
  82754. /**
  82755. * Defines if mipmaps should not be generated (default is false)
  82756. */
  82757. noMipmap,
  82758. /**
  82759. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  82760. */
  82761. generateHarmonics,
  82762. /**
  82763. * 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)
  82764. */
  82765. useInGammaSpace,
  82766. /**
  82767. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  82768. */
  82769. usePMREMGenerator) {
  82770. if (noMipmap === void 0) { noMipmap = false; }
  82771. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82772. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  82773. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  82774. var _this = _super.call(this, name) || this;
  82775. _this.name = name;
  82776. _this.url = url;
  82777. _this.size = size;
  82778. _this.noMipmap = noMipmap;
  82779. _this.generateHarmonics = generateHarmonics;
  82780. _this.useInGammaSpace = useInGammaSpace;
  82781. _this.usePMREMGenerator = usePMREMGenerator;
  82782. return _this;
  82783. }
  82784. /**
  82785. * Execute the current task
  82786. * @param scene defines the scene where you want your assets to be loaded
  82787. * @param onSuccess is a callback called when the task is successfully executed
  82788. * @param onError is a callback called if an error occurs
  82789. */
  82790. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  82791. var onload = function () {
  82792. onSuccess();
  82793. };
  82794. var onerror = function (message, exception) {
  82795. onError(message, exception);
  82796. };
  82797. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  82798. };
  82799. return HDRCubeTextureAssetTask;
  82800. }(AbstractAssetTask));
  82801. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  82802. /**
  82803. * This class can be used to easily import assets into a scene
  82804. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  82805. */
  82806. var AssetsManager = /** @class */ (function () {
  82807. /**
  82808. * Creates a new AssetsManager
  82809. * @param scene defines the scene to work on
  82810. */
  82811. function AssetsManager(scene) {
  82812. this._isLoading = false;
  82813. this._tasks = new Array();
  82814. this._waitingTasksCount = 0;
  82815. this._totalTasksCount = 0;
  82816. /**
  82817. * Observable called when all tasks are processed
  82818. */
  82819. this.onTaskSuccessObservable = new BABYLON.Observable();
  82820. /**
  82821. * Observable called when a task had an error
  82822. */
  82823. this.onTaskErrorObservable = new BABYLON.Observable();
  82824. /**
  82825. * Observable called when a task is successful
  82826. */
  82827. this.onTasksDoneObservable = new BABYLON.Observable();
  82828. /**
  82829. * Observable called when a task is done (whatever the result is)
  82830. */
  82831. this.onProgressObservable = new BABYLON.Observable();
  82832. /**
  82833. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  82834. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  82835. */
  82836. this.useDefaultLoadingScreen = true;
  82837. this._scene = scene;
  82838. }
  82839. /**
  82840. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  82841. * @param taskName defines the name of the new task
  82842. * @param meshesNames defines the name of meshes to load
  82843. * @param rootUrl defines the root url to use to locate files
  82844. * @param sceneFilename defines the filename of the scene file
  82845. * @returns a new {BABYLON.MeshAssetTask} object
  82846. */
  82847. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  82848. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  82849. this._tasks.push(task);
  82850. return task;
  82851. };
  82852. /**
  82853. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  82854. * @param taskName defines the name of the new task
  82855. * @param url defines the url of the file to load
  82856. * @returns a new {BABYLON.TextFileAssetTask} object
  82857. */
  82858. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  82859. var task = new TextFileAssetTask(taskName, url);
  82860. this._tasks.push(task);
  82861. return task;
  82862. };
  82863. /**
  82864. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  82865. * @param taskName defines the name of the new task
  82866. * @param url defines the url of the file to load
  82867. * @returns a new {BABYLON.BinaryFileAssetTask} object
  82868. */
  82869. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  82870. var task = new BinaryFileAssetTask(taskName, url);
  82871. this._tasks.push(task);
  82872. return task;
  82873. };
  82874. /**
  82875. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  82876. * @param taskName defines the name of the new task
  82877. * @param url defines the url of the file to load
  82878. * @returns a new {BABYLON.ImageAssetTask} object
  82879. */
  82880. AssetsManager.prototype.addImageTask = function (taskName, url) {
  82881. var task = new ImageAssetTask(taskName, url);
  82882. this._tasks.push(task);
  82883. return task;
  82884. };
  82885. /**
  82886. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  82887. * @param taskName defines the name of the new task
  82888. * @param url defines the url of the file to load
  82889. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  82890. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  82891. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  82892. * @returns a new {BABYLON.TextureAssetTask} object
  82893. */
  82894. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  82895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  82896. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  82897. this._tasks.push(task);
  82898. return task;
  82899. };
  82900. /**
  82901. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  82902. * @param taskName defines the name of the new task
  82903. * @param url defines the url of the file to load
  82904. * @param extensions defines the extension to use to load the cube map (can be null)
  82905. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  82906. * @param files defines the list of files to load (can be null)
  82907. * @returns a new {BABYLON.CubeTextureAssetTask} object
  82908. */
  82909. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  82910. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  82911. this._tasks.push(task);
  82912. return task;
  82913. };
  82914. /**
  82915. *
  82916. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  82917. * @param taskName defines the name of the new task
  82918. * @param url defines the url of the file to load
  82919. * @param size defines the size you want for the cubemap (can be null)
  82920. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  82921. * @param generateHarmonics defines if you want to automatically generate (true by default)
  82922. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  82923. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  82924. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  82925. */
  82926. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  82927. if (noMipmap === void 0) { noMipmap = false; }
  82928. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82929. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  82930. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  82931. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  82932. this._tasks.push(task);
  82933. return task;
  82934. };
  82935. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  82936. var _this = this;
  82937. this._waitingTasksCount--;
  82938. try {
  82939. if (task.taskState === AssetTaskState.DONE) {
  82940. // Let's remove successfull tasks
  82941. BABYLON.Tools.SetImmediate(function () {
  82942. var index = _this._tasks.indexOf(task);
  82943. if (index > -1) {
  82944. _this._tasks.splice(index, 1);
  82945. }
  82946. });
  82947. }
  82948. if (this.onProgress) {
  82949. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  82950. }
  82951. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  82952. }
  82953. catch (e) {
  82954. BABYLON.Tools.Error("Error running progress callbacks.");
  82955. console.log(e);
  82956. }
  82957. if (this._waitingTasksCount === 0) {
  82958. try {
  82959. if (this.onFinish) {
  82960. this.onFinish(this._tasks);
  82961. }
  82962. this.onTasksDoneObservable.notifyObservers(this._tasks);
  82963. }
  82964. catch (e) {
  82965. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  82966. console.log(e);
  82967. }
  82968. this._isLoading = false;
  82969. this._scene.getEngine().hideLoadingUI();
  82970. }
  82971. };
  82972. AssetsManager.prototype._runTask = function (task) {
  82973. var _this = this;
  82974. var done = function () {
  82975. try {
  82976. if (_this.onTaskSuccess) {
  82977. _this.onTaskSuccess(task);
  82978. }
  82979. _this.onTaskSuccessObservable.notifyObservers(task);
  82980. _this._decreaseWaitingTasksCount(task);
  82981. }
  82982. catch (e) {
  82983. error("Error executing task success callbacks", e);
  82984. }
  82985. };
  82986. var error = function (message, exception) {
  82987. task._setErrorObject(message, exception);
  82988. if (_this.onTaskError) {
  82989. _this.onTaskError(task);
  82990. }
  82991. _this.onTaskErrorObservable.notifyObservers(task);
  82992. _this._decreaseWaitingTasksCount(task);
  82993. };
  82994. task.run(this._scene, done, error);
  82995. };
  82996. /**
  82997. * Reset the {BABYLON.AssetsManager} and remove all tasks
  82998. * @return the current instance of the {BABYLON.AssetsManager}
  82999. */
  83000. AssetsManager.prototype.reset = function () {
  83001. this._isLoading = false;
  83002. this._tasks = new Array();
  83003. return this;
  83004. };
  83005. /**
  83006. * Start the loading process
  83007. * @return the current instance of the {BABYLON.AssetsManager}
  83008. */
  83009. AssetsManager.prototype.load = function () {
  83010. if (this._isLoading) {
  83011. return this;
  83012. }
  83013. this._isLoading = true;
  83014. this._waitingTasksCount = this._tasks.length;
  83015. this._totalTasksCount = this._tasks.length;
  83016. if (this._waitingTasksCount === 0) {
  83017. if (this.onFinish) {
  83018. this.onFinish(this._tasks);
  83019. }
  83020. this.onTasksDoneObservable.notifyObservers(this._tasks);
  83021. return this;
  83022. }
  83023. if (this.useDefaultLoadingScreen) {
  83024. this._scene.getEngine().displayLoadingUI();
  83025. }
  83026. for (var index = 0; index < this._tasks.length; index++) {
  83027. var task = this._tasks[index];
  83028. this._runTask(task);
  83029. }
  83030. return this;
  83031. };
  83032. return AssetsManager;
  83033. }());
  83034. BABYLON.AssetsManager = AssetsManager;
  83035. })(BABYLON || (BABYLON = {}));
  83036. //# sourceMappingURL=babylon.assetsManager.js.map
  83037. var BABYLON;
  83038. (function (BABYLON) {
  83039. var serializedGeometries = [];
  83040. var serializeGeometry = function (geometry, serializationGeometries) {
  83041. if (serializedGeometries[geometry.id]) {
  83042. return;
  83043. }
  83044. if (geometry.doNotSerialize) {
  83045. return;
  83046. }
  83047. if (geometry instanceof BABYLON.BoxGeometry) {
  83048. serializationGeometries.boxes.push(geometry.serialize());
  83049. }
  83050. else if (geometry instanceof BABYLON.SphereGeometry) {
  83051. serializationGeometries.spheres.push(geometry.serialize());
  83052. }
  83053. else if (geometry instanceof BABYLON.CylinderGeometry) {
  83054. serializationGeometries.cylinders.push(geometry.serialize());
  83055. }
  83056. else if (geometry instanceof BABYLON.TorusGeometry) {
  83057. serializationGeometries.toruses.push(geometry.serialize());
  83058. }
  83059. else if (geometry instanceof BABYLON.GroundGeometry) {
  83060. serializationGeometries.grounds.push(geometry.serialize());
  83061. }
  83062. else if (geometry instanceof BABYLON.Plane) {
  83063. serializationGeometries.planes.push(geometry.serialize());
  83064. }
  83065. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  83066. serializationGeometries.torusKnots.push(geometry.serialize());
  83067. }
  83068. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  83069. throw new Error("Unknown primitive type");
  83070. }
  83071. else {
  83072. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  83073. }
  83074. serializedGeometries[geometry.id] = true;
  83075. };
  83076. var serializeMesh = function (mesh, serializationScene) {
  83077. var serializationObject = {};
  83078. // Geometry
  83079. var geometry = mesh._geometry;
  83080. if (geometry) {
  83081. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  83082. // 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
  83083. serializeGeometry(geometry, serializationScene.geometries);
  83084. }
  83085. }
  83086. // Custom
  83087. if (mesh.serialize) {
  83088. mesh.serialize(serializationObject);
  83089. }
  83090. return serializationObject;
  83091. };
  83092. var finalizeSingleMesh = function (mesh, serializationObject) {
  83093. //only works if the mesh is already loaded
  83094. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  83095. //serialize material
  83096. if (mesh.material) {
  83097. if (mesh.material instanceof BABYLON.StandardMaterial) {
  83098. serializationObject.materials = serializationObject.materials || [];
  83099. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  83100. serializationObject.materials.push(mesh.material.serialize());
  83101. }
  83102. }
  83103. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  83104. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  83105. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  83106. serializationObject.multiMaterials.push(mesh.material.serialize());
  83107. }
  83108. }
  83109. }
  83110. //serialize geometry
  83111. var geometry = mesh._geometry;
  83112. if (geometry) {
  83113. if (!serializationObject.geometries) {
  83114. serializationObject.geometries = {};
  83115. serializationObject.geometries.boxes = [];
  83116. serializationObject.geometries.spheres = [];
  83117. serializationObject.geometries.cylinders = [];
  83118. serializationObject.geometries.toruses = [];
  83119. serializationObject.geometries.grounds = [];
  83120. serializationObject.geometries.planes = [];
  83121. serializationObject.geometries.torusKnots = [];
  83122. serializationObject.geometries.vertexData = [];
  83123. }
  83124. serializeGeometry(geometry, serializationObject.geometries);
  83125. }
  83126. // Skeletons
  83127. if (mesh.skeleton) {
  83128. serializationObject.skeletons = serializationObject.skeletons || [];
  83129. serializationObject.skeletons.push(mesh.skeleton.serialize());
  83130. }
  83131. //serialize the actual mesh
  83132. serializationObject.meshes = serializationObject.meshes || [];
  83133. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  83134. }
  83135. };
  83136. var SceneSerializer = /** @class */ (function () {
  83137. function SceneSerializer() {
  83138. }
  83139. SceneSerializer.ClearCache = function () {
  83140. serializedGeometries = [];
  83141. };
  83142. SceneSerializer.Serialize = function (scene) {
  83143. var serializationObject = {};
  83144. SceneSerializer.ClearCache();
  83145. // Scene
  83146. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  83147. serializationObject.autoClear = scene.autoClear;
  83148. serializationObject.clearColor = scene.clearColor.asArray();
  83149. serializationObject.ambientColor = scene.ambientColor.asArray();
  83150. serializationObject.gravity = scene.gravity.asArray();
  83151. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  83152. serializationObject.workerCollisions = scene.workerCollisions;
  83153. // Fog
  83154. if (scene.fogMode && scene.fogMode !== 0) {
  83155. serializationObject.fogMode = scene.fogMode;
  83156. serializationObject.fogColor = scene.fogColor.asArray();
  83157. serializationObject.fogStart = scene.fogStart;
  83158. serializationObject.fogEnd = scene.fogEnd;
  83159. serializationObject.fogDensity = scene.fogDensity;
  83160. }
  83161. //Physics
  83162. if (scene.isPhysicsEnabled()) {
  83163. var physicEngine = scene.getPhysicsEngine();
  83164. if (physicEngine) {
  83165. serializationObject.physicsEnabled = true;
  83166. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  83167. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  83168. }
  83169. }
  83170. // Metadata
  83171. if (scene.metadata) {
  83172. serializationObject.metadata = scene.metadata;
  83173. }
  83174. // Morph targets
  83175. serializationObject.morphTargetManagers = [];
  83176. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  83177. var abstractMesh = _a[_i];
  83178. var manager = abstractMesh.morphTargetManager;
  83179. if (manager) {
  83180. serializationObject.morphTargetManagers.push(manager.serialize());
  83181. }
  83182. }
  83183. // Lights
  83184. serializationObject.lights = [];
  83185. var index;
  83186. var light;
  83187. for (index = 0; index < scene.lights.length; index++) {
  83188. light = scene.lights[index];
  83189. if (!light.doNotSerialize) {
  83190. serializationObject.lights.push(light.serialize());
  83191. }
  83192. }
  83193. // Cameras
  83194. serializationObject.cameras = [];
  83195. for (index = 0; index < scene.cameras.length; index++) {
  83196. var camera = scene.cameras[index];
  83197. if (!camera.doNotSerialize) {
  83198. serializationObject.cameras.push(camera.serialize());
  83199. }
  83200. }
  83201. if (scene.activeCamera) {
  83202. serializationObject.activeCameraID = scene.activeCamera.id;
  83203. }
  83204. // Animations
  83205. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  83206. // Materials
  83207. serializationObject.materials = [];
  83208. serializationObject.multiMaterials = [];
  83209. var material;
  83210. for (index = 0; index < scene.materials.length; index++) {
  83211. material = scene.materials[index];
  83212. if (!material.doNotSerialize) {
  83213. serializationObject.materials.push(material.serialize());
  83214. }
  83215. }
  83216. // MultiMaterials
  83217. serializationObject.multiMaterials = [];
  83218. for (index = 0; index < scene.multiMaterials.length; index++) {
  83219. var multiMaterial = scene.multiMaterials[index];
  83220. serializationObject.multiMaterials.push(multiMaterial.serialize());
  83221. }
  83222. // Environment texture
  83223. if (scene.environmentTexture) {
  83224. serializationObject.environmentTexture = scene.environmentTexture.name;
  83225. }
  83226. // Skeletons
  83227. serializationObject.skeletons = [];
  83228. for (index = 0; index < scene.skeletons.length; index++) {
  83229. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  83230. }
  83231. // Transform nodes
  83232. serializationObject.transformNodes = [];
  83233. for (index = 0; index < scene.transformNodes.length; index++) {
  83234. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  83235. }
  83236. // Geometries
  83237. serializationObject.geometries = {};
  83238. serializationObject.geometries.boxes = [];
  83239. serializationObject.geometries.spheres = [];
  83240. serializationObject.geometries.cylinders = [];
  83241. serializationObject.geometries.toruses = [];
  83242. serializationObject.geometries.grounds = [];
  83243. serializationObject.geometries.planes = [];
  83244. serializationObject.geometries.torusKnots = [];
  83245. serializationObject.geometries.vertexData = [];
  83246. serializedGeometries = [];
  83247. var geometries = scene.getGeometries();
  83248. for (index = 0; index < geometries.length; index++) {
  83249. var geometry = geometries[index];
  83250. if (geometry.isReady()) {
  83251. serializeGeometry(geometry, serializationObject.geometries);
  83252. }
  83253. }
  83254. // Meshes
  83255. serializationObject.meshes = [];
  83256. for (index = 0; index < scene.meshes.length; index++) {
  83257. var abstractMesh = scene.meshes[index];
  83258. if (abstractMesh instanceof BABYLON.Mesh) {
  83259. var mesh = abstractMesh;
  83260. if (!mesh.doNotSerialize) {
  83261. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  83262. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  83263. }
  83264. }
  83265. }
  83266. }
  83267. // Particles Systems
  83268. serializationObject.particleSystems = [];
  83269. for (index = 0; index < scene.particleSystems.length; index++) {
  83270. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  83271. }
  83272. // Lens flares
  83273. serializationObject.lensFlareSystems = [];
  83274. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  83275. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  83276. }
  83277. // Shadows
  83278. serializationObject.shadowGenerators = [];
  83279. for (index = 0; index < scene.lights.length; index++) {
  83280. light = scene.lights[index];
  83281. var shadowGenerator = light.getShadowGenerator();
  83282. if (shadowGenerator) {
  83283. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  83284. }
  83285. }
  83286. // Action Manager
  83287. if (scene.actionManager) {
  83288. serializationObject.actions = scene.actionManager.serialize("scene");
  83289. }
  83290. // Audio
  83291. serializationObject.sounds = [];
  83292. for (index = 0; index < scene.soundTracks.length; index++) {
  83293. var soundtrack = scene.soundTracks[index];
  83294. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  83295. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  83296. }
  83297. }
  83298. return serializationObject;
  83299. };
  83300. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  83301. if (withParents === void 0) { withParents = false; }
  83302. if (withChildren === void 0) { withChildren = false; }
  83303. var serializationObject = {};
  83304. SceneSerializer.ClearCache();
  83305. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  83306. if (withParents || withChildren) {
  83307. //deliberate for loop! not for each, appended should be processed as well.
  83308. for (var i = 0; i < toSerialize.length; ++i) {
  83309. if (withChildren) {
  83310. toSerialize[i].getDescendants().forEach(function (node) {
  83311. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  83312. toSerialize.push(node);
  83313. }
  83314. });
  83315. }
  83316. //make sure the array doesn't contain the object already
  83317. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  83318. toSerialize.push(toSerialize[i].parent);
  83319. }
  83320. }
  83321. }
  83322. toSerialize.forEach(function (mesh) {
  83323. finalizeSingleMesh(mesh, serializationObject);
  83324. });
  83325. return serializationObject;
  83326. };
  83327. return SceneSerializer;
  83328. }());
  83329. BABYLON.SceneSerializer = SceneSerializer;
  83330. })(BABYLON || (BABYLON = {}));
  83331. //# sourceMappingURL=babylon.sceneSerializer.js.map
  83332. var BABYLON;
  83333. (function (BABYLON) {
  83334. var ReflectionProbe = /** @class */ (function () {
  83335. function ReflectionProbe(name, size, scene, generateMipMaps) {
  83336. if (generateMipMaps === void 0) { generateMipMaps = true; }
  83337. var _this = this;
  83338. this.name = name;
  83339. this._viewMatrix = BABYLON.Matrix.Identity();
  83340. this._target = BABYLON.Vector3.Zero();
  83341. this._add = BABYLON.Vector3.Zero();
  83342. this.invertYAxis = false;
  83343. this.position = BABYLON.Vector3.Zero();
  83344. this._scene = scene;
  83345. this._scene.reflectionProbes.push(this);
  83346. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  83347. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  83348. switch (faceIndex) {
  83349. case 0:
  83350. _this._add.copyFromFloats(1, 0, 0);
  83351. break;
  83352. case 1:
  83353. _this._add.copyFromFloats(-1, 0, 0);
  83354. break;
  83355. case 2:
  83356. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  83357. break;
  83358. case 3:
  83359. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  83360. break;
  83361. case 4:
  83362. _this._add.copyFromFloats(0, 0, 1);
  83363. break;
  83364. case 5:
  83365. _this._add.copyFromFloats(0, 0, -1);
  83366. break;
  83367. }
  83368. if (_this._attachedMesh) {
  83369. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  83370. }
  83371. _this.position.addToRef(_this._add, _this._target);
  83372. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  83373. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  83374. scene._forcedViewPosition = _this.position;
  83375. });
  83376. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  83377. scene._forcedViewPosition = null;
  83378. scene.updateTransformMatrix(true);
  83379. });
  83380. if (scene.activeCamera) {
  83381. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  83382. }
  83383. }
  83384. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  83385. get: function () {
  83386. return this._renderTargetTexture.samples;
  83387. },
  83388. set: function (value) {
  83389. this._renderTargetTexture.samples = value;
  83390. },
  83391. enumerable: true,
  83392. configurable: true
  83393. });
  83394. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  83395. get: function () {
  83396. return this._renderTargetTexture.refreshRate;
  83397. },
  83398. set: function (value) {
  83399. this._renderTargetTexture.refreshRate = value;
  83400. },
  83401. enumerable: true,
  83402. configurable: true
  83403. });
  83404. ReflectionProbe.prototype.getScene = function () {
  83405. return this._scene;
  83406. };
  83407. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  83408. get: function () {
  83409. return this._renderTargetTexture;
  83410. },
  83411. enumerable: true,
  83412. configurable: true
  83413. });
  83414. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  83415. get: function () {
  83416. return this._renderTargetTexture.renderList;
  83417. },
  83418. enumerable: true,
  83419. configurable: true
  83420. });
  83421. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  83422. this._attachedMesh = mesh;
  83423. };
  83424. /**
  83425. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  83426. *
  83427. * @param renderingGroupId The rendering group id corresponding to its index
  83428. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  83429. */
  83430. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  83431. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  83432. };
  83433. ReflectionProbe.prototype.dispose = function () {
  83434. var index = this._scene.reflectionProbes.indexOf(this);
  83435. if (index !== -1) {
  83436. // Remove from the scene if found
  83437. this._scene.reflectionProbes.splice(index, 1);
  83438. }
  83439. if (this._renderTargetTexture) {
  83440. this._renderTargetTexture.dispose();
  83441. this._renderTargetTexture = null;
  83442. }
  83443. };
  83444. return ReflectionProbe;
  83445. }());
  83446. BABYLON.ReflectionProbe = ReflectionProbe;
  83447. })(BABYLON || (BABYLON = {}));
  83448. //# sourceMappingURL=babylon.reflectionProbe.js.map
  83449. var BABYLON;
  83450. (function (BABYLON) {
  83451. var Layer = /** @class */ (function () {
  83452. function Layer(name, imgUrl, scene, isBackground, color) {
  83453. this.name = name;
  83454. this.scale = new BABYLON.Vector2(1, 1);
  83455. this.offset = new BABYLON.Vector2(0, 0);
  83456. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  83457. this.layerMask = 0x0FFFFFFF;
  83458. this._vertexBuffers = {};
  83459. // Events
  83460. /**
  83461. * An event triggered when the layer is disposed.
  83462. * @type {BABYLON.Observable}
  83463. */
  83464. this.onDisposeObservable = new BABYLON.Observable();
  83465. /**
  83466. * An event triggered before rendering the scene
  83467. * @type {BABYLON.Observable}
  83468. */
  83469. this.onBeforeRenderObservable = new BABYLON.Observable();
  83470. /**
  83471. * An event triggered after rendering the scene
  83472. * @type {BABYLON.Observable}
  83473. */
  83474. this.onAfterRenderObservable = new BABYLON.Observable();
  83475. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  83476. this.isBackground = isBackground === undefined ? true : isBackground;
  83477. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  83478. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  83479. this._scene.layers.push(this);
  83480. var engine = this._scene.getEngine();
  83481. // VBO
  83482. var vertices = [];
  83483. vertices.push(1, 1);
  83484. vertices.push(-1, 1);
  83485. vertices.push(-1, -1);
  83486. vertices.push(1, -1);
  83487. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83488. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83489. this._createIndexBuffer();
  83490. // Effects
  83491. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  83492. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  83493. }
  83494. Object.defineProperty(Layer.prototype, "onDispose", {
  83495. set: function (callback) {
  83496. if (this._onDisposeObserver) {
  83497. this.onDisposeObservable.remove(this._onDisposeObserver);
  83498. }
  83499. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  83500. },
  83501. enumerable: true,
  83502. configurable: true
  83503. });
  83504. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  83505. set: function (callback) {
  83506. if (this._onBeforeRenderObserver) {
  83507. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  83508. }
  83509. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  83510. },
  83511. enumerable: true,
  83512. configurable: true
  83513. });
  83514. Object.defineProperty(Layer.prototype, "onAfterRender", {
  83515. set: function (callback) {
  83516. if (this._onAfterRenderObserver) {
  83517. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83518. }
  83519. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  83520. },
  83521. enumerable: true,
  83522. configurable: true
  83523. });
  83524. Layer.prototype._createIndexBuffer = function () {
  83525. var engine = this._scene.getEngine();
  83526. // Indices
  83527. var indices = [];
  83528. indices.push(0);
  83529. indices.push(1);
  83530. indices.push(2);
  83531. indices.push(0);
  83532. indices.push(2);
  83533. indices.push(3);
  83534. this._indexBuffer = engine.createIndexBuffer(indices);
  83535. };
  83536. Layer.prototype._rebuild = function () {
  83537. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83538. if (vb) {
  83539. vb._rebuild();
  83540. }
  83541. this._createIndexBuffer();
  83542. };
  83543. Layer.prototype.render = function () {
  83544. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  83545. // Check
  83546. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  83547. return;
  83548. var engine = this._scene.getEngine();
  83549. this.onBeforeRenderObservable.notifyObservers(this);
  83550. // Render
  83551. engine.enableEffect(currentEffect);
  83552. engine.setState(false);
  83553. // Texture
  83554. currentEffect.setTexture("textureSampler", this.texture);
  83555. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  83556. // Color
  83557. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  83558. // Scale / offset
  83559. currentEffect.setVector2("offset", this.offset);
  83560. currentEffect.setVector2("scale", this.scale);
  83561. // VBOs
  83562. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83563. // Draw order
  83564. if (!this.alphaTest) {
  83565. engine.setAlphaMode(this.alphaBlendingMode);
  83566. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83567. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83568. }
  83569. else {
  83570. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83571. }
  83572. this.onAfterRenderObservable.notifyObservers(this);
  83573. };
  83574. Layer.prototype.dispose = function () {
  83575. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83576. if (vertexBuffer) {
  83577. vertexBuffer.dispose();
  83578. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83579. }
  83580. if (this._indexBuffer) {
  83581. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83582. this._indexBuffer = null;
  83583. }
  83584. if (this.texture) {
  83585. this.texture.dispose();
  83586. this.texture = null;
  83587. }
  83588. // Remove from scene
  83589. var index = this._scene.layers.indexOf(this);
  83590. this._scene.layers.splice(index, 1);
  83591. // Callback
  83592. this.onDisposeObservable.notifyObservers(this);
  83593. this.onDisposeObservable.clear();
  83594. this.onAfterRenderObservable.clear();
  83595. this.onBeforeRenderObservable.clear();
  83596. };
  83597. return Layer;
  83598. }());
  83599. BABYLON.Layer = Layer;
  83600. })(BABYLON || (BABYLON = {}));
  83601. //# sourceMappingURL=babylon.layer.js.map
  83602. var BABYLON;
  83603. (function (BABYLON) {
  83604. var TextureTools = /** @class */ (function () {
  83605. function TextureTools() {
  83606. }
  83607. /**
  83608. * Uses the GPU to create a copy texture rescaled at a given size
  83609. * @param texture Texture to copy from
  83610. * @param width Desired width
  83611. * @param height Desired height
  83612. * @return Generated texture
  83613. */
  83614. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  83615. if (useBilinearMode === void 0) { useBilinearMode = true; }
  83616. var scene = texture.getScene();
  83617. var engine = scene.getEngine();
  83618. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  83619. rtt.wrapU = texture.wrapU;
  83620. rtt.wrapV = texture.wrapV;
  83621. rtt.uOffset = texture.uOffset;
  83622. rtt.vOffset = texture.vOffset;
  83623. rtt.uScale = texture.uScale;
  83624. rtt.vScale = texture.vScale;
  83625. rtt.uAng = texture.uAng;
  83626. rtt.vAng = texture.vAng;
  83627. rtt.wAng = texture.wAng;
  83628. rtt.coordinatesIndex = texture.coordinatesIndex;
  83629. rtt.level = texture.level;
  83630. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  83631. rtt._texture.isReady = false;
  83632. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83633. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83634. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83635. passPostProcess.getEffect().executeWhenCompiled(function () {
  83636. passPostProcess.onApply = function (effect) {
  83637. effect.setTexture("textureSampler", texture);
  83638. };
  83639. var internalTexture = rtt.getInternalTexture();
  83640. if (internalTexture) {
  83641. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  83642. engine.unBindFramebuffer(internalTexture);
  83643. rtt.disposeFramebufferObjects();
  83644. passPostProcess.dispose();
  83645. internalTexture.isReady = true;
  83646. }
  83647. });
  83648. return rtt;
  83649. };
  83650. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  83651. if (!scene._environmentBRDFTexture) {
  83652. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83653. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83654. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83655. scene._environmentBRDFTexture = texture;
  83656. }
  83657. return scene._environmentBRDFTexture;
  83658. };
  83659. 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=";
  83660. return TextureTools;
  83661. }());
  83662. BABYLON.TextureTools = TextureTools;
  83663. })(BABYLON || (BABYLON = {}));
  83664. //# sourceMappingURL=babylon.textureTools.js.map
  83665. var BABYLON;
  83666. (function (BABYLON) {
  83667. var FramingBehavior = /** @class */ (function () {
  83668. function FramingBehavior() {
  83669. this._mode = FramingBehavior.FitFrustumSidesMode;
  83670. this._radiusScale = 1.0;
  83671. this._positionScale = 0.5;
  83672. this._defaultElevation = 0.3;
  83673. this._elevationReturnTime = 1500;
  83674. this._elevationReturnWaitTime = 1000;
  83675. this._zoomStopsAnimation = false;
  83676. this._framingTime = 1500;
  83677. this._isPointerDown = false;
  83678. this._lastInteractionTime = -Infinity;
  83679. // Framing control
  83680. this._animatables = new Array();
  83681. this._betaIsAnimating = false;
  83682. }
  83683. Object.defineProperty(FramingBehavior.prototype, "name", {
  83684. get: function () {
  83685. return "Framing";
  83686. },
  83687. enumerable: true,
  83688. configurable: true
  83689. });
  83690. Object.defineProperty(FramingBehavior.prototype, "mode", {
  83691. /**
  83692. * Gets current mode used by the behavior.
  83693. */
  83694. get: function () {
  83695. return this._mode;
  83696. },
  83697. /**
  83698. * Sets the current mode used by the behavior
  83699. */
  83700. set: function (mode) {
  83701. this._mode = mode;
  83702. },
  83703. enumerable: true,
  83704. configurable: true
  83705. });
  83706. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  83707. /**
  83708. * Gets the scale applied to the radius
  83709. */
  83710. get: function () {
  83711. return this._radiusScale;
  83712. },
  83713. /**
  83714. * Sets the scale applied to the radius (1 by default)
  83715. */
  83716. set: function (radius) {
  83717. this._radiusScale = radius;
  83718. },
  83719. enumerable: true,
  83720. configurable: true
  83721. });
  83722. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  83723. /**
  83724. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  83725. */
  83726. get: function () {
  83727. return this._positionScale;
  83728. },
  83729. /**
  83730. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  83731. */
  83732. set: function (scale) {
  83733. this._positionScale = scale;
  83734. },
  83735. enumerable: true,
  83736. configurable: true
  83737. });
  83738. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  83739. /**
  83740. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  83741. * behaviour is triggered, in radians.
  83742. */
  83743. get: function () {
  83744. return this._defaultElevation;
  83745. },
  83746. /**
  83747. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  83748. * behaviour is triggered, in radians.
  83749. */
  83750. set: function (elevation) {
  83751. this._defaultElevation = elevation;
  83752. },
  83753. enumerable: true,
  83754. configurable: true
  83755. });
  83756. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  83757. /**
  83758. * Gets the time (in milliseconds) taken to return to the default beta position.
  83759. * Negative value indicates camera should not return to default.
  83760. */
  83761. get: function () {
  83762. return this._elevationReturnTime;
  83763. },
  83764. /**
  83765. * Sets the time (in milliseconds) taken to return to the default beta position.
  83766. * Negative value indicates camera should not return to default.
  83767. */
  83768. set: function (speed) {
  83769. this._elevationReturnTime = speed;
  83770. },
  83771. enumerable: true,
  83772. configurable: true
  83773. });
  83774. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  83775. /**
  83776. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  83777. */
  83778. get: function () {
  83779. return this._elevationReturnWaitTime;
  83780. },
  83781. /**
  83782. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  83783. */
  83784. set: function (time) {
  83785. this._elevationReturnWaitTime = time;
  83786. },
  83787. enumerable: true,
  83788. configurable: true
  83789. });
  83790. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  83791. /**
  83792. * Gets the flag that indicates if user zooming should stop animation.
  83793. */
  83794. get: function () {
  83795. return this._zoomStopsAnimation;
  83796. },
  83797. /**
  83798. * Sets the flag that indicates if user zooming should stop animation.
  83799. */
  83800. set: function (flag) {
  83801. this._zoomStopsAnimation = flag;
  83802. },
  83803. enumerable: true,
  83804. configurable: true
  83805. });
  83806. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  83807. /**
  83808. * Gets the transition time when framing the mesh, in milliseconds
  83809. */
  83810. get: function () {
  83811. return this._framingTime;
  83812. },
  83813. /**
  83814. * Sets the transition time when framing the mesh, in milliseconds
  83815. */
  83816. set: function (time) {
  83817. this._framingTime = time;
  83818. },
  83819. enumerable: true,
  83820. configurable: true
  83821. });
  83822. FramingBehavior.prototype.init = function () {
  83823. // Do notihng
  83824. };
  83825. FramingBehavior.prototype.attach = function (camera) {
  83826. var _this = this;
  83827. this._attachedCamera = camera;
  83828. var scene = this._attachedCamera.getScene();
  83829. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  83830. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  83831. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  83832. _this._isPointerDown = true;
  83833. return;
  83834. }
  83835. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  83836. _this._isPointerDown = false;
  83837. }
  83838. });
  83839. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  83840. if (mesh) {
  83841. _this.zoomOnMesh(mesh);
  83842. }
  83843. });
  83844. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83845. // Stop the animation if there is user interaction and the animation should stop for this interaction
  83846. _this._applyUserInteraction();
  83847. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  83848. // back to the default position after a given timeout
  83849. _this._maintainCameraAboveGround();
  83850. });
  83851. };
  83852. FramingBehavior.prototype.detach = function () {
  83853. if (!this._attachedCamera) {
  83854. return;
  83855. }
  83856. var scene = this._attachedCamera.getScene();
  83857. if (this._onPrePointerObservableObserver) {
  83858. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  83859. }
  83860. if (this._onAfterCheckInputsObserver) {
  83861. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83862. }
  83863. if (this._onMeshTargetChangedObserver) {
  83864. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  83865. }
  83866. this._attachedCamera = null;
  83867. };
  83868. /**
  83869. * Targets the given mesh and updates zoom level accordingly.
  83870. * @param mesh The mesh to target.
  83871. * @param radius Optional. If a cached radius position already exists, overrides default.
  83872. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  83873. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  83874. * @param onAnimationEnd Callback triggered at the end of the framing animation
  83875. */
  83876. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  83877. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  83878. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  83879. mesh.computeWorldMatrix(true);
  83880. var boundingBox = mesh.getBoundingInfo().boundingBox;
  83881. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  83882. };
  83883. /**
  83884. * Targets the given mesh with its children and updates zoom level accordingly.
  83885. * @param mesh The mesh to target.
  83886. * @param radius Optional. If a cached radius position already exists, overrides default.
  83887. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  83888. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  83889. * @param onAnimationEnd Callback triggered at the end of the framing animation
  83890. */
  83891. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  83892. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  83893. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  83894. mesh.computeWorldMatrix(true);
  83895. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  83896. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  83897. };
  83898. /**
  83899. * Targets the given meshes with their children and updates zoom level accordingly.
  83900. * @param meshes The mesh to target.
  83901. * @param radius Optional. If a cached radius position already exists, overrides default.
  83902. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  83903. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  83904. * @param onAnimationEnd Callback triggered at the end of the framing animation
  83905. */
  83906. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  83907. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  83908. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  83909. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  83910. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  83911. for (var i = 0; i < meshes.length; i++) {
  83912. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  83913. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  83914. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  83915. }
  83916. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  83917. };
  83918. /**
  83919. * Targets the given mesh and updates zoom level accordingly.
  83920. * @param mesh The mesh to target.
  83921. * @param radius Optional. If a cached radius position already exists, overrides default.
  83922. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  83923. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  83924. * @param onAnimationEnd Callback triggered at the end of the framing animation
  83925. */
  83926. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  83927. var _this = this;
  83928. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  83929. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  83930. var zoomTarget;
  83931. if (!this._attachedCamera) {
  83932. return;
  83933. }
  83934. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  83935. var bottom = minimumWorld.y;
  83936. var top = maximumWorld.y;
  83937. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  83938. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  83939. if (focusOnOriginXZ) {
  83940. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  83941. }
  83942. else {
  83943. var centerWorld = minimumWorld.add(radiusWorld);
  83944. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  83945. }
  83946. if (!this._vectorTransition) {
  83947. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  83948. }
  83949. this._betaIsAnimating = true;
  83950. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  83951. if (animatable) {
  83952. this._animatables.push(animatable);
  83953. }
  83954. // sets the radius and lower radius bounds
  83955. // Small delta ensures camera is not always at lower zoom limit.
  83956. var radius = 0;
  83957. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  83958. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  83959. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  83960. radius = position;
  83961. }
  83962. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  83963. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  83964. if (this._attachedCamera.lowerRadiusLimit === null) {
  83965. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  83966. }
  83967. }
  83968. // Set sensibilities
  83969. var extend = maximumWorld.subtract(minimumWorld).length();
  83970. this._attachedCamera.panningSensibility = 5000 / extend;
  83971. this._attachedCamera.wheelPrecision = 100 / radius;
  83972. // transition to new radius
  83973. if (!this._radiusTransition) {
  83974. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  83975. }
  83976. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  83977. if (onAnimationEnd) {
  83978. onAnimationEnd();
  83979. }
  83980. if (_this._attachedCamera) {
  83981. _this._attachedCamera.storeState();
  83982. }
  83983. });
  83984. if (animatable) {
  83985. this._animatables.push(animatable);
  83986. }
  83987. };
  83988. /**
  83989. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  83990. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  83991. * frustum width.
  83992. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  83993. * to fully enclose the mesh in the viewing frustum.
  83994. */
  83995. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  83996. var size = maximumWorld.subtract(minimumWorld);
  83997. var boxVectorGlobalDiagonal = size.length();
  83998. var frustumSlope = this._getFrustumSlope();
  83999. // Formula for setting distance
  84000. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  84001. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  84002. // Horizon distance
  84003. var radius = radiusWithoutFraming * this._radiusScale;
  84004. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  84005. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  84006. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  84007. var camera = this._attachedCamera;
  84008. if (!camera) {
  84009. return 0;
  84010. }
  84011. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  84012. // Don't exceed the requested limit
  84013. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  84014. }
  84015. // Don't exceed the upper radius limit
  84016. if (camera.upperRadiusLimit) {
  84017. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  84018. }
  84019. return distance;
  84020. };
  84021. /**
  84022. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  84023. * is automatically returned to its default position (expected to be above ground plane).
  84024. */
  84025. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  84026. var _this = this;
  84027. if (this._elevationReturnTime < 0) {
  84028. return;
  84029. }
  84030. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  84031. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  84032. var limitBeta = Math.PI * 0.5;
  84033. // Bring the camera back up if below the ground plane
  84034. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  84035. this._betaIsAnimating = true;
  84036. //Transition to new position
  84037. this.stopAllAnimations();
  84038. if (!this._betaTransition) {
  84039. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  84040. }
  84041. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  84042. _this._clearAnimationLocks();
  84043. _this.stopAllAnimations();
  84044. });
  84045. if (animatabe) {
  84046. this._animatables.push(animatabe);
  84047. }
  84048. }
  84049. };
  84050. /**
  84051. * Returns the frustum slope based on the canvas ratio and camera FOV
  84052. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  84053. */
  84054. FramingBehavior.prototype._getFrustumSlope = function () {
  84055. // Calculate the viewport ratio
  84056. // Aspect Ratio is Height/Width.
  84057. var camera = this._attachedCamera;
  84058. if (!camera) {
  84059. return BABYLON.Vector2.Zero();
  84060. }
  84061. var engine = camera.getScene().getEngine();
  84062. var aspectRatio = engine.getAspectRatio(camera);
  84063. // Camera FOV is the vertical field of view (top-bottom) in radians.
  84064. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  84065. var frustumSlopeY = Math.tan(camera.fov / 2);
  84066. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  84067. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  84068. // along the forward vector.
  84069. var frustumSlopeX = frustumSlopeY * aspectRatio;
  84070. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  84071. };
  84072. /**
  84073. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  84074. */
  84075. FramingBehavior.prototype._clearAnimationLocks = function () {
  84076. this._betaIsAnimating = false;
  84077. };
  84078. /**
  84079. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  84080. */
  84081. FramingBehavior.prototype._applyUserInteraction = function () {
  84082. if (this.isUserIsMoving) {
  84083. this._lastInteractionTime = BABYLON.Tools.Now;
  84084. this.stopAllAnimations();
  84085. this._clearAnimationLocks();
  84086. }
  84087. };
  84088. /**
  84089. * Stops and removes all animations that have been applied to the camera
  84090. */
  84091. FramingBehavior.prototype.stopAllAnimations = function () {
  84092. if (this._attachedCamera) {
  84093. this._attachedCamera.animations = [];
  84094. }
  84095. while (this._animatables.length) {
  84096. if (this._animatables[0]) {
  84097. this._animatables[0].onAnimationEnd = null;
  84098. this._animatables[0].stop();
  84099. }
  84100. this._animatables.shift();
  84101. }
  84102. };
  84103. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  84104. /**
  84105. * Gets a value indicating if the user is moving the camera
  84106. */
  84107. get: function () {
  84108. if (!this._attachedCamera) {
  84109. return false;
  84110. }
  84111. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  84112. this._attachedCamera.inertialBetaOffset !== 0 ||
  84113. this._attachedCamera.inertialRadiusOffset !== 0 ||
  84114. this._attachedCamera.inertialPanningX !== 0 ||
  84115. this._attachedCamera.inertialPanningY !== 0 ||
  84116. this._isPointerDown;
  84117. },
  84118. enumerable: true,
  84119. configurable: true
  84120. });
  84121. /**
  84122. * The easing function used by animations
  84123. */
  84124. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  84125. /**
  84126. * The easing mode used by animations
  84127. */
  84128. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  84129. // Statics
  84130. /**
  84131. * The camera can move all the way towards the mesh.
  84132. */
  84133. FramingBehavior.IgnoreBoundsSizeMode = 0;
  84134. /**
  84135. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  84136. */
  84137. FramingBehavior.FitFrustumSidesMode = 1;
  84138. return FramingBehavior;
  84139. }());
  84140. BABYLON.FramingBehavior = FramingBehavior;
  84141. })(BABYLON || (BABYLON = {}));
  84142. //# sourceMappingURL=babylon.framingBehavior.js.map
  84143. var BABYLON;
  84144. (function (BABYLON) {
  84145. /**
  84146. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  84147. */
  84148. var BouncingBehavior = /** @class */ (function () {
  84149. function BouncingBehavior() {
  84150. /**
  84151. * The duration of the animation, in milliseconds
  84152. */
  84153. this.transitionDuration = 450;
  84154. /**
  84155. * Length of the distance animated by the transition when lower radius is reached
  84156. */
  84157. this.lowerRadiusTransitionRange = 2;
  84158. /**
  84159. * Length of the distance animated by the transition when upper radius is reached
  84160. */
  84161. this.upperRadiusTransitionRange = -2;
  84162. this._autoTransitionRange = false;
  84163. // Animations
  84164. this._radiusIsAnimating = false;
  84165. this._radiusBounceTransition = null;
  84166. this._animatables = new Array();
  84167. }
  84168. Object.defineProperty(BouncingBehavior.prototype, "name", {
  84169. get: function () {
  84170. return "Bouncing";
  84171. },
  84172. enumerable: true,
  84173. configurable: true
  84174. });
  84175. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  84176. /**
  84177. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  84178. */
  84179. get: function () {
  84180. return this._autoTransitionRange;
  84181. },
  84182. /**
  84183. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  84184. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  84185. */
  84186. set: function (value) {
  84187. var _this = this;
  84188. if (this._autoTransitionRange === value) {
  84189. return;
  84190. }
  84191. this._autoTransitionRange = value;
  84192. var camera = this._attachedCamera;
  84193. if (!camera) {
  84194. return;
  84195. }
  84196. if (value) {
  84197. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  84198. if (!mesh) {
  84199. return;
  84200. }
  84201. mesh.computeWorldMatrix(true);
  84202. var diagonal = mesh.getBoundingInfo().diagonalLength;
  84203. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  84204. _this.upperRadiusTransitionRange = diagonal * 0.05;
  84205. });
  84206. }
  84207. else if (this._onMeshTargetChangedObserver) {
  84208. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  84209. }
  84210. },
  84211. enumerable: true,
  84212. configurable: true
  84213. });
  84214. BouncingBehavior.prototype.init = function () {
  84215. // Do notihng
  84216. };
  84217. BouncingBehavior.prototype.attach = function (camera) {
  84218. var _this = this;
  84219. this._attachedCamera = camera;
  84220. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  84221. if (!_this._attachedCamera) {
  84222. return;
  84223. }
  84224. // Add the bounce animation to the lower radius limit
  84225. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  84226. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  84227. }
  84228. // Add the bounce animation to the upper radius limit
  84229. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  84230. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  84231. }
  84232. });
  84233. };
  84234. BouncingBehavior.prototype.detach = function () {
  84235. if (!this._attachedCamera) {
  84236. return;
  84237. }
  84238. if (this._onAfterCheckInputsObserver) {
  84239. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  84240. }
  84241. if (this._onMeshTargetChangedObserver) {
  84242. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  84243. }
  84244. this._attachedCamera = null;
  84245. };
  84246. /**
  84247. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  84248. * @param radiusLimit The limit to check against.
  84249. * @return Bool to indicate if at limit.
  84250. */
  84251. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  84252. if (!this._attachedCamera) {
  84253. return false;
  84254. }
  84255. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  84256. return true;
  84257. }
  84258. return false;
  84259. };
  84260. /**
  84261. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  84262. * @param radiusDelta The delta by which to animate to. Can be negative.
  84263. */
  84264. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  84265. var _this = this;
  84266. if (!this._attachedCamera) {
  84267. return;
  84268. }
  84269. if (!this._radiusBounceTransition) {
  84270. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  84271. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  84272. }
  84273. // Prevent zoom until bounce has completed
  84274. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  84275. this._attachedCamera.wheelPrecision = Infinity;
  84276. this._attachedCamera.inertialRadiusOffset = 0;
  84277. // Animate to the radius limit
  84278. this.stopAllAnimations();
  84279. this._radiusIsAnimating = true;
  84280. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  84281. if (animatable) {
  84282. this._animatables.push(animatable);
  84283. }
  84284. };
  84285. /**
  84286. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  84287. */
  84288. BouncingBehavior.prototype._clearAnimationLocks = function () {
  84289. this._radiusIsAnimating = false;
  84290. if (this._attachedCamera) {
  84291. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  84292. }
  84293. };
  84294. /**
  84295. * Stops and removes all animations that have been applied to the camera
  84296. */
  84297. BouncingBehavior.prototype.stopAllAnimations = function () {
  84298. if (this._attachedCamera) {
  84299. this._attachedCamera.animations = [];
  84300. }
  84301. while (this._animatables.length) {
  84302. this._animatables[0].onAnimationEnd = null;
  84303. this._animatables[0].stop();
  84304. this._animatables.shift();
  84305. }
  84306. };
  84307. /**
  84308. * The easing function used by animations
  84309. */
  84310. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  84311. /**
  84312. * The easing mode used by animations
  84313. */
  84314. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  84315. return BouncingBehavior;
  84316. }());
  84317. BABYLON.BouncingBehavior = BouncingBehavior;
  84318. })(BABYLON || (BABYLON = {}));
  84319. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  84320. var BABYLON;
  84321. (function (BABYLON) {
  84322. var AutoRotationBehavior = /** @class */ (function () {
  84323. function AutoRotationBehavior() {
  84324. this._zoomStopsAnimation = false;
  84325. this._idleRotationSpeed = 0.05;
  84326. this._idleRotationWaitTime = 2000;
  84327. this._idleRotationSpinupTime = 2000;
  84328. this._isPointerDown = false;
  84329. this._lastFrameTime = null;
  84330. this._lastInteractionTime = -Infinity;
  84331. this._cameraRotationSpeed = 0;
  84332. this._lastFrameRadius = 0;
  84333. }
  84334. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  84335. get: function () {
  84336. return "AutoRotation";
  84337. },
  84338. enumerable: true,
  84339. configurable: true
  84340. });
  84341. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  84342. /**
  84343. * Gets the flag that indicates if user zooming should stop animation.
  84344. */
  84345. get: function () {
  84346. return this._zoomStopsAnimation;
  84347. },
  84348. /**
  84349. * Sets the flag that indicates if user zooming should stop animation.
  84350. */
  84351. set: function (flag) {
  84352. this._zoomStopsAnimation = flag;
  84353. },
  84354. enumerable: true,
  84355. configurable: true
  84356. });
  84357. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  84358. /**
  84359. * Gets the default speed at which the camera rotates around the model.
  84360. */
  84361. get: function () {
  84362. return this._idleRotationSpeed;
  84363. },
  84364. /**
  84365. * Sets the default speed at which the camera rotates around the model.
  84366. */
  84367. set: function (speed) {
  84368. this._idleRotationSpeed = speed;
  84369. },
  84370. enumerable: true,
  84371. configurable: true
  84372. });
  84373. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  84374. /**
  84375. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  84376. */
  84377. get: function () {
  84378. return this._idleRotationWaitTime;
  84379. },
  84380. /**
  84381. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  84382. */
  84383. set: function (time) {
  84384. this._idleRotationWaitTime = time;
  84385. },
  84386. enumerable: true,
  84387. configurable: true
  84388. });
  84389. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  84390. /**
  84391. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  84392. */
  84393. get: function () {
  84394. return this._idleRotationSpinupTime;
  84395. },
  84396. /**
  84397. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  84398. */
  84399. set: function (time) {
  84400. this._idleRotationSpinupTime = time;
  84401. },
  84402. enumerable: true,
  84403. configurable: true
  84404. });
  84405. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  84406. /**
  84407. * Gets a value indicating if the camera is currently rotating because of this behavior
  84408. */
  84409. get: function () {
  84410. return Math.abs(this._cameraRotationSpeed) > 0;
  84411. },
  84412. enumerable: true,
  84413. configurable: true
  84414. });
  84415. AutoRotationBehavior.prototype.init = function () {
  84416. // Do notihng
  84417. };
  84418. AutoRotationBehavior.prototype.attach = function (camera) {
  84419. var _this = this;
  84420. this._attachedCamera = camera;
  84421. var scene = this._attachedCamera.getScene();
  84422. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  84423. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  84424. _this._isPointerDown = true;
  84425. return;
  84426. }
  84427. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  84428. _this._isPointerDown = false;
  84429. }
  84430. });
  84431. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  84432. var now = BABYLON.Tools.Now;
  84433. var dt = 0;
  84434. if (_this._lastFrameTime != null) {
  84435. dt = now - _this._lastFrameTime;
  84436. }
  84437. _this._lastFrameTime = now;
  84438. // Stop the animation if there is user interaction and the animation should stop for this interaction
  84439. _this._applyUserInteraction();
  84440. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  84441. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  84442. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  84443. // Step camera rotation by rotation speed
  84444. if (_this._attachedCamera) {
  84445. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  84446. }
  84447. });
  84448. };
  84449. AutoRotationBehavior.prototype.detach = function () {
  84450. if (!this._attachedCamera) {
  84451. return;
  84452. }
  84453. var scene = this._attachedCamera.getScene();
  84454. if (this._onPrePointerObservableObserver) {
  84455. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  84456. }
  84457. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  84458. this._attachedCamera = null;
  84459. };
  84460. /**
  84461. * Returns true if user is scrolling.
  84462. * @return true if user is scrolling.
  84463. */
  84464. AutoRotationBehavior.prototype._userIsZooming = function () {
  84465. if (!this._attachedCamera) {
  84466. return false;
  84467. }
  84468. return this._attachedCamera.inertialRadiusOffset !== 0;
  84469. };
  84470. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  84471. if (!this._attachedCamera) {
  84472. return false;
  84473. }
  84474. var zoomHasHitLimit = false;
  84475. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  84476. zoomHasHitLimit = true;
  84477. }
  84478. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  84479. this._lastFrameRadius = this._attachedCamera.radius;
  84480. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  84481. };
  84482. /**
  84483. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  84484. */
  84485. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  84486. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  84487. this._lastInteractionTime = BABYLON.Tools.Now;
  84488. }
  84489. };
  84490. // Tools
  84491. AutoRotationBehavior.prototype._userIsMoving = function () {
  84492. if (!this._attachedCamera) {
  84493. return false;
  84494. }
  84495. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  84496. this._attachedCamera.inertialBetaOffset !== 0 ||
  84497. this._attachedCamera.inertialRadiusOffset !== 0 ||
  84498. this._attachedCamera.inertialPanningX !== 0 ||
  84499. this._attachedCamera.inertialPanningY !== 0 ||
  84500. this._isPointerDown;
  84501. };
  84502. return AutoRotationBehavior;
  84503. }());
  84504. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  84505. })(BABYLON || (BABYLON = {}));
  84506. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  84507. var BABYLON;
  84508. (function (BABYLON) {
  84509. /**
  84510. * This class can be used to get instrumentation data from a Babylon engine
  84511. */
  84512. var EngineInstrumentation = /** @class */ (function () {
  84513. function EngineInstrumentation(engine) {
  84514. this.engine = engine;
  84515. this._captureGPUFrameTime = false;
  84516. this._gpuFrameTime = new BABYLON.PerfCounter();
  84517. this._captureShaderCompilationTime = false;
  84518. this._shaderCompilationTime = new BABYLON.PerfCounter();
  84519. // Observers
  84520. this._onBeginFrameObserver = null;
  84521. this._onEndFrameObserver = null;
  84522. this._onBeforeShaderCompilationObserver = null;
  84523. this._onAfterShaderCompilationObserver = null;
  84524. }
  84525. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  84526. // Properties
  84527. /**
  84528. * Gets the perf counter used for GPU frame time
  84529. */
  84530. get: function () {
  84531. return this._gpuFrameTime;
  84532. },
  84533. enumerable: true,
  84534. configurable: true
  84535. });
  84536. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  84537. /**
  84538. * Gets the GPU frame time capture status
  84539. */
  84540. get: function () {
  84541. return this._captureGPUFrameTime;
  84542. },
  84543. /**
  84544. * Enable or disable the GPU frame time capture
  84545. */
  84546. set: function (value) {
  84547. var _this = this;
  84548. if (value === this._captureGPUFrameTime) {
  84549. return;
  84550. }
  84551. this._captureGPUFrameTime = value;
  84552. if (value) {
  84553. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  84554. if (!_this._gpuFrameTimeToken) {
  84555. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  84556. }
  84557. });
  84558. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  84559. if (!_this._gpuFrameTimeToken) {
  84560. return;
  84561. }
  84562. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  84563. if (time > -1) {
  84564. _this._gpuFrameTimeToken = null;
  84565. _this._gpuFrameTime.fetchNewFrame();
  84566. _this._gpuFrameTime.addCount(time, true);
  84567. }
  84568. });
  84569. }
  84570. else {
  84571. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  84572. this._onBeginFrameObserver = null;
  84573. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  84574. this._onEndFrameObserver = null;
  84575. }
  84576. },
  84577. enumerable: true,
  84578. configurable: true
  84579. });
  84580. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  84581. /**
  84582. * Gets the perf counter used for shader compilation time
  84583. */
  84584. get: function () {
  84585. return this._shaderCompilationTime;
  84586. },
  84587. enumerable: true,
  84588. configurable: true
  84589. });
  84590. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  84591. /**
  84592. * Gets the shader compilation time capture status
  84593. */
  84594. get: function () {
  84595. return this._captureShaderCompilationTime;
  84596. },
  84597. /**
  84598. * Enable or disable the shader compilation time capture
  84599. */
  84600. set: function (value) {
  84601. var _this = this;
  84602. if (value === this._captureShaderCompilationTime) {
  84603. return;
  84604. }
  84605. this._captureShaderCompilationTime = value;
  84606. if (value) {
  84607. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  84608. _this._shaderCompilationTime.fetchNewFrame();
  84609. _this._shaderCompilationTime.beginMonitoring();
  84610. });
  84611. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  84612. _this._shaderCompilationTime.endMonitoring();
  84613. });
  84614. }
  84615. else {
  84616. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  84617. this._onBeforeShaderCompilationObserver = null;
  84618. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  84619. this._onAfterShaderCompilationObserver = null;
  84620. }
  84621. },
  84622. enumerable: true,
  84623. configurable: true
  84624. });
  84625. EngineInstrumentation.prototype.dispose = function () {
  84626. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  84627. this._onBeginFrameObserver = null;
  84628. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  84629. this._onEndFrameObserver = null;
  84630. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  84631. this._onBeforeShaderCompilationObserver = null;
  84632. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  84633. this._onAfterShaderCompilationObserver = null;
  84634. this.engine = null;
  84635. };
  84636. return EngineInstrumentation;
  84637. }());
  84638. BABYLON.EngineInstrumentation = EngineInstrumentation;
  84639. })(BABYLON || (BABYLON = {}));
  84640. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  84641. var BABYLON;
  84642. (function (BABYLON) {
  84643. /**
  84644. * This class can be used to get instrumentation data from a Babylon engine
  84645. */
  84646. var SceneInstrumentation = /** @class */ (function () {
  84647. function SceneInstrumentation(scene) {
  84648. var _this = this;
  84649. this.scene = scene;
  84650. this._captureActiveMeshesEvaluationTime = false;
  84651. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  84652. this._captureRenderTargetsRenderTime = false;
  84653. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  84654. this._captureFrameTime = false;
  84655. this._frameTime = new BABYLON.PerfCounter();
  84656. this._captureRenderTime = false;
  84657. this._renderTime = new BABYLON.PerfCounter();
  84658. this._captureInterFrameTime = false;
  84659. this._interFrameTime = new BABYLON.PerfCounter();
  84660. this._captureParticlesRenderTime = false;
  84661. this._particlesRenderTime = new BABYLON.PerfCounter();
  84662. this._captureSpritesRenderTime = false;
  84663. this._spritesRenderTime = new BABYLON.PerfCounter();
  84664. this._capturePhysicsTime = false;
  84665. this._physicsTime = new BABYLON.PerfCounter();
  84666. this._captureAnimationsTime = false;
  84667. this._animationsTime = new BABYLON.PerfCounter();
  84668. // Observers
  84669. this._onBeforeActiveMeshesEvaluationObserver = null;
  84670. this._onAfterActiveMeshesEvaluationObserver = null;
  84671. this._onBeforeRenderTargetsRenderObserver = null;
  84672. this._onAfterRenderTargetsRenderObserver = null;
  84673. this._onAfterRenderObserver = null;
  84674. this._onBeforeDrawPhaseObserver = null;
  84675. this._onAfterDrawPhaseObserver = null;
  84676. this._onBeforeAnimationsObserver = null;
  84677. this._onBeforeParticlesRenderingObserver = null;
  84678. this._onAfterParticlesRenderingObserver = null;
  84679. this._onBeforeSpritesRenderingObserver = null;
  84680. this._onAfterSpritesRenderingObserver = null;
  84681. this._onBeforePhysicsObserver = null;
  84682. this._onAfterPhysicsObserver = null;
  84683. this._onAfterAnimationsObserver = null;
  84684. // Before render
  84685. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  84686. if (_this._captureActiveMeshesEvaluationTime) {
  84687. _this._activeMeshesEvaluationTime.fetchNewFrame();
  84688. }
  84689. if (_this._captureRenderTargetsRenderTime) {
  84690. _this._renderTargetsRenderTime.fetchNewFrame();
  84691. }
  84692. if (_this._captureFrameTime) {
  84693. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  84694. _this._frameTime.beginMonitoring();
  84695. }
  84696. if (_this._captureInterFrameTime) {
  84697. _this._interFrameTime.endMonitoring();
  84698. }
  84699. if (_this._captureParticlesRenderTime) {
  84700. _this._particlesRenderTime.fetchNewFrame();
  84701. }
  84702. if (_this._captureSpritesRenderTime) {
  84703. _this._spritesRenderTime.fetchNewFrame();
  84704. }
  84705. if (_this._captureAnimationsTime) {
  84706. _this._animationsTime.beginMonitoring();
  84707. }
  84708. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  84709. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  84710. });
  84711. // After render
  84712. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  84713. if (_this._captureFrameTime) {
  84714. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  84715. _this._frameTime.endMonitoring();
  84716. }
  84717. if (_this._captureRenderTime) {
  84718. _this._renderTime.endMonitoring(false);
  84719. }
  84720. if (_this._captureInterFrameTime) {
  84721. _this._interFrameTime.beginMonitoring();
  84722. }
  84723. });
  84724. }
  84725. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  84726. // Properties
  84727. /**
  84728. * Gets the perf counter used for active meshes evaluation time
  84729. */
  84730. get: function () {
  84731. return this._activeMeshesEvaluationTime;
  84732. },
  84733. enumerable: true,
  84734. configurable: true
  84735. });
  84736. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  84737. /**
  84738. * Gets the active meshes evaluation time capture status
  84739. */
  84740. get: function () {
  84741. return this._captureActiveMeshesEvaluationTime;
  84742. },
  84743. /**
  84744. * Enable or disable the active meshes evaluation time capture
  84745. */
  84746. set: function (value) {
  84747. var _this = this;
  84748. if (value === this._captureActiveMeshesEvaluationTime) {
  84749. return;
  84750. }
  84751. this._captureActiveMeshesEvaluationTime = value;
  84752. if (value) {
  84753. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  84754. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  84755. _this._activeMeshesEvaluationTime.beginMonitoring();
  84756. });
  84757. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  84758. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  84759. _this._activeMeshesEvaluationTime.endMonitoring();
  84760. });
  84761. }
  84762. else {
  84763. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  84764. this._onBeforeActiveMeshesEvaluationObserver = null;
  84765. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  84766. this._onAfterActiveMeshesEvaluationObserver = null;
  84767. }
  84768. },
  84769. enumerable: true,
  84770. configurable: true
  84771. });
  84772. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  84773. /**
  84774. * Gets the perf counter used for render targets render time
  84775. */
  84776. get: function () {
  84777. return this._renderTargetsRenderTime;
  84778. },
  84779. enumerable: true,
  84780. configurable: true
  84781. });
  84782. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  84783. /**
  84784. * Gets the render targets render time capture status
  84785. */
  84786. get: function () {
  84787. return this._captureRenderTargetsRenderTime;
  84788. },
  84789. /**
  84790. * Enable or disable the render targets render time capture
  84791. */
  84792. set: function (value) {
  84793. var _this = this;
  84794. if (value === this._captureRenderTargetsRenderTime) {
  84795. return;
  84796. }
  84797. this._captureRenderTargetsRenderTime = value;
  84798. if (value) {
  84799. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  84800. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  84801. _this._renderTargetsRenderTime.beginMonitoring();
  84802. });
  84803. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  84804. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  84805. _this._renderTargetsRenderTime.endMonitoring(false);
  84806. });
  84807. }
  84808. else {
  84809. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  84810. this._onBeforeRenderTargetsRenderObserver = null;
  84811. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  84812. this._onAfterRenderTargetsRenderObserver = null;
  84813. }
  84814. },
  84815. enumerable: true,
  84816. configurable: true
  84817. });
  84818. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  84819. /**
  84820. * Gets the perf counter used for particles render time
  84821. */
  84822. get: function () {
  84823. return this._particlesRenderTime;
  84824. },
  84825. enumerable: true,
  84826. configurable: true
  84827. });
  84828. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  84829. /**
  84830. * Gets the particles render time capture status
  84831. */
  84832. get: function () {
  84833. return this._captureParticlesRenderTime;
  84834. },
  84835. /**
  84836. * Enable or disable the particles render time capture
  84837. */
  84838. set: function (value) {
  84839. var _this = this;
  84840. if (value === this._captureParticlesRenderTime) {
  84841. return;
  84842. }
  84843. this._captureParticlesRenderTime = value;
  84844. if (value) {
  84845. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  84846. BABYLON.Tools.StartPerformanceCounter("Particles");
  84847. _this._particlesRenderTime.beginMonitoring();
  84848. });
  84849. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  84850. BABYLON.Tools.EndPerformanceCounter("Particles");
  84851. _this._particlesRenderTime.endMonitoring(false);
  84852. });
  84853. }
  84854. else {
  84855. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  84856. this._onBeforeParticlesRenderingObserver = null;
  84857. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  84858. this._onAfterParticlesRenderingObserver = null;
  84859. }
  84860. },
  84861. enumerable: true,
  84862. configurable: true
  84863. });
  84864. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  84865. /**
  84866. * Gets the perf counter used for sprites render time
  84867. */
  84868. get: function () {
  84869. return this._spritesRenderTime;
  84870. },
  84871. enumerable: true,
  84872. configurable: true
  84873. });
  84874. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  84875. /**
  84876. * Gets the sprites render time capture status
  84877. */
  84878. get: function () {
  84879. return this._captureSpritesRenderTime;
  84880. },
  84881. /**
  84882. * Enable or disable the sprites render time capture
  84883. */
  84884. set: function (value) {
  84885. var _this = this;
  84886. if (value === this._captureSpritesRenderTime) {
  84887. return;
  84888. }
  84889. this._captureSpritesRenderTime = value;
  84890. if (value) {
  84891. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  84892. BABYLON.Tools.StartPerformanceCounter("Sprites");
  84893. _this._spritesRenderTime.beginMonitoring();
  84894. });
  84895. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  84896. BABYLON.Tools.EndPerformanceCounter("Sprites");
  84897. _this._spritesRenderTime.endMonitoring(false);
  84898. });
  84899. }
  84900. else {
  84901. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  84902. this._onBeforeSpritesRenderingObserver = null;
  84903. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  84904. this._onAfterSpritesRenderingObserver = null;
  84905. }
  84906. },
  84907. enumerable: true,
  84908. configurable: true
  84909. });
  84910. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  84911. /**
  84912. * Gets the perf counter used for physics time
  84913. */
  84914. get: function () {
  84915. return this._physicsTime;
  84916. },
  84917. enumerable: true,
  84918. configurable: true
  84919. });
  84920. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  84921. /**
  84922. * Gets the physics time capture status
  84923. */
  84924. get: function () {
  84925. return this._capturePhysicsTime;
  84926. },
  84927. /**
  84928. * Enable or disable the physics time capture
  84929. */
  84930. set: function (value) {
  84931. var _this = this;
  84932. if (value === this._capturePhysicsTime) {
  84933. return;
  84934. }
  84935. this._capturePhysicsTime = value;
  84936. if (value) {
  84937. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  84938. BABYLON.Tools.StartPerformanceCounter("Physics");
  84939. _this._physicsTime.beginMonitoring();
  84940. });
  84941. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  84942. BABYLON.Tools.EndPerformanceCounter("Physics");
  84943. _this._physicsTime.endMonitoring();
  84944. });
  84945. }
  84946. else {
  84947. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  84948. this._onBeforePhysicsObserver = null;
  84949. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  84950. this._onAfterPhysicsObserver = null;
  84951. }
  84952. },
  84953. enumerable: true,
  84954. configurable: true
  84955. });
  84956. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  84957. /**
  84958. * Gets the perf counter used for animations time
  84959. */
  84960. get: function () {
  84961. return this._animationsTime;
  84962. },
  84963. enumerable: true,
  84964. configurable: true
  84965. });
  84966. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  84967. /**
  84968. * Gets the animations time capture status
  84969. */
  84970. get: function () {
  84971. return this._captureAnimationsTime;
  84972. },
  84973. /**
  84974. * Enable or disable the animations time capture
  84975. */
  84976. set: function (value) {
  84977. var _this = this;
  84978. if (value === this._captureAnimationsTime) {
  84979. return;
  84980. }
  84981. this._captureAnimationsTime = value;
  84982. if (value) {
  84983. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  84984. _this._animationsTime.endMonitoring();
  84985. });
  84986. }
  84987. else {
  84988. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  84989. this._onAfterAnimationsObserver = null;
  84990. }
  84991. },
  84992. enumerable: true,
  84993. configurable: true
  84994. });
  84995. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  84996. /**
  84997. * Gets the perf counter used for frame time capture
  84998. */
  84999. get: function () {
  85000. return this._frameTime;
  85001. },
  85002. enumerable: true,
  85003. configurable: true
  85004. });
  85005. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  85006. /**
  85007. * Gets the frame time capture status
  85008. */
  85009. get: function () {
  85010. return this._captureFrameTime;
  85011. },
  85012. /**
  85013. * Enable or disable the frame time capture
  85014. */
  85015. set: function (value) {
  85016. this._captureFrameTime = value;
  85017. },
  85018. enumerable: true,
  85019. configurable: true
  85020. });
  85021. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  85022. /**
  85023. * Gets the perf counter used for inter-frames time capture
  85024. */
  85025. get: function () {
  85026. return this._interFrameTime;
  85027. },
  85028. enumerable: true,
  85029. configurable: true
  85030. });
  85031. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  85032. /**
  85033. * Gets the inter-frames time capture status
  85034. */
  85035. get: function () {
  85036. return this._captureInterFrameTime;
  85037. },
  85038. /**
  85039. * Enable or disable the inter-frames time capture
  85040. */
  85041. set: function (value) {
  85042. this._captureInterFrameTime = value;
  85043. },
  85044. enumerable: true,
  85045. configurable: true
  85046. });
  85047. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  85048. /**
  85049. * Gets the perf counter used for render time capture
  85050. */
  85051. get: function () {
  85052. return this._renderTime;
  85053. },
  85054. enumerable: true,
  85055. configurable: true
  85056. });
  85057. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  85058. /**
  85059. * Gets the render time capture status
  85060. */
  85061. get: function () {
  85062. return this._captureRenderTime;
  85063. },
  85064. /**
  85065. * Enable or disable the render time capture
  85066. */
  85067. set: function (value) {
  85068. var _this = this;
  85069. if (value === this._captureRenderTime) {
  85070. return;
  85071. }
  85072. this._captureRenderTime = value;
  85073. if (value) {
  85074. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  85075. _this._renderTime.beginMonitoring();
  85076. BABYLON.Tools.StartPerformanceCounter("Main render");
  85077. });
  85078. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  85079. _this._renderTime.endMonitoring(false);
  85080. BABYLON.Tools.EndPerformanceCounter("Main render");
  85081. });
  85082. }
  85083. else {
  85084. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  85085. this._onBeforeDrawPhaseObserver = null;
  85086. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  85087. this._onAfterDrawPhaseObserver = null;
  85088. }
  85089. },
  85090. enumerable: true,
  85091. configurable: true
  85092. });
  85093. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  85094. /**
  85095. * Gets the perf counter used for draw calls
  85096. */
  85097. get: function () {
  85098. return this.scene.getEngine()._drawCalls;
  85099. },
  85100. enumerable: true,
  85101. configurable: true
  85102. });
  85103. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  85104. /**
  85105. * Gets the perf counter used for texture collisions
  85106. */
  85107. get: function () {
  85108. return this.scene.getEngine()._textureCollisions;
  85109. },
  85110. enumerable: true,
  85111. configurable: true
  85112. });
  85113. SceneInstrumentation.prototype.dispose = function () {
  85114. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  85115. this._onAfterRenderObserver = null;
  85116. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  85117. this._onBeforeActiveMeshesEvaluationObserver = null;
  85118. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  85119. this._onAfterActiveMeshesEvaluationObserver = null;
  85120. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  85121. this._onBeforeRenderTargetsRenderObserver = null;
  85122. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  85123. this._onAfterRenderTargetsRenderObserver = null;
  85124. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  85125. this._onBeforeAnimationsObserver = null;
  85126. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  85127. this._onBeforeParticlesRenderingObserver = null;
  85128. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  85129. this._onAfterParticlesRenderingObserver = null;
  85130. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  85131. this._onBeforeSpritesRenderingObserver = null;
  85132. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  85133. this._onAfterSpritesRenderingObserver = null;
  85134. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  85135. this._onBeforeDrawPhaseObserver = null;
  85136. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  85137. this._onAfterDrawPhaseObserver = null;
  85138. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  85139. this._onBeforePhysicsObserver = null;
  85140. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  85141. this._onAfterPhysicsObserver = null;
  85142. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  85143. this._onAfterAnimationsObserver = null;
  85144. this.scene = null;
  85145. };
  85146. return SceneInstrumentation;
  85147. }());
  85148. BABYLON.SceneInstrumentation = SceneInstrumentation;
  85149. })(BABYLON || (BABYLON = {}));
  85150. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  85151. var BABYLON;
  85152. (function (BABYLON) {
  85153. var _TimeToken = /** @class */ (function () {
  85154. function _TimeToken() {
  85155. this._timeElapsedQueryEnded = false;
  85156. }
  85157. return _TimeToken;
  85158. }());
  85159. BABYLON._TimeToken = _TimeToken;
  85160. })(BABYLON || (BABYLON = {}));
  85161. //# sourceMappingURL=babylon.timeToken.js.map
  85162. var BABYLON;
  85163. (function (BABYLON) {
  85164. /**
  85165. * Background material defines definition.
  85166. * @ignore Mainly internal Use
  85167. */
  85168. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  85169. __extends(BackgroundMaterialDefines, _super);
  85170. /**
  85171. * Constructor of the defines.
  85172. */
  85173. function BackgroundMaterialDefines() {
  85174. var _this = _super.call(this) || this;
  85175. /**
  85176. * True if the diffuse texture is in use.
  85177. */
  85178. _this.DIFFUSE = false;
  85179. /**
  85180. * The direct UV channel to use.
  85181. */
  85182. _this.DIFFUSEDIRECTUV = 0;
  85183. /**
  85184. * True if the diffuse texture is in gamma space.
  85185. */
  85186. _this.GAMMADIFFUSE = false;
  85187. /**
  85188. * True if the diffuse texture has opacity in the alpha channel.
  85189. */
  85190. _this.DIFFUSEHASALPHA = false;
  85191. /**
  85192. * True if you want the material to fade to transparent at grazing angle.
  85193. */
  85194. _this.OPACITYFRESNEL = false;
  85195. /**
  85196. * True if an extra blur needs to be added in the reflection.
  85197. */
  85198. _this.REFLECTIONBLUR = false;
  85199. /**
  85200. * True if you want the material to fade to reflection at grazing angle.
  85201. */
  85202. _this.REFLECTIONFRESNEL = false;
  85203. /**
  85204. * True if you want the material to falloff as far as you move away from the scene center.
  85205. */
  85206. _this.REFLECTIONFALLOFF = false;
  85207. /**
  85208. * False if the current Webgl implementation does not support the texture lod extension.
  85209. */
  85210. _this.TEXTURELODSUPPORT = false;
  85211. /**
  85212. * True to ensure the data are premultiplied.
  85213. */
  85214. _this.PREMULTIPLYALPHA = false;
  85215. /**
  85216. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  85217. */
  85218. _this.USERGBCOLOR = false;
  85219. /**
  85220. * True to add noise in order to reduce the banding effect.
  85221. */
  85222. _this.NOISE = false;
  85223. // Image Processing Configuration.
  85224. _this.IMAGEPROCESSING = false;
  85225. _this.VIGNETTE = false;
  85226. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  85227. _this.VIGNETTEBLENDMODEOPAQUE = false;
  85228. _this.TONEMAPPING = false;
  85229. _this.CONTRAST = false;
  85230. _this.COLORCURVES = false;
  85231. _this.COLORGRADING = false;
  85232. _this.COLORGRADING3D = false;
  85233. _this.SAMPLER3DGREENDEPTH = false;
  85234. _this.SAMPLER3DBGRMAP = false;
  85235. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  85236. _this.EXPOSURE = false;
  85237. // Reflection.
  85238. _this.REFLECTION = false;
  85239. _this.REFLECTIONMAP_3D = false;
  85240. _this.REFLECTIONMAP_SPHERICAL = false;
  85241. _this.REFLECTIONMAP_PLANAR = false;
  85242. _this.REFLECTIONMAP_CUBIC = false;
  85243. _this.REFLECTIONMAP_PROJECTION = false;
  85244. _this.REFLECTIONMAP_SKYBOX = false;
  85245. _this.REFLECTIONMAP_EXPLICIT = false;
  85246. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  85247. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  85248. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  85249. _this.INVERTCUBICMAP = false;
  85250. _this.REFLECTIONMAP_OPPOSITEZ = false;
  85251. _this.LODINREFLECTIONALPHA = false;
  85252. _this.GAMMAREFLECTION = false;
  85253. // Default BJS.
  85254. _this.MAINUV1 = false;
  85255. _this.MAINUV2 = false;
  85256. _this.UV1 = false;
  85257. _this.UV2 = false;
  85258. _this.CLIPPLANE = false;
  85259. _this.POINTSIZE = false;
  85260. _this.FOG = false;
  85261. _this.NORMAL = false;
  85262. _this.NUM_BONE_INFLUENCERS = 0;
  85263. _this.BonesPerMesh = 0;
  85264. _this.INSTANCES = false;
  85265. _this.SHADOWFLOAT = false;
  85266. _this.rebuild();
  85267. return _this;
  85268. }
  85269. return BackgroundMaterialDefines;
  85270. }(BABYLON.MaterialDefines));
  85271. /**
  85272. * Background material used to create an efficient environement around your scene.
  85273. */
  85274. var BackgroundMaterial = /** @class */ (function (_super) {
  85275. __extends(BackgroundMaterial, _super);
  85276. /**
  85277. * Instantiates a Background Material in the given scene
  85278. * @param name The friendly name of the material
  85279. * @param scene The scene to add the material to
  85280. */
  85281. function BackgroundMaterial(name, scene) {
  85282. var _this = _super.call(this, name, scene) || this;
  85283. /**
  85284. * Key light Color (multiply against the R channel of the environement texture)
  85285. */
  85286. _this.primaryColor = BABYLON.Color3.White();
  85287. /**
  85288. * Key light Level (allowing HDR output of the background)
  85289. */
  85290. _this.primaryLevel = 1;
  85291. /**
  85292. * Secondary light Color (multiply against the G channel of the environement texture)
  85293. */
  85294. _this.secondaryColor = BABYLON.Color3.Gray();
  85295. /**
  85296. * Secondary light Level (allowing HDR output of the background)
  85297. */
  85298. _this.secondaryLevel = 1;
  85299. /**
  85300. * Tertiary light Color (multiply against the B channel of the environement texture)
  85301. */
  85302. _this.tertiaryColor = BABYLON.Color3.Black();
  85303. /**
  85304. * Tertiary light Level (allowing HDR output of the background)
  85305. */
  85306. _this.tertiaryLevel = 1;
  85307. /**
  85308. * Reflection Texture used in the material.
  85309. * Should be author in a specific way for the best result (refer to the documentation).
  85310. */
  85311. _this.reflectionTexture = null;
  85312. /**
  85313. * Reflection Texture level of blur.
  85314. *
  85315. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  85316. * texture twice.
  85317. */
  85318. _this.reflectionBlur = 0;
  85319. /**
  85320. * Diffuse Texture used in the material.
  85321. * Should be author in a specific way for the best result (refer to the documentation).
  85322. */
  85323. _this.diffuseTexture = null;
  85324. _this._shadowLights = null;
  85325. /**
  85326. * Specify the list of lights casting shadow on the material.
  85327. * All scene shadow lights will be included if null.
  85328. */
  85329. _this.shadowLights = null;
  85330. /**
  85331. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  85332. * soft lighting on the background.
  85333. */
  85334. _this.shadowBlurScale = 1;
  85335. /**
  85336. * Helps adjusting the shadow to a softer level if required.
  85337. * 0 means black shadows and 1 means no shadows.
  85338. */
  85339. _this.shadowLevel = 0;
  85340. /**
  85341. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  85342. * It is usually zero but might be interesting to modify according to your setup.
  85343. */
  85344. _this.sceneCenter = BABYLON.Vector3.Zero();
  85345. /**
  85346. * This helps specifying that the material is falling off to the sky box at grazing angle.
  85347. * This helps ensuring a nice transition when the camera goes under the ground.
  85348. */
  85349. _this.opacityFresnel = true;
  85350. /**
  85351. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  85352. * This helps adding a mirror texture on the ground.
  85353. */
  85354. _this.reflectionFresnel = false;
  85355. /**
  85356. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  85357. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  85358. */
  85359. _this.reflectionFalloffDistance = 0.0;
  85360. /**
  85361. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  85362. */
  85363. _this.reflectionAmount = 1.0;
  85364. /**
  85365. * This specifies the weight of the reflection at grazing angle.
  85366. */
  85367. _this.reflectionReflectance0 = 0.05;
  85368. /**
  85369. * This specifies the weight of the reflection at a perpendicular point of view.
  85370. */
  85371. _this.reflectionReflectance90 = 0.5;
  85372. /**
  85373. * Helps to directly use the maps channels instead of their level.
  85374. */
  85375. _this.useRGBColor = true;
  85376. /**
  85377. * This helps reducing the banding effect that could occur on the background.
  85378. */
  85379. _this.enableNoise = false;
  85380. _this._maxSimultaneousLights = 4;
  85381. /**
  85382. * Number of Simultaneous lights allowed on the material.
  85383. */
  85384. _this.maxSimultaneousLights = 4;
  85385. /**
  85386. * Keep track of the image processing observer to allow dispose and replace.
  85387. */
  85388. _this._imageProcessingObserver = null;
  85389. // Temp values kept as cache in the material.
  85390. _this._renderTargets = new BABYLON.SmartArray(16);
  85391. _this._reflectionControls = BABYLON.Vector4.Zero();
  85392. // Setup the default processing configuration to the scene.
  85393. _this._attachImageProcessingConfiguration(null);
  85394. _this.getRenderTargetTextures = function () {
  85395. _this._renderTargets.reset();
  85396. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  85397. _this._renderTargets.push(_this._diffuseTexture);
  85398. }
  85399. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  85400. _this._renderTargets.push(_this._reflectionTexture);
  85401. }
  85402. return _this._renderTargets;
  85403. };
  85404. return _this;
  85405. }
  85406. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  85407. /**
  85408. * Sets the reflection reflectance fresnel values according to the default standard
  85409. * empirically know to work well :-)
  85410. */
  85411. set: function (value) {
  85412. var reflectionWeight = value;
  85413. if (reflectionWeight < 0.5) {
  85414. reflectionWeight = reflectionWeight * 2.0;
  85415. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  85416. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  85417. }
  85418. else {
  85419. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  85420. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  85421. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  85422. }
  85423. },
  85424. enumerable: true,
  85425. configurable: true
  85426. });
  85427. /**
  85428. * Attaches a new image processing configuration to the PBR Material.
  85429. * @param configuration (if null the scene configuration will be use)
  85430. */
  85431. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  85432. var _this = this;
  85433. if (configuration === this._imageProcessingConfiguration) {
  85434. return;
  85435. }
  85436. // Detaches observer.
  85437. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85438. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85439. }
  85440. // Pick the scene configuration if needed.
  85441. if (!configuration) {
  85442. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  85443. }
  85444. else {
  85445. this._imageProcessingConfiguration = configuration;
  85446. }
  85447. // Attaches observer.
  85448. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  85449. _this._markAllSubMeshesAsImageProcessingDirty();
  85450. });
  85451. };
  85452. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  85453. /**
  85454. * Gets the image processing configuration used either in this material.
  85455. */
  85456. get: function () {
  85457. return this._imageProcessingConfiguration;
  85458. },
  85459. /**
  85460. * Sets the Default image processing configuration used either in the this material.
  85461. *
  85462. * If sets to null, the scene one is in use.
  85463. */
  85464. set: function (value) {
  85465. this._attachImageProcessingConfiguration(value);
  85466. // Ensure the effect will be rebuilt.
  85467. this._markAllSubMeshesAsTexturesDirty();
  85468. },
  85469. enumerable: true,
  85470. configurable: true
  85471. });
  85472. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  85473. /**
  85474. * Gets wether the color curves effect is enabled.
  85475. */
  85476. get: function () {
  85477. return this.imageProcessingConfiguration.colorCurvesEnabled;
  85478. },
  85479. /**
  85480. * Sets wether the color curves effect is enabled.
  85481. */
  85482. set: function (value) {
  85483. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  85484. },
  85485. enumerable: true,
  85486. configurable: true
  85487. });
  85488. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  85489. /**
  85490. * Gets wether the color grading effect is enabled.
  85491. */
  85492. get: function () {
  85493. return this.imageProcessingConfiguration.colorGradingEnabled;
  85494. },
  85495. /**
  85496. * Gets wether the color grading effect is enabled.
  85497. */
  85498. set: function (value) {
  85499. this.imageProcessingConfiguration.colorGradingEnabled = value;
  85500. },
  85501. enumerable: true,
  85502. configurable: true
  85503. });
  85504. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  85505. /**
  85506. * Gets wether tonemapping is enabled or not.
  85507. */
  85508. get: function () {
  85509. return this._imageProcessingConfiguration.toneMappingEnabled;
  85510. },
  85511. /**
  85512. * Sets wether tonemapping is enabled or not
  85513. */
  85514. set: function (value) {
  85515. this._imageProcessingConfiguration.toneMappingEnabled = value;
  85516. },
  85517. enumerable: true,
  85518. configurable: true
  85519. });
  85520. ;
  85521. ;
  85522. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  85523. /**
  85524. * The camera exposure used on this material.
  85525. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  85526. * This corresponds to a photographic exposure.
  85527. */
  85528. get: function () {
  85529. return this._imageProcessingConfiguration.exposure;
  85530. },
  85531. /**
  85532. * The camera exposure used on this material.
  85533. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  85534. * This corresponds to a photographic exposure.
  85535. */
  85536. set: function (value) {
  85537. this._imageProcessingConfiguration.exposure = value;
  85538. },
  85539. enumerable: true,
  85540. configurable: true
  85541. });
  85542. ;
  85543. ;
  85544. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  85545. /**
  85546. * Gets The camera contrast used on this material.
  85547. */
  85548. get: function () {
  85549. return this._imageProcessingConfiguration.contrast;
  85550. },
  85551. /**
  85552. * Sets The camera contrast used on this material.
  85553. */
  85554. set: function (value) {
  85555. this._imageProcessingConfiguration.contrast = value;
  85556. },
  85557. enumerable: true,
  85558. configurable: true
  85559. });
  85560. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  85561. /**
  85562. * Gets the Color Grading 2D Lookup Texture.
  85563. */
  85564. get: function () {
  85565. return this._imageProcessingConfiguration.colorGradingTexture;
  85566. },
  85567. /**
  85568. * Sets the Color Grading 2D Lookup Texture.
  85569. */
  85570. set: function (value) {
  85571. this.imageProcessingConfiguration.colorGradingTexture = value;
  85572. },
  85573. enumerable: true,
  85574. configurable: true
  85575. });
  85576. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  85577. /**
  85578. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85579. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85580. * 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;
  85581. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85582. */
  85583. get: function () {
  85584. return this.imageProcessingConfiguration.colorCurves;
  85585. },
  85586. /**
  85587. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85588. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85589. * 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;
  85590. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85591. */
  85592. set: function (value) {
  85593. this.imageProcessingConfiguration.colorCurves = value;
  85594. },
  85595. enumerable: true,
  85596. configurable: true
  85597. });
  85598. /**
  85599. * The entire material has been created in order to prevent overdraw.
  85600. * @returns false
  85601. */
  85602. BackgroundMaterial.prototype.needAlphaTesting = function () {
  85603. return true;
  85604. };
  85605. /**
  85606. * The entire material has been created in order to prevent overdraw.
  85607. * @returns true if blending is enable
  85608. */
  85609. BackgroundMaterial.prototype.needAlphaBlending = function () {
  85610. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  85611. };
  85612. /**
  85613. * Checks wether the material is ready to be rendered for a given mesh.
  85614. * @param mesh The mesh to render
  85615. * @param subMesh The submesh to check against
  85616. * @param useInstances Specify wether or not the material is used with instances
  85617. * @returns true if all the dependencies are ready (Textures, Effects...)
  85618. */
  85619. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  85620. var _this = this;
  85621. if (useInstances === void 0) { useInstances = false; }
  85622. if (subMesh.effect && this.isFrozen) {
  85623. if (this._wasPreviouslyReady) {
  85624. return true;
  85625. }
  85626. }
  85627. if (!subMesh._materialDefines) {
  85628. subMesh._materialDefines = new BackgroundMaterialDefines();
  85629. }
  85630. var scene = this.getScene();
  85631. var defines = subMesh._materialDefines;
  85632. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  85633. if (defines._renderId === scene.getRenderId()) {
  85634. return true;
  85635. }
  85636. }
  85637. var engine = scene.getEngine();
  85638. // Lights
  85639. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  85640. defines._needNormals = true;
  85641. // Textures
  85642. if (defines._areTexturesDirty) {
  85643. defines._needUVs = false;
  85644. if (scene.texturesEnabled) {
  85645. if (scene.getEngine().getCaps().textureLOD) {
  85646. defines.TEXTURELODSUPPORT = true;
  85647. }
  85648. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85649. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  85650. return false;
  85651. }
  85652. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  85653. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  85654. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  85655. defines.OPACITYFRESNEL = this._opacityFresnel;
  85656. }
  85657. else {
  85658. defines.DIFFUSE = false;
  85659. defines.DIFFUSEHASALPHA = false;
  85660. defines.GAMMADIFFUSE = false;
  85661. defines.OPACITYFRESNEL = false;
  85662. }
  85663. var reflectionTexture = this._reflectionTexture;
  85664. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85665. if (!reflectionTexture.isReadyOrNotBlocking()) {
  85666. return false;
  85667. }
  85668. defines.REFLECTION = true;
  85669. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  85670. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  85671. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  85672. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  85673. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  85674. defines.INVERTCUBICMAP = true;
  85675. }
  85676. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  85677. switch (reflectionTexture.coordinatesMode) {
  85678. case BABYLON.Texture.CUBIC_MODE:
  85679. case BABYLON.Texture.INVCUBIC_MODE:
  85680. defines.REFLECTIONMAP_CUBIC = true;
  85681. break;
  85682. case BABYLON.Texture.EXPLICIT_MODE:
  85683. defines.REFLECTIONMAP_EXPLICIT = true;
  85684. break;
  85685. case BABYLON.Texture.PLANAR_MODE:
  85686. defines.REFLECTIONMAP_PLANAR = true;
  85687. break;
  85688. case BABYLON.Texture.PROJECTION_MODE:
  85689. defines.REFLECTIONMAP_PROJECTION = true;
  85690. break;
  85691. case BABYLON.Texture.SKYBOX_MODE:
  85692. defines.REFLECTIONMAP_SKYBOX = true;
  85693. break;
  85694. case BABYLON.Texture.SPHERICAL_MODE:
  85695. defines.REFLECTIONMAP_SPHERICAL = true;
  85696. break;
  85697. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  85698. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  85699. break;
  85700. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  85701. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  85702. break;
  85703. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  85704. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  85705. break;
  85706. }
  85707. if (this.reflectionFresnel) {
  85708. defines.REFLECTIONFRESNEL = true;
  85709. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  85710. this._reflectionControls.x = this.reflectionAmount;
  85711. this._reflectionControls.y = this.reflectionReflectance0;
  85712. this._reflectionControls.z = this.reflectionReflectance90;
  85713. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  85714. }
  85715. else {
  85716. defines.REFLECTIONFRESNEL = false;
  85717. defines.REFLECTIONFALLOFF = false;
  85718. }
  85719. }
  85720. else {
  85721. defines.REFLECTION = false;
  85722. defines.REFLECTIONFALLOFF = false;
  85723. defines.REFLECTIONBLUR = false;
  85724. defines.REFLECTIONMAP_3D = false;
  85725. defines.REFLECTIONMAP_SPHERICAL = false;
  85726. defines.REFLECTIONMAP_PLANAR = false;
  85727. defines.REFLECTIONMAP_CUBIC = false;
  85728. defines.REFLECTIONMAP_PROJECTION = false;
  85729. defines.REFLECTIONMAP_SKYBOX = false;
  85730. defines.REFLECTIONMAP_EXPLICIT = false;
  85731. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  85732. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  85733. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  85734. defines.INVERTCUBICMAP = false;
  85735. defines.REFLECTIONMAP_OPPOSITEZ = false;
  85736. defines.LODINREFLECTIONALPHA = false;
  85737. defines.GAMMAREFLECTION = false;
  85738. }
  85739. }
  85740. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  85741. defines.USERGBCOLOR = this._useRGBColor;
  85742. defines.NOISE = this._enableNoise;
  85743. }
  85744. if (defines._areImageProcessingDirty) {
  85745. if (!this._imageProcessingConfiguration.isReady()) {
  85746. return false;
  85747. }
  85748. this._imageProcessingConfiguration.prepareDefines(defines);
  85749. }
  85750. // Misc.
  85751. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  85752. // Values that need to be evaluated on every frame
  85753. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  85754. // Attribs
  85755. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  85756. if (mesh) {
  85757. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85758. mesh.createNormals(true);
  85759. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  85760. }
  85761. }
  85762. }
  85763. // Get correct effect
  85764. if (defines.isDirty) {
  85765. defines.markAsProcessed();
  85766. scene.resetCachedMaterial();
  85767. // Fallbacks
  85768. var fallbacks = new BABYLON.EffectFallbacks();
  85769. if (defines.FOG) {
  85770. fallbacks.addFallback(0, "FOG");
  85771. }
  85772. if (defines.POINTSIZE) {
  85773. fallbacks.addFallback(1, "POINTSIZE");
  85774. }
  85775. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  85776. if (defines.NUM_BONE_INFLUENCERS > 0) {
  85777. fallbacks.addCPUSkinningFallback(0, mesh);
  85778. }
  85779. //Attributes
  85780. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85781. if (defines.NORMAL) {
  85782. attribs.push(BABYLON.VertexBuffer.NormalKind);
  85783. }
  85784. if (defines.UV1) {
  85785. attribs.push(BABYLON.VertexBuffer.UVKind);
  85786. }
  85787. if (defines.UV2) {
  85788. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85789. }
  85790. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  85791. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  85792. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  85793. "vFogInfos", "vFogColor", "pointSize",
  85794. "vClipPlane", "mBones",
  85795. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  85796. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  85797. "shadowLevel", "alpha",
  85798. "vBackgroundCenter", "vReflectionControl",
  85799. "vDiffuseInfos", "diffuseMatrix",
  85800. ];
  85801. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  85802. var uniformBuffers = ["Material", "Scene"];
  85803. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  85804. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  85805. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  85806. uniformsNames: uniforms,
  85807. uniformBuffersNames: uniformBuffers,
  85808. samplers: samplers,
  85809. defines: defines,
  85810. maxSimultaneousLights: this._maxSimultaneousLights
  85811. });
  85812. var onCompiled = function (effect) {
  85813. if (_this.onCompiled) {
  85814. _this.onCompiled(effect);
  85815. }
  85816. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  85817. };
  85818. var join = defines.toString();
  85819. subMesh.setEffect(scene.getEngine().createEffect("background", {
  85820. attributes: attribs,
  85821. uniformsNames: uniforms,
  85822. uniformBuffersNames: uniformBuffers,
  85823. samplers: samplers,
  85824. defines: join,
  85825. fallbacks: fallbacks,
  85826. onCompiled: onCompiled,
  85827. onError: this.onError,
  85828. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  85829. }, engine), defines);
  85830. this.buildUniformLayout();
  85831. }
  85832. if (!subMesh.effect || !subMesh.effect.isReady()) {
  85833. return false;
  85834. }
  85835. defines._renderId = scene.getRenderId();
  85836. this._wasPreviouslyReady = true;
  85837. return true;
  85838. };
  85839. /**
  85840. * Build the uniform buffer used in the material.
  85841. */
  85842. BackgroundMaterial.prototype.buildUniformLayout = function () {
  85843. // Order is important !
  85844. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  85845. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  85846. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  85847. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  85848. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  85849. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  85850. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  85851. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  85852. this._uniformBuffer.addUniform("pointSize", 1);
  85853. this._uniformBuffer.addUniform("shadowLevel", 1);
  85854. this._uniformBuffer.addUniform("alpha", 1);
  85855. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  85856. this._uniformBuffer.addUniform("vReflectionControl", 4);
  85857. this._uniformBuffer.create();
  85858. };
  85859. /**
  85860. * Unbind the material.
  85861. */
  85862. BackgroundMaterial.prototype.unbind = function () {
  85863. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  85864. this._uniformBuffer.setTexture("diffuseSampler", null);
  85865. }
  85866. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  85867. this._uniformBuffer.setTexture("reflectionSampler", null);
  85868. }
  85869. _super.prototype.unbind.call(this);
  85870. };
  85871. /**
  85872. * Bind only the world matrix to the material.
  85873. * @param world The world matrix to bind.
  85874. */
  85875. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  85876. this._activeEffect.setMatrix("world", world);
  85877. };
  85878. /**
  85879. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  85880. * @param world The world matrix to bind.
  85881. * @param subMesh The submesh to bind for.
  85882. */
  85883. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  85884. var scene = this.getScene();
  85885. var defines = subMesh._materialDefines;
  85886. if (!defines) {
  85887. return;
  85888. }
  85889. var effect = subMesh.effect;
  85890. if (!effect) {
  85891. return;
  85892. }
  85893. this._activeEffect = effect;
  85894. // Matrices
  85895. this.bindOnlyWorldMatrix(world);
  85896. // Bones
  85897. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  85898. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  85899. if (mustRebind) {
  85900. this._uniformBuffer.bindToEffect(effect, "Material");
  85901. this.bindViewProjection(effect);
  85902. var reflectionTexture = this._reflectionTexture;
  85903. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  85904. // Texture uniforms
  85905. if (scene.texturesEnabled) {
  85906. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85907. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  85908. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  85909. }
  85910. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85911. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  85912. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  85913. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  85914. }
  85915. }
  85916. if (this.shadowLevel > 0) {
  85917. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  85918. }
  85919. this._uniformBuffer.updateFloat("alpha", this.alpha);
  85920. // Point size
  85921. if (this.pointsCloud) {
  85922. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  85923. }
  85924. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  85925. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  85926. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  85927. }
  85928. // Textures
  85929. if (scene.texturesEnabled) {
  85930. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85931. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  85932. }
  85933. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85934. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  85935. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  85936. }
  85937. else if (!defines.REFLECTIONBLUR) {
  85938. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  85939. }
  85940. else {
  85941. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  85942. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  85943. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  85944. }
  85945. if (defines.REFLECTIONFRESNEL) {
  85946. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  85947. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  85948. }
  85949. }
  85950. }
  85951. // Clip plane
  85952. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  85953. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  85954. }
  85955. if (mustRebind || !this.isFrozen) {
  85956. if (scene.lightsEnabled) {
  85957. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  85958. }
  85959. // View
  85960. this.bindView(effect);
  85961. // Fog
  85962. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  85963. // image processing
  85964. this._imageProcessingConfiguration.bind(this._activeEffect);
  85965. }
  85966. this._uniformBuffer.update();
  85967. this._afterBind(mesh);
  85968. };
  85969. /**
  85970. * Dispose the material.
  85971. * @param forceDisposeEffect Force disposal of the associated effect.
  85972. * @param forceDisposeTextures Force disposal of the associated textures.
  85973. */
  85974. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  85975. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  85976. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  85977. if (forceDisposeTextures) {
  85978. if (this.diffuseTexture) {
  85979. this.diffuseTexture.dispose();
  85980. }
  85981. if (this.reflectionTexture) {
  85982. this.reflectionTexture.dispose();
  85983. }
  85984. }
  85985. this._renderTargets.dispose();
  85986. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85987. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85988. }
  85989. _super.prototype.dispose.call(this, forceDisposeEffect);
  85990. };
  85991. /**
  85992. * Clones the material.
  85993. * @param name The cloned name.
  85994. * @returns The cloned material.
  85995. */
  85996. BackgroundMaterial.prototype.clone = function (name) {
  85997. var _this = this;
  85998. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  85999. };
  86000. /**
  86001. * Serializes the current material to its JSON representation.
  86002. * @returns The JSON representation.
  86003. */
  86004. BackgroundMaterial.prototype.serialize = function () {
  86005. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86006. serializationObject.customType = "BABYLON.BackgroundMaterial";
  86007. return serializationObject;
  86008. };
  86009. /**
  86010. * Gets the class name of the material
  86011. * @returns "BackgroundMaterial"
  86012. */
  86013. BackgroundMaterial.prototype.getClassName = function () {
  86014. return "BackgroundMaterial";
  86015. };
  86016. /**
  86017. * Parse a JSON input to create back a background material.
  86018. * @param source The JSON data to parse
  86019. * @param scene The scene to create the parsed material in
  86020. * @param rootUrl The root url of the assets the material depends upon
  86021. * @returns the instantiated BackgroundMaterial.
  86022. */
  86023. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  86024. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  86025. };
  86026. /**
  86027. * Standard reflectance value at parallel view angle.
  86028. */
  86029. BackgroundMaterial.StandardReflectance0 = 0.05;
  86030. /**
  86031. * Standard reflectance value at grazing angle.
  86032. */
  86033. BackgroundMaterial.StandardReflectance90 = 0.5;
  86034. __decorate([
  86035. BABYLON.serializeAsColor3()
  86036. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  86037. __decorate([
  86038. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86039. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  86040. __decorate([
  86041. BABYLON.serialize()
  86042. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  86043. __decorate([
  86044. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86045. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  86046. __decorate([
  86047. BABYLON.serializeAsColor3()
  86048. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  86049. __decorate([
  86050. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86051. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  86052. __decorate([
  86053. BABYLON.serialize()
  86054. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  86055. __decorate([
  86056. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86057. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  86058. __decorate([
  86059. BABYLON.serializeAsColor3()
  86060. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  86061. __decorate([
  86062. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86063. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  86064. __decorate([
  86065. BABYLON.serialize()
  86066. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  86067. __decorate([
  86068. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86069. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  86070. __decorate([
  86071. BABYLON.serializeAsTexture()
  86072. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  86073. __decorate([
  86074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86075. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  86076. __decorate([
  86077. BABYLON.serialize()
  86078. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  86079. __decorate([
  86080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86081. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  86082. __decorate([
  86083. BABYLON.serializeAsTexture()
  86084. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  86085. __decorate([
  86086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86087. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  86088. __decorate([
  86089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86090. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  86091. __decorate([
  86092. BABYLON.serialize()
  86093. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  86094. __decorate([
  86095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86096. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  86097. __decorate([
  86098. BABYLON.serialize()
  86099. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  86100. __decorate([
  86101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86102. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  86103. __decorate([
  86104. BABYLON.serializeAsVector3()
  86105. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  86106. __decorate([
  86107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86108. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  86109. __decorate([
  86110. BABYLON.serialize()
  86111. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  86112. __decorate([
  86113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86114. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  86115. __decorate([
  86116. BABYLON.serialize()
  86117. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  86118. __decorate([
  86119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86120. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  86121. __decorate([
  86122. BABYLON.serialize()
  86123. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  86124. __decorate([
  86125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86126. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  86127. __decorate([
  86128. BABYLON.serialize()
  86129. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  86130. __decorate([
  86131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86132. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  86133. __decorate([
  86134. BABYLON.serialize()
  86135. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  86136. __decorate([
  86137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86138. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  86139. __decorate([
  86140. BABYLON.serialize()
  86141. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  86142. __decorate([
  86143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86144. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  86145. __decorate([
  86146. BABYLON.serialize()
  86147. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  86148. __decorate([
  86149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86150. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  86151. __decorate([
  86152. BABYLON.serialize()
  86153. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  86154. __decorate([
  86155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86156. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  86157. __decorate([
  86158. BABYLON.serialize()
  86159. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  86160. __decorate([
  86161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86162. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  86163. __decorate([
  86164. BABYLON.serializeAsImageProcessingConfiguration()
  86165. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  86166. return BackgroundMaterial;
  86167. }(BABYLON.PushMaterial));
  86168. BABYLON.BackgroundMaterial = BackgroundMaterial;
  86169. })(BABYLON || (BABYLON = {}));
  86170. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  86171. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86172. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86173. s = arguments[i];
  86174. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86175. t[p] = s[p];
  86176. }
  86177. return t;
  86178. };
  86179. var BABYLON;
  86180. (function (BABYLON) {
  86181. /**
  86182. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  86183. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  86184. * It also helps with the default setup of your imageProcessing configuration.
  86185. */
  86186. var EnvironmentHelper = /** @class */ (function () {
  86187. /**
  86188. * constructor
  86189. * @param options
  86190. * @param scene The scene to add the material to
  86191. */
  86192. function EnvironmentHelper(options, scene) {
  86193. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  86194. this._scene = scene;
  86195. this._setupBackground();
  86196. this._setupImageProcessing();
  86197. }
  86198. /**
  86199. * Creates the default options for the helper.
  86200. */
  86201. EnvironmentHelper._getDefaultOptions = function () {
  86202. return {
  86203. createGround: true,
  86204. groundSize: 15,
  86205. groundTexture: this._groundTextureCDNUrl,
  86206. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  86207. groundOpacity: 0.9,
  86208. enableGroundShadow: true,
  86209. groundShadowLevel: 0.5,
  86210. enableGroundMirror: false,
  86211. groundMirrorSizeRatio: 0.3,
  86212. groundMirrorBlurKernel: 64,
  86213. groundMirrorAmount: 1,
  86214. groundMirrorFresnelWeight: 1,
  86215. groundMirrorFallOffDistance: 0,
  86216. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  86217. groundYBias: 0.00001,
  86218. createSkybox: true,
  86219. skyboxSize: 20,
  86220. skyboxTexture: this._skyboxTextureCDNUrl,
  86221. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  86222. backgroundYRotation: 0,
  86223. sizeAuto: true,
  86224. rootPosition: BABYLON.Vector3.Zero(),
  86225. setupImageProcessing: true,
  86226. environmentTexture: this._environmentTextureCDNUrl,
  86227. cameraExposure: 0.8,
  86228. cameraContrast: 1.2,
  86229. toneMappingEnabled: true,
  86230. };
  86231. };
  86232. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  86233. /**
  86234. * Gets the root mesh created by the helper.
  86235. */
  86236. get: function () {
  86237. return this._rootMesh;
  86238. },
  86239. enumerable: true,
  86240. configurable: true
  86241. });
  86242. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  86243. /**
  86244. * Gets the skybox created by the helper.
  86245. */
  86246. get: function () {
  86247. return this._skybox;
  86248. },
  86249. enumerable: true,
  86250. configurable: true
  86251. });
  86252. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  86253. /**
  86254. * Gets the skybox texture created by the helper.
  86255. */
  86256. get: function () {
  86257. return this._skyboxTexture;
  86258. },
  86259. enumerable: true,
  86260. configurable: true
  86261. });
  86262. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  86263. /**
  86264. * Gets the skybox material created by the helper.
  86265. */
  86266. get: function () {
  86267. return this._skyboxMaterial;
  86268. },
  86269. enumerable: true,
  86270. configurable: true
  86271. });
  86272. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  86273. /**
  86274. * Gets the ground mesh created by the helper.
  86275. */
  86276. get: function () {
  86277. return this._ground;
  86278. },
  86279. enumerable: true,
  86280. configurable: true
  86281. });
  86282. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  86283. /**
  86284. * Gets the ground texture created by the helper.
  86285. */
  86286. get: function () {
  86287. return this._groundTexture;
  86288. },
  86289. enumerable: true,
  86290. configurable: true
  86291. });
  86292. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  86293. /**
  86294. * Gets the ground mirror created by the helper.
  86295. */
  86296. get: function () {
  86297. return this._groundMirror;
  86298. },
  86299. enumerable: true,
  86300. configurable: true
  86301. });
  86302. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  86303. /**
  86304. * Gets the ground mirror render list to helps pushing the meshes
  86305. * you wish in the ground reflection.
  86306. */
  86307. get: function () {
  86308. if (this._groundMirror) {
  86309. return this._groundMirror.renderList;
  86310. }
  86311. return null;
  86312. },
  86313. enumerable: true,
  86314. configurable: true
  86315. });
  86316. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  86317. /**
  86318. * Gets the ground material created by the helper.
  86319. */
  86320. get: function () {
  86321. return this._groundMaterial;
  86322. },
  86323. enumerable: true,
  86324. configurable: true
  86325. });
  86326. /**
  86327. * Updates the background according to the new options
  86328. * @param options
  86329. */
  86330. EnvironmentHelper.prototype.updateOptions = function (options) {
  86331. var newOptions = __assign({}, this._options, options);
  86332. if (this._ground && !newOptions.createGround) {
  86333. this._ground.dispose();
  86334. this._ground = null;
  86335. }
  86336. if (this._groundMaterial && !newOptions.createGround) {
  86337. this._groundMaterial.dispose();
  86338. this._groundMaterial = null;
  86339. }
  86340. if (this._groundTexture) {
  86341. if (this._options.groundTexture != newOptions.groundTexture) {
  86342. this._groundTexture.dispose();
  86343. this._groundTexture = null;
  86344. }
  86345. }
  86346. if (this._skybox && !newOptions.createSkybox) {
  86347. this._skybox.dispose();
  86348. this._skybox = null;
  86349. }
  86350. if (this._skyboxMaterial && !newOptions.createSkybox) {
  86351. this._skyboxMaterial.dispose();
  86352. this._skyboxMaterial = null;
  86353. }
  86354. if (this._skyboxTexture) {
  86355. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  86356. this._skyboxTexture.dispose();
  86357. this._skyboxTexture = null;
  86358. }
  86359. }
  86360. if (this._groundMirror && !newOptions.enableGroundMirror) {
  86361. this._groundMirror.dispose();
  86362. this._groundMirror = null;
  86363. }
  86364. if (this._scene.environmentTexture) {
  86365. if (this._options.environmentTexture != newOptions.environmentTexture) {
  86366. this._scene.environmentTexture.dispose();
  86367. }
  86368. }
  86369. this._options = newOptions;
  86370. this._setupBackground();
  86371. this._setupImageProcessing();
  86372. };
  86373. /**
  86374. * Sets the primary color of all the available elements.
  86375. * @param color
  86376. */
  86377. EnvironmentHelper.prototype.setMainColor = function (color) {
  86378. if (this.groundMaterial) {
  86379. this.groundMaterial.primaryColor = color;
  86380. }
  86381. if (this.skyboxMaterial) {
  86382. this.skyboxMaterial.primaryColor = color;
  86383. }
  86384. if (this.groundMirror) {
  86385. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  86386. }
  86387. };
  86388. /**
  86389. * Setup the image processing according to the specified options.
  86390. */
  86391. EnvironmentHelper.prototype._setupImageProcessing = function () {
  86392. if (this._options.setupImageProcessing) {
  86393. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  86394. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  86395. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  86396. this._setupEnvironmentTexture();
  86397. }
  86398. };
  86399. /**
  86400. * Setup the environment texture according to the specified options.
  86401. */
  86402. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  86403. if (this._scene.environmentTexture) {
  86404. return;
  86405. }
  86406. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  86407. this._scene.environmentTexture = this._options.environmentTexture;
  86408. return;
  86409. }
  86410. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  86411. this._scene.environmentTexture = environmentTexture;
  86412. };
  86413. /**
  86414. * Setup the background according to the specified options.
  86415. */
  86416. EnvironmentHelper.prototype._setupBackground = function () {
  86417. if (!this._rootMesh) {
  86418. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  86419. }
  86420. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  86421. var sceneSize = this._getSceneSize();
  86422. if (this._options.createGround) {
  86423. this._setupGround(sceneSize);
  86424. this._setupGroundMaterial();
  86425. this._setupGroundDiffuseTexture();
  86426. if (this._options.enableGroundMirror) {
  86427. this._setupGroundMirrorTexture(sceneSize);
  86428. }
  86429. this._setupMirrorInGroundMaterial();
  86430. }
  86431. if (this._options.createSkybox) {
  86432. this._setupSkybox(sceneSize);
  86433. this._setupSkyboxMaterial();
  86434. this._setupSkyboxReflectionTexture();
  86435. }
  86436. this._rootMesh.position.x = sceneSize.rootPosition.x;
  86437. this._rootMesh.position.z = sceneSize.rootPosition.z;
  86438. this._rootMesh.position.y = sceneSize.rootPosition.y;
  86439. };
  86440. /**
  86441. * Get the scene sizes according to the setup.
  86442. */
  86443. EnvironmentHelper.prototype._getSceneSize = function () {
  86444. var groundSize = this._options.groundSize;
  86445. var skyboxSize = this._options.skyboxSize;
  86446. var rootPosition = this._options.rootPosition;
  86447. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  86448. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  86449. }
  86450. var sceneExtends = this._scene.getWorldExtends();
  86451. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  86452. if (this._options.sizeAuto) {
  86453. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  86454. this._scene.activeCamera.upperRadiusLimit) {
  86455. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  86456. skyboxSize = groundSize;
  86457. }
  86458. var sceneDiagonalLenght = sceneDiagonal.length();
  86459. if (sceneDiagonalLenght > groundSize) {
  86460. groundSize = sceneDiagonalLenght * 2;
  86461. skyboxSize = groundSize;
  86462. }
  86463. // 10 % bigger.
  86464. groundSize *= 1.1;
  86465. skyboxSize *= 1.5;
  86466. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  86467. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  86468. }
  86469. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  86470. };
  86471. /**
  86472. * Setup the ground according to the specified options.
  86473. */
  86474. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  86475. var _this = this;
  86476. if (!this._ground) {
  86477. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  86478. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  86479. this._ground.parent = this._rootMesh;
  86480. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  86481. }
  86482. this._ground.receiveShadows = this._options.enableGroundShadow;
  86483. };
  86484. /**
  86485. * Setup the ground material according to the specified options.
  86486. */
  86487. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  86488. if (!this._groundMaterial) {
  86489. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  86490. }
  86491. this._groundMaterial.alpha = this._options.groundOpacity;
  86492. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  86493. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  86494. this._groundMaterial.primaryLevel = 1;
  86495. this._groundMaterial.primaryColor = this._options.groundColor;
  86496. this._groundMaterial.secondaryLevel = 0;
  86497. this._groundMaterial.tertiaryLevel = 0;
  86498. this._groundMaterial.useRGBColor = false;
  86499. this._groundMaterial.enableNoise = true;
  86500. if (this._ground) {
  86501. this._ground.material = this._groundMaterial;
  86502. }
  86503. };
  86504. /**
  86505. * Setup the ground diffuse texture according to the specified options.
  86506. */
  86507. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  86508. if (!this._groundMaterial) {
  86509. return;
  86510. }
  86511. if (this._groundTexture) {
  86512. return;
  86513. }
  86514. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  86515. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  86516. return;
  86517. }
  86518. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  86519. diffuseTexture.gammaSpace = false;
  86520. diffuseTexture.hasAlpha = true;
  86521. this._groundMaterial.diffuseTexture = diffuseTexture;
  86522. };
  86523. /**
  86524. * Setup the ground mirror texture according to the specified options.
  86525. */
  86526. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  86527. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86528. if (!this._groundMirror) {
  86529. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  86530. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  86531. this._groundMirror.anisotropicFilteringLevel = 1;
  86532. this._groundMirror.wrapU = wrapping;
  86533. this._groundMirror.wrapV = wrapping;
  86534. this._groundMirror.gammaSpace = false;
  86535. if (this._groundMirror.renderList) {
  86536. for (var i = 0; i < this._scene.meshes.length; i++) {
  86537. var mesh = this._scene.meshes[i];
  86538. if (mesh !== this._ground &&
  86539. mesh !== this._skybox &&
  86540. mesh !== this._rootMesh) {
  86541. this._groundMirror.renderList.push(mesh);
  86542. }
  86543. }
  86544. }
  86545. }
  86546. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  86547. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  86548. };
  86549. /**
  86550. * Setup the ground to receive the mirror texture.
  86551. */
  86552. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  86553. if (this._groundMaterial) {
  86554. this._groundMaterial.reflectionTexture = this._groundMirror;
  86555. this._groundMaterial.reflectionFresnel = true;
  86556. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  86557. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  86558. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  86559. }
  86560. };
  86561. /**
  86562. * Setup the skybox according to the specified options.
  86563. */
  86564. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  86565. var _this = this;
  86566. if (!this._skybox) {
  86567. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  86568. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  86569. }
  86570. this._skybox.parent = this._rootMesh;
  86571. };
  86572. /**
  86573. * Setup the skybox material according to the specified options.
  86574. */
  86575. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  86576. if (!this._skybox) {
  86577. return;
  86578. }
  86579. if (!this._skyboxMaterial) {
  86580. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  86581. }
  86582. this._skyboxMaterial.useRGBColor = false;
  86583. this._skyboxMaterial.primaryLevel = 1;
  86584. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  86585. this._skyboxMaterial.secondaryLevel = 0;
  86586. this._skyboxMaterial.tertiaryLevel = 0;
  86587. this._skyboxMaterial.enableNoise = true;
  86588. this._skybox.material = this._skyboxMaterial;
  86589. };
  86590. /**
  86591. * Setup the skybox reflection texture according to the specified options.
  86592. */
  86593. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  86594. if (!this._skyboxMaterial) {
  86595. return;
  86596. }
  86597. if (this._skyboxTexture) {
  86598. return;
  86599. }
  86600. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  86601. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  86602. return;
  86603. }
  86604. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  86605. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  86606. this._skyboxTexture.gammaSpace = false;
  86607. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  86608. };
  86609. /**
  86610. * Dispose all the elements created by the Helper.
  86611. */
  86612. EnvironmentHelper.prototype.dispose = function () {
  86613. if (this._groundMaterial) {
  86614. this._groundMaterial.dispose(true, true);
  86615. }
  86616. if (this._skyboxMaterial) {
  86617. this._skyboxMaterial.dispose(true, true);
  86618. }
  86619. this._rootMesh.dispose(false);
  86620. };
  86621. /**
  86622. * Default ground texture URL.
  86623. */
  86624. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  86625. /**
  86626. * Default skybox texture URL.
  86627. */
  86628. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  86629. /**
  86630. * Default environment texture URL.
  86631. */
  86632. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  86633. return EnvironmentHelper;
  86634. }());
  86635. BABYLON.EnvironmentHelper = EnvironmentHelper;
  86636. })(BABYLON || (BABYLON = {}));
  86637. //# sourceMappingURL=babylon.environmentHelper.js.map
  86638. 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,coc,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec4 blurred=texture2D(textureSampler,vUV);\nvec4 original=texture2D(originalSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\ngl_FragColor=mix(original,blurred,coc);\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 depthSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \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);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\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\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\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#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\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}"};
  86639. 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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(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\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#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 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;\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 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};"};
  86640. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  86641. var BABYLON;
  86642. (function (BABYLON) {
  86643. var GridMaterialDefines = /** @class */ (function (_super) {
  86644. __extends(GridMaterialDefines, _super);
  86645. function GridMaterialDefines() {
  86646. var _this = _super.call(this) || this;
  86647. _this.TRANSPARENT = false;
  86648. _this.FOG = false;
  86649. _this.PREMULTIPLYALPHA = false;
  86650. _this.rebuild();
  86651. return _this;
  86652. }
  86653. return GridMaterialDefines;
  86654. }(BABYLON.MaterialDefines));
  86655. /**
  86656. * The grid materials allows you to wrap any shape with a grid.
  86657. * Colors are customizable.
  86658. */
  86659. var GridMaterial = /** @class */ (function (_super) {
  86660. __extends(GridMaterial, _super);
  86661. /**
  86662. * constructor
  86663. * @param name The name given to the material in order to identify it afterwards.
  86664. * @param scene The scene the material is used in.
  86665. */
  86666. function GridMaterial(name, scene) {
  86667. var _this = _super.call(this, name, scene) || this;
  86668. /**
  86669. * Main color of the grid (e.g. between lines)
  86670. */
  86671. _this.mainColor = BABYLON.Color3.Black();
  86672. /**
  86673. * Color of the grid lines.
  86674. */
  86675. _this.lineColor = BABYLON.Color3.Teal();
  86676. /**
  86677. * The scale of the grid compared to unit.
  86678. */
  86679. _this.gridRatio = 1.0;
  86680. /**
  86681. * Allows setting an offset for the grid lines.
  86682. */
  86683. _this.gridOffset = BABYLON.Vector3.Zero();
  86684. /**
  86685. * The frequency of thicker lines.
  86686. */
  86687. _this.majorUnitFrequency = 10;
  86688. /**
  86689. * The visibility of minor units in the grid.
  86690. */
  86691. _this.minorUnitVisibility = 0.33;
  86692. /**
  86693. * The grid opacity outside of the lines.
  86694. */
  86695. _this.opacity = 1.0;
  86696. /**
  86697. * Determine RBG output is premultiplied by alpha value.
  86698. */
  86699. _this.preMultiplyAlpha = false;
  86700. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  86701. return _this;
  86702. }
  86703. /**
  86704. * Returns wehter or not the grid requires alpha blending.
  86705. */
  86706. GridMaterial.prototype.needAlphaBlending = function () {
  86707. return this.opacity < 1.0;
  86708. };
  86709. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  86710. return this.needAlphaBlending();
  86711. };
  86712. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  86713. if (this.isFrozen) {
  86714. if (this._wasPreviouslyReady && subMesh.effect) {
  86715. return true;
  86716. }
  86717. }
  86718. if (!subMesh._materialDefines) {
  86719. subMesh._materialDefines = new GridMaterialDefines();
  86720. }
  86721. var defines = subMesh._materialDefines;
  86722. var scene = this.getScene();
  86723. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  86724. if (this._renderId === scene.getRenderId()) {
  86725. return true;
  86726. }
  86727. }
  86728. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  86729. defines.TRANSPARENT = !defines.TRANSPARENT;
  86730. defines.markAsUnprocessed();
  86731. }
  86732. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  86733. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  86734. defines.markAsUnprocessed();
  86735. }
  86736. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  86737. // Get correct effect
  86738. if (defines.isDirty) {
  86739. defines.markAsProcessed();
  86740. scene.resetCachedMaterial();
  86741. // Attributes
  86742. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86743. // Defines
  86744. var join = defines.toString();
  86745. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  86746. }
  86747. if (!subMesh.effect || !subMesh.effect.isReady()) {
  86748. return false;
  86749. }
  86750. this._renderId = scene.getRenderId();
  86751. this._wasPreviouslyReady = true;
  86752. return true;
  86753. };
  86754. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  86755. var scene = this.getScene();
  86756. var defines = subMesh._materialDefines;
  86757. if (!defines) {
  86758. return;
  86759. }
  86760. var effect = subMesh.effect;
  86761. if (!effect) {
  86762. return;
  86763. }
  86764. this._activeEffect = effect;
  86765. // Matrices
  86766. this.bindOnlyWorldMatrix(world);
  86767. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  86768. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  86769. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  86770. // Uniforms
  86771. if (this._mustRebind(scene, effect)) {
  86772. this._activeEffect.setColor3("mainColor", this.mainColor);
  86773. this._activeEffect.setColor3("lineColor", this.lineColor);
  86774. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  86775. this._gridControl.x = this.gridRatio;
  86776. this._gridControl.y = Math.round(this.majorUnitFrequency);
  86777. this._gridControl.z = this.minorUnitVisibility;
  86778. this._gridControl.w = this.opacity;
  86779. this._activeEffect.setVector4("gridControl", this._gridControl);
  86780. }
  86781. // Fog
  86782. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  86783. this._afterBind(mesh, this._activeEffect);
  86784. };
  86785. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  86786. _super.prototype.dispose.call(this, forceDisposeEffect);
  86787. };
  86788. GridMaterial.prototype.clone = function (name) {
  86789. var _this = this;
  86790. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  86791. };
  86792. GridMaterial.prototype.serialize = function () {
  86793. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86794. serializationObject.customType = "BABYLON.GridMaterial";
  86795. return serializationObject;
  86796. };
  86797. GridMaterial.prototype.getClassName = function () {
  86798. return "GridMaterial";
  86799. };
  86800. GridMaterial.Parse = function (source, scene, rootUrl) {
  86801. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  86802. };
  86803. __decorate([
  86804. BABYLON.serializeAsColor3()
  86805. ], GridMaterial.prototype, "mainColor", void 0);
  86806. __decorate([
  86807. BABYLON.serializeAsColor3()
  86808. ], GridMaterial.prototype, "lineColor", void 0);
  86809. __decorate([
  86810. BABYLON.serialize()
  86811. ], GridMaterial.prototype, "gridRatio", void 0);
  86812. __decorate([
  86813. BABYLON.serializeAsColor3()
  86814. ], GridMaterial.prototype, "gridOffset", void 0);
  86815. __decorate([
  86816. BABYLON.serialize()
  86817. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  86818. __decorate([
  86819. BABYLON.serialize()
  86820. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  86821. __decorate([
  86822. BABYLON.serialize()
  86823. ], GridMaterial.prototype, "opacity", void 0);
  86824. __decorate([
  86825. BABYLON.serialize()
  86826. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  86827. return GridMaterial;
  86828. }(BABYLON.PushMaterial));
  86829. BABYLON.GridMaterial = GridMaterial;
  86830. })(BABYLON || (BABYLON = {}));
  86831. //# sourceMappingURL=babylon.gridmaterial.js.map
  86832. 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}";
  86833. 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}";
  86834. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  86835. var BABYLON;
  86836. (function (BABYLON) {
  86837. var GLTFLoaderCoordinateSystemMode;
  86838. (function (GLTFLoaderCoordinateSystemMode) {
  86839. /**
  86840. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  86841. */
  86842. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  86843. /**
  86844. * Sets the useRightHandedSystem flag on the scene.
  86845. */
  86846. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  86847. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  86848. var GLTFLoaderAnimationStartMode;
  86849. (function (GLTFLoaderAnimationStartMode) {
  86850. /**
  86851. * No animation will start.
  86852. */
  86853. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  86854. /**
  86855. * The first animation will start.
  86856. */
  86857. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  86858. /**
  86859. * All animations will start.
  86860. */
  86861. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  86862. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  86863. var GLTFFileLoader = /** @class */ (function () {
  86864. function GLTFFileLoader() {
  86865. // #region Common options
  86866. /**
  86867. * Raised when the asset has been parsed.
  86868. * The data.json property stores the glTF JSON.
  86869. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  86870. */
  86871. this.onParsedObservable = new BABYLON.Observable();
  86872. // #endregion
  86873. // #region V2 options
  86874. /**
  86875. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  86876. */
  86877. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  86878. /**
  86879. * The animation start mode (NONE, FIRST, ALL).
  86880. */
  86881. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  86882. /**
  86883. * Set to true to compile materials before raising the success callback.
  86884. */
  86885. this.compileMaterials = false;
  86886. /**
  86887. * Set to true to also compile materials with clip planes.
  86888. */
  86889. this.useClipPlane = false;
  86890. /**
  86891. * Set to true to compile shadow generators before raising the success callback.
  86892. */
  86893. this.compileShadowGenerators = false;
  86894. /**
  86895. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  86896. */
  86897. this.onMeshLoadedObservable = new BABYLON.Observable();
  86898. /**
  86899. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  86900. */
  86901. this.onTextureLoadedObservable = new BABYLON.Observable();
  86902. /**
  86903. * Raised when the loader creates a material after parsing the glTF properties of the material.
  86904. */
  86905. this.onMaterialLoadedObservable = new BABYLON.Observable();
  86906. /**
  86907. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  86908. * For assets with LODs, raised when all of the LODs are complete.
  86909. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  86910. */
  86911. this.onCompleteObservable = new BABYLON.Observable();
  86912. /**
  86913. * Raised when the loader is disposed.
  86914. */
  86915. this.onDisposeObservable = new BABYLON.Observable();
  86916. // #endregion
  86917. this._loader = null;
  86918. this.name = "gltf";
  86919. this.extensions = {
  86920. ".gltf": { isBinary: false },
  86921. ".glb": { isBinary: true }
  86922. };
  86923. }
  86924. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  86925. set: function (callback) {
  86926. if (this._onParsedObserver) {
  86927. this.onParsedObservable.remove(this._onParsedObserver);
  86928. }
  86929. this._onParsedObserver = this.onParsedObservable.add(callback);
  86930. },
  86931. enumerable: true,
  86932. configurable: true
  86933. });
  86934. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  86935. set: function (callback) {
  86936. if (this._onMeshLoadedObserver) {
  86937. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  86938. }
  86939. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  86940. },
  86941. enumerable: true,
  86942. configurable: true
  86943. });
  86944. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  86945. set: function (callback) {
  86946. if (this._onTextureLoadedObserver) {
  86947. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  86948. }
  86949. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  86950. },
  86951. enumerable: true,
  86952. configurable: true
  86953. });
  86954. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  86955. set: function (callback) {
  86956. if (this._onMaterialLoadedObserver) {
  86957. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  86958. }
  86959. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  86960. },
  86961. enumerable: true,
  86962. configurable: true
  86963. });
  86964. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  86965. set: function (callback) {
  86966. if (this._onCompleteObserver) {
  86967. this.onCompleteObservable.remove(this._onCompleteObserver);
  86968. }
  86969. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  86970. },
  86971. enumerable: true,
  86972. configurable: true
  86973. });
  86974. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  86975. set: function (callback) {
  86976. if (this._onDisposeObserver) {
  86977. this.onDisposeObservable.remove(this._onDisposeObserver);
  86978. }
  86979. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86980. },
  86981. enumerable: true,
  86982. configurable: true
  86983. });
  86984. /**
  86985. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  86986. */
  86987. GLTFFileLoader.prototype.dispose = function () {
  86988. if (this._loader) {
  86989. this._loader.dispose();
  86990. this._loader = null;
  86991. }
  86992. this.onParsedObservable.clear();
  86993. this.onMeshLoadedObservable.clear();
  86994. this.onTextureLoadedObservable.clear();
  86995. this.onMaterialLoadedObservable.clear();
  86996. this.onCompleteObservable.clear();
  86997. this.onDisposeObservable.notifyObservers(this);
  86998. this.onDisposeObservable.clear();
  86999. };
  87000. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87001. try {
  87002. var loaderData = this._parse(data);
  87003. this._loader = this._getLoader(loaderData);
  87004. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  87005. }
  87006. catch (e) {
  87007. if (onError) {
  87008. onError(e.message, e);
  87009. }
  87010. else {
  87011. BABYLON.Tools.Error(e.message);
  87012. }
  87013. }
  87014. };
  87015. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87016. try {
  87017. var loaderData = this._parse(data);
  87018. this._loader = this._getLoader(loaderData);
  87019. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  87020. }
  87021. catch (e) {
  87022. if (onError) {
  87023. onError(e.message, e);
  87024. }
  87025. else {
  87026. BABYLON.Tools.Error(e.message);
  87027. }
  87028. }
  87029. };
  87030. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87031. try {
  87032. var loaderData = this._parse(data);
  87033. this._loader = this._getLoader(loaderData);
  87034. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  87035. var container = new BABYLON.AssetContainer(scene);
  87036. Array.prototype.push.apply(container.meshes, meshes);
  87037. Array.prototype.push.apply(container.particleSystems, particleSystems);
  87038. Array.prototype.push.apply(container.skeletons, skeletons);
  87039. container.removeAllFromScene();
  87040. onSuccess(container);
  87041. }, onProgress, onError);
  87042. }
  87043. catch (e) {
  87044. if (onError) {
  87045. onError(e.message, e);
  87046. }
  87047. else {
  87048. BABYLON.Tools.Error(e.message);
  87049. }
  87050. }
  87051. };
  87052. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  87053. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  87054. };
  87055. GLTFFileLoader.prototype.createPlugin = function () {
  87056. return new GLTFFileLoader();
  87057. };
  87058. GLTFFileLoader.prototype._parse = function (data) {
  87059. var parsedData;
  87060. if (data instanceof ArrayBuffer) {
  87061. parsedData = GLTFFileLoader._parseBinary(data);
  87062. }
  87063. else {
  87064. parsedData = {
  87065. json: JSON.parse(data),
  87066. bin: null
  87067. };
  87068. }
  87069. this.onParsedObservable.notifyObservers(parsedData);
  87070. return parsedData;
  87071. };
  87072. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  87073. var _this = this;
  87074. var loaderVersion = { major: 2, minor: 0 };
  87075. var asset = loaderData.json.asset || {};
  87076. var version = GLTFFileLoader._parseVersion(asset.version);
  87077. if (!version) {
  87078. throw new Error("Invalid version: " + asset.version);
  87079. }
  87080. if (asset.minVersion !== undefined) {
  87081. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  87082. if (!minVersion) {
  87083. throw new Error("Invalid minimum version: " + asset.minVersion);
  87084. }
  87085. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  87086. throw new Error("Incompatible minimum version: " + asset.minVersion);
  87087. }
  87088. }
  87089. var createLoaders = {
  87090. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  87091. 2: GLTFFileLoader.CreateGLTFLoaderV2
  87092. };
  87093. var createLoader = createLoaders[version.major];
  87094. if (!createLoader) {
  87095. throw new Error("Unsupported version: " + asset.version);
  87096. }
  87097. var loader = createLoader();
  87098. loader.coordinateSystemMode = this.coordinateSystemMode;
  87099. loader.animationStartMode = this.animationStartMode;
  87100. loader.compileMaterials = this.compileMaterials;
  87101. loader.useClipPlane = this.useClipPlane;
  87102. loader.compileShadowGenerators = this.compileShadowGenerators;
  87103. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  87104. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  87105. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  87106. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  87107. return loader;
  87108. };
  87109. GLTFFileLoader._parseBinary = function (data) {
  87110. var Binary = {
  87111. Magic: 0x46546C67
  87112. };
  87113. var binaryReader = new BinaryReader(data);
  87114. var magic = binaryReader.readUint32();
  87115. if (magic !== Binary.Magic) {
  87116. throw new Error("Unexpected magic: " + magic);
  87117. }
  87118. var version = binaryReader.readUint32();
  87119. switch (version) {
  87120. case 1: return GLTFFileLoader._parseV1(binaryReader);
  87121. case 2: return GLTFFileLoader._parseV2(binaryReader);
  87122. }
  87123. throw new Error("Unsupported version: " + version);
  87124. };
  87125. GLTFFileLoader._parseV1 = function (binaryReader) {
  87126. var ContentFormat = {
  87127. JSON: 0
  87128. };
  87129. var length = binaryReader.readUint32();
  87130. if (length != binaryReader.getLength()) {
  87131. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  87132. }
  87133. var contentLength = binaryReader.readUint32();
  87134. var contentFormat = binaryReader.readUint32();
  87135. var content;
  87136. switch (contentFormat) {
  87137. case ContentFormat.JSON: {
  87138. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  87139. break;
  87140. }
  87141. default: {
  87142. throw new Error("Unexpected content format: " + contentFormat);
  87143. }
  87144. }
  87145. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  87146. var body = binaryReader.readUint8Array(bytesRemaining);
  87147. return {
  87148. json: content,
  87149. bin: body
  87150. };
  87151. };
  87152. GLTFFileLoader._parseV2 = function (binaryReader) {
  87153. var ChunkFormat = {
  87154. JSON: 0x4E4F534A,
  87155. BIN: 0x004E4942
  87156. };
  87157. var length = binaryReader.readUint32();
  87158. if (length !== binaryReader.getLength()) {
  87159. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  87160. }
  87161. // JSON chunk
  87162. var chunkLength = binaryReader.readUint32();
  87163. var chunkFormat = binaryReader.readUint32();
  87164. if (chunkFormat !== ChunkFormat.JSON) {
  87165. throw new Error("First chunk format is not JSON");
  87166. }
  87167. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  87168. // Look for BIN chunk
  87169. var bin = null;
  87170. while (binaryReader.getPosition() < binaryReader.getLength()) {
  87171. var chunkLength_1 = binaryReader.readUint32();
  87172. var chunkFormat_1 = binaryReader.readUint32();
  87173. switch (chunkFormat_1) {
  87174. case ChunkFormat.JSON: {
  87175. throw new Error("Unexpected JSON chunk");
  87176. }
  87177. case ChunkFormat.BIN: {
  87178. bin = binaryReader.readUint8Array(chunkLength_1);
  87179. break;
  87180. }
  87181. default: {
  87182. // ignore unrecognized chunkFormat
  87183. binaryReader.skipBytes(chunkLength_1);
  87184. break;
  87185. }
  87186. }
  87187. }
  87188. return {
  87189. json: json,
  87190. bin: bin
  87191. };
  87192. };
  87193. GLTFFileLoader._parseVersion = function (version) {
  87194. if (version === "1.0" || version === "1.0.1") {
  87195. return {
  87196. major: 1,
  87197. minor: 0
  87198. };
  87199. }
  87200. var match = (version + "").match(/^(\d+)\.(\d+)/);
  87201. if (!match) {
  87202. return null;
  87203. }
  87204. return {
  87205. major: parseInt(match[1]),
  87206. minor: parseInt(match[2])
  87207. };
  87208. };
  87209. GLTFFileLoader._compareVersion = function (a, b) {
  87210. if (a.major > b.major)
  87211. return 1;
  87212. if (a.major < b.major)
  87213. return -1;
  87214. if (a.minor > b.minor)
  87215. return 1;
  87216. if (a.minor < b.minor)
  87217. return -1;
  87218. return 0;
  87219. };
  87220. GLTFFileLoader._decodeBufferToText = function (buffer) {
  87221. var result = "";
  87222. var length = buffer.byteLength;
  87223. for (var i = 0; i < length; i++) {
  87224. result += String.fromCharCode(buffer[i]);
  87225. }
  87226. return result;
  87227. };
  87228. // #endregion
  87229. // #region V1 options
  87230. GLTFFileLoader.IncrementalLoading = true;
  87231. GLTFFileLoader.HomogeneousCoordinates = false;
  87232. return GLTFFileLoader;
  87233. }());
  87234. BABYLON.GLTFFileLoader = GLTFFileLoader;
  87235. var BinaryReader = /** @class */ (function () {
  87236. function BinaryReader(arrayBuffer) {
  87237. this._arrayBuffer = arrayBuffer;
  87238. this._dataView = new DataView(arrayBuffer);
  87239. this._byteOffset = 0;
  87240. }
  87241. BinaryReader.prototype.getPosition = function () {
  87242. return this._byteOffset;
  87243. };
  87244. BinaryReader.prototype.getLength = function () {
  87245. return this._arrayBuffer.byteLength;
  87246. };
  87247. BinaryReader.prototype.readUint32 = function () {
  87248. var value = this._dataView.getUint32(this._byteOffset, true);
  87249. this._byteOffset += 4;
  87250. return value;
  87251. };
  87252. BinaryReader.prototype.readUint8Array = function (length) {
  87253. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  87254. this._byteOffset += length;
  87255. return value;
  87256. };
  87257. BinaryReader.prototype.skipBytes = function (length) {
  87258. this._byteOffset += length;
  87259. };
  87260. return BinaryReader;
  87261. }());
  87262. if (BABYLON.SceneLoader) {
  87263. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  87264. }
  87265. })(BABYLON || (BABYLON = {}));
  87266. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  87267. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87268. var BABYLON;
  87269. (function (BABYLON) {
  87270. var GLTF1;
  87271. (function (GLTF1) {
  87272. /**
  87273. * Enums
  87274. */
  87275. var EComponentType;
  87276. (function (EComponentType) {
  87277. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  87278. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  87279. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  87280. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  87281. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  87282. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  87283. var EShaderType;
  87284. (function (EShaderType) {
  87285. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  87286. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  87287. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  87288. var EParameterType;
  87289. (function (EParameterType) {
  87290. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  87291. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  87292. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  87293. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  87294. EParameterType[EParameterType["INT"] = 5124] = "INT";
  87295. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  87296. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  87297. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  87298. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  87299. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  87300. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  87301. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  87302. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  87303. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  87304. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  87305. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  87306. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  87307. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  87308. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  87309. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  87310. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  87311. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  87312. var ETextureWrapMode;
  87313. (function (ETextureWrapMode) {
  87314. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  87315. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  87316. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  87317. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  87318. var ETextureFilterType;
  87319. (function (ETextureFilterType) {
  87320. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  87321. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  87322. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  87323. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  87324. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  87325. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  87326. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  87327. var ETextureFormat;
  87328. (function (ETextureFormat) {
  87329. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  87330. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  87331. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  87332. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  87333. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  87334. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  87335. var ECullingType;
  87336. (function (ECullingType) {
  87337. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  87338. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  87339. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  87340. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  87341. var EBlendingFunction;
  87342. (function (EBlendingFunction) {
  87343. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  87344. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  87345. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  87346. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  87347. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  87348. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  87349. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  87350. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  87351. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  87352. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  87353. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  87354. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  87355. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  87356. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  87357. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  87358. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  87359. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87360. })(BABYLON || (BABYLON = {}));
  87361. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  87362. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87363. var BABYLON;
  87364. (function (BABYLON) {
  87365. var GLTF1;
  87366. (function (GLTF1) {
  87367. /**
  87368. * Tokenizer. Used for shaders compatibility
  87369. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  87370. */
  87371. var ETokenType;
  87372. (function (ETokenType) {
  87373. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  87374. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  87375. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  87376. })(ETokenType || (ETokenType = {}));
  87377. var Tokenizer = /** @class */ (function () {
  87378. function Tokenizer(toParse) {
  87379. this._pos = 0;
  87380. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  87381. this._toParse = toParse;
  87382. this._maxPos = toParse.length;
  87383. }
  87384. Tokenizer.prototype.getNextToken = function () {
  87385. if (this.isEnd())
  87386. return ETokenType.END_OF_INPUT;
  87387. this.currentString = this.read();
  87388. this.currentToken = ETokenType.UNKNOWN;
  87389. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  87390. this.currentToken = ETokenType.IDENTIFIER;
  87391. this.currentIdentifier = this.currentString;
  87392. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  87393. this.currentIdentifier += this.currentString;
  87394. this.forward();
  87395. }
  87396. }
  87397. return this.currentToken;
  87398. };
  87399. Tokenizer.prototype.peek = function () {
  87400. return this._toParse[this._pos];
  87401. };
  87402. Tokenizer.prototype.read = function () {
  87403. return this._toParse[this._pos++];
  87404. };
  87405. Tokenizer.prototype.forward = function () {
  87406. this._pos++;
  87407. };
  87408. Tokenizer.prototype.isEnd = function () {
  87409. return this._pos >= this._maxPos;
  87410. };
  87411. return Tokenizer;
  87412. }());
  87413. /**
  87414. * Values
  87415. */
  87416. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  87417. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  87418. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  87419. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  87420. /**
  87421. * Parse
  87422. */
  87423. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  87424. for (var buf in parsedBuffers) {
  87425. var parsedBuffer = parsedBuffers[buf];
  87426. gltfRuntime.buffers[buf] = parsedBuffer;
  87427. gltfRuntime.buffersCount++;
  87428. }
  87429. };
  87430. var parseShaders = function (parsedShaders, gltfRuntime) {
  87431. for (var sha in parsedShaders) {
  87432. var parsedShader = parsedShaders[sha];
  87433. gltfRuntime.shaders[sha] = parsedShader;
  87434. gltfRuntime.shaderscount++;
  87435. }
  87436. };
  87437. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  87438. for (var object in parsedObjects) {
  87439. var parsedObject = parsedObjects[object];
  87440. gltfRuntime[runtimeProperty][object] = parsedObject;
  87441. }
  87442. };
  87443. /**
  87444. * Utils
  87445. */
  87446. var normalizeUVs = function (buffer) {
  87447. if (!buffer) {
  87448. return;
  87449. }
  87450. for (var i = 0; i < buffer.length / 2; i++) {
  87451. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  87452. }
  87453. };
  87454. var getAttribute = function (attributeParameter) {
  87455. if (attributeParameter.semantic === "NORMAL") {
  87456. return "normal";
  87457. }
  87458. else if (attributeParameter.semantic === "POSITION") {
  87459. return "position";
  87460. }
  87461. else if (attributeParameter.semantic === "JOINT") {
  87462. return "matricesIndices";
  87463. }
  87464. else if (attributeParameter.semantic === "WEIGHT") {
  87465. return "matricesWeights";
  87466. }
  87467. else if (attributeParameter.semantic === "COLOR") {
  87468. return "color";
  87469. }
  87470. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  87471. var channel = Number(attributeParameter.semantic.split("_")[1]);
  87472. return "uv" + (channel === 0 ? "" : channel + 1);
  87473. }
  87474. return null;
  87475. };
  87476. /**
  87477. * Loads and creates animations
  87478. */
  87479. var loadAnimations = function (gltfRuntime) {
  87480. for (var anim in gltfRuntime.animations) {
  87481. var animation = gltfRuntime.animations[anim];
  87482. if (!animation.channels || !animation.samplers) {
  87483. continue;
  87484. }
  87485. var lastAnimation = null;
  87486. for (var i = 0; i < animation.channels.length; i++) {
  87487. // Get parameters and load buffers
  87488. var channel = animation.channels[i];
  87489. var sampler = animation.samplers[channel.sampler];
  87490. if (!sampler) {
  87491. continue;
  87492. }
  87493. var inputData = null;
  87494. var outputData = null;
  87495. if (animation.parameters) {
  87496. inputData = animation.parameters[sampler.input];
  87497. outputData = animation.parameters[sampler.output];
  87498. }
  87499. else {
  87500. inputData = sampler.input;
  87501. outputData = sampler.output;
  87502. }
  87503. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  87504. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  87505. var targetID = channel.target.id;
  87506. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  87507. if (targetNode === null) {
  87508. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  87509. }
  87510. if (targetNode === null) {
  87511. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  87512. continue;
  87513. }
  87514. var isBone = targetNode instanceof BABYLON.Bone;
  87515. // Get target path (position, rotation or scaling)
  87516. var targetPath = channel.target.path;
  87517. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  87518. if (targetPathIndex !== -1) {
  87519. targetPath = babylonAnimationPaths[targetPathIndex];
  87520. }
  87521. // Determine animation type
  87522. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  87523. if (!isBone) {
  87524. if (targetPath === "rotationQuaternion") {
  87525. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  87526. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  87527. }
  87528. else {
  87529. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87530. }
  87531. }
  87532. // Create animation and key frames
  87533. var babylonAnimation = null;
  87534. var keys = [];
  87535. var arrayOffset = 0;
  87536. var modifyKey = false;
  87537. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  87538. babylonAnimation = lastAnimation;
  87539. modifyKey = true;
  87540. }
  87541. if (!modifyKey) {
  87542. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87543. }
  87544. // For each frame
  87545. for (var j = 0; j < bufferInput.length; j++) {
  87546. var value = null;
  87547. if (targetPath === "rotationQuaternion") {
  87548. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  87549. arrayOffset += 4;
  87550. }
  87551. else {
  87552. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  87553. arrayOffset += 3;
  87554. }
  87555. if (isBone) {
  87556. var bone = targetNode;
  87557. var translation = BABYLON.Vector3.Zero();
  87558. var rotationQuaternion = new BABYLON.Quaternion();
  87559. var scaling = BABYLON.Vector3.Zero();
  87560. // Warning on decompose
  87561. var mat = bone.getBaseMatrix();
  87562. if (modifyKey && lastAnimation) {
  87563. mat = lastAnimation.getKeys()[j].value;
  87564. }
  87565. mat.decompose(scaling, rotationQuaternion, translation);
  87566. if (targetPath === "position") {
  87567. translation = value;
  87568. }
  87569. else if (targetPath === "rotationQuaternion") {
  87570. rotationQuaternion = value;
  87571. }
  87572. else {
  87573. scaling = value;
  87574. }
  87575. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  87576. }
  87577. if (!modifyKey) {
  87578. keys.push({
  87579. frame: bufferInput[j],
  87580. value: value
  87581. });
  87582. }
  87583. else if (lastAnimation) {
  87584. lastAnimation.getKeys()[j].value = value;
  87585. }
  87586. }
  87587. // Finish
  87588. if (!modifyKey && babylonAnimation) {
  87589. babylonAnimation.setKeys(keys);
  87590. targetNode.animations.push(babylonAnimation);
  87591. }
  87592. lastAnimation = babylonAnimation;
  87593. gltfRuntime.scene.stopAnimation(targetNode);
  87594. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  87595. }
  87596. }
  87597. };
  87598. /**
  87599. * Returns the bones transformation matrix
  87600. */
  87601. var configureBoneTransformation = function (node) {
  87602. var mat = null;
  87603. if (node.translation || node.rotation || node.scale) {
  87604. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  87605. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  87606. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  87607. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  87608. }
  87609. else {
  87610. mat = BABYLON.Matrix.FromArray(node.matrix);
  87611. }
  87612. return mat;
  87613. };
  87614. /**
  87615. * Returns the parent bone
  87616. */
  87617. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  87618. // Try to find
  87619. for (var i = 0; i < newSkeleton.bones.length; i++) {
  87620. if (newSkeleton.bones[i].name === jointName) {
  87621. return newSkeleton.bones[i];
  87622. }
  87623. }
  87624. // Not found, search in gltf nodes
  87625. var nodes = gltfRuntime.nodes;
  87626. for (var nde in nodes) {
  87627. var node = nodes[nde];
  87628. if (!node.jointName) {
  87629. continue;
  87630. }
  87631. var children = node.children;
  87632. for (var i = 0; i < children.length; i++) {
  87633. var child = gltfRuntime.nodes[children[i]];
  87634. if (!child.jointName) {
  87635. continue;
  87636. }
  87637. if (child.jointName === jointName) {
  87638. var mat = configureBoneTransformation(node);
  87639. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  87640. bone.id = nde;
  87641. return bone;
  87642. }
  87643. }
  87644. }
  87645. return null;
  87646. };
  87647. /**
  87648. * Returns the appropriate root node
  87649. */
  87650. var getNodeToRoot = function (nodesToRoot, id) {
  87651. for (var i = 0; i < nodesToRoot.length; i++) {
  87652. var nodeToRoot = nodesToRoot[i];
  87653. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  87654. var child = nodeToRoot.node.children[j];
  87655. if (child === id) {
  87656. return nodeToRoot.bone;
  87657. }
  87658. }
  87659. }
  87660. return null;
  87661. };
  87662. /**
  87663. * Returns the node with the joint name
  87664. */
  87665. var getJointNode = function (gltfRuntime, jointName) {
  87666. var nodes = gltfRuntime.nodes;
  87667. var node = nodes[jointName];
  87668. if (node) {
  87669. return {
  87670. node: node,
  87671. id: jointName
  87672. };
  87673. }
  87674. for (var nde in nodes) {
  87675. node = nodes[nde];
  87676. if (node.jointName === jointName) {
  87677. return {
  87678. node: node,
  87679. id: nde
  87680. };
  87681. }
  87682. }
  87683. return null;
  87684. };
  87685. /**
  87686. * Checks if a nodes is in joints
  87687. */
  87688. var nodeIsInJoints = function (skins, id) {
  87689. for (var i = 0; i < skins.jointNames.length; i++) {
  87690. if (skins.jointNames[i] === id) {
  87691. return true;
  87692. }
  87693. }
  87694. return false;
  87695. };
  87696. /**
  87697. * Fills the nodes to root for bones and builds hierarchy
  87698. */
  87699. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  87700. // Creates nodes for root
  87701. for (var nde in gltfRuntime.nodes) {
  87702. var node = gltfRuntime.nodes[nde];
  87703. var id = nde;
  87704. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  87705. continue;
  87706. }
  87707. // Create node to root bone
  87708. var mat = configureBoneTransformation(node);
  87709. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  87710. bone.id = id;
  87711. nodesToRoot.push({ bone: bone, node: node, id: id });
  87712. }
  87713. // Parenting
  87714. for (var i = 0; i < nodesToRoot.length; i++) {
  87715. var nodeToRoot = nodesToRoot[i];
  87716. var children = nodeToRoot.node.children;
  87717. for (var j = 0; j < children.length; j++) {
  87718. var child = null;
  87719. for (var k = 0; k < nodesToRoot.length; k++) {
  87720. if (nodesToRoot[k].id === children[j]) {
  87721. child = nodesToRoot[k];
  87722. break;
  87723. }
  87724. }
  87725. if (child) {
  87726. child.bone._parent = nodeToRoot.bone;
  87727. nodeToRoot.bone.children.push(child.bone);
  87728. }
  87729. }
  87730. }
  87731. };
  87732. /**
  87733. * Imports a skeleton
  87734. */
  87735. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  87736. if (!newSkeleton) {
  87737. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  87738. }
  87739. if (!skins.babylonSkeleton) {
  87740. return newSkeleton;
  87741. }
  87742. // Find the root bones
  87743. var nodesToRoot = [];
  87744. var nodesToRootToAdd = [];
  87745. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  87746. newSkeleton.bones = [];
  87747. // Joints
  87748. for (var i = 0; i < skins.jointNames.length; i++) {
  87749. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  87750. if (!jointNode) {
  87751. continue;
  87752. }
  87753. var node = jointNode.node;
  87754. if (!node) {
  87755. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  87756. continue;
  87757. }
  87758. var id = jointNode.id;
  87759. // Optimize, if the bone already exists...
  87760. var existingBone = gltfRuntime.scene.getBoneByID(id);
  87761. if (existingBone) {
  87762. newSkeleton.bones.push(existingBone);
  87763. continue;
  87764. }
  87765. // Search for parent bone
  87766. var foundBone = false;
  87767. var parentBone = null;
  87768. for (var j = 0; j < i; j++) {
  87769. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  87770. if (!jointNode_1) {
  87771. continue;
  87772. }
  87773. var joint = jointNode_1.node;
  87774. if (!joint) {
  87775. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  87776. continue;
  87777. }
  87778. var children = joint.children;
  87779. if (!children) {
  87780. continue;
  87781. }
  87782. foundBone = false;
  87783. for (var k = 0; k < children.length; k++) {
  87784. if (children[k] === id) {
  87785. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  87786. foundBone = true;
  87787. break;
  87788. }
  87789. }
  87790. if (foundBone) {
  87791. break;
  87792. }
  87793. }
  87794. // Create bone
  87795. var mat = configureBoneTransformation(node);
  87796. if (!parentBone && nodesToRoot.length > 0) {
  87797. parentBone = getNodeToRoot(nodesToRoot, id);
  87798. if (parentBone) {
  87799. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  87800. nodesToRootToAdd.push(parentBone);
  87801. }
  87802. }
  87803. }
  87804. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  87805. bone.id = id;
  87806. }
  87807. // Polish
  87808. var bones = newSkeleton.bones;
  87809. newSkeleton.bones = [];
  87810. for (var i = 0; i < skins.jointNames.length; i++) {
  87811. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  87812. if (!jointNode) {
  87813. continue;
  87814. }
  87815. for (var j = 0; j < bones.length; j++) {
  87816. if (bones[j].id === jointNode.id) {
  87817. newSkeleton.bones.push(bones[j]);
  87818. break;
  87819. }
  87820. }
  87821. }
  87822. newSkeleton.prepare();
  87823. // Finish
  87824. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  87825. newSkeleton.bones.push(nodesToRootToAdd[i]);
  87826. }
  87827. return newSkeleton;
  87828. };
  87829. /**
  87830. * Imports a mesh and its geometries
  87831. */
  87832. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  87833. if (!newMesh) {
  87834. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  87835. newMesh.id = id;
  87836. }
  87837. if (!node.babylonNode) {
  87838. return newMesh;
  87839. }
  87840. var subMaterials = [];
  87841. var vertexData = new BABYLON.VertexData();
  87842. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  87843. var verticesStarts = new Array();
  87844. var verticesCounts = new Array();
  87845. var indexStarts = new Array();
  87846. var indexCounts = new Array();
  87847. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  87848. var meshID = meshes[meshIndex];
  87849. var mesh = gltfRuntime.meshes[meshID];
  87850. if (!mesh) {
  87851. continue;
  87852. }
  87853. // Positions, normals and UVs
  87854. for (var i = 0; i < mesh.primitives.length; i++) {
  87855. // Temporary vertex data
  87856. var tempVertexData = new BABYLON.VertexData();
  87857. var primitive = mesh.primitives[i];
  87858. if (primitive.mode !== 4) {
  87859. // continue;
  87860. }
  87861. var attributes = primitive.attributes;
  87862. var accessor = null;
  87863. var buffer = null;
  87864. // Set positions, normal and uvs
  87865. for (var semantic in attributes) {
  87866. // Link accessor and buffer view
  87867. accessor = gltfRuntime.accessors[attributes[semantic]];
  87868. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  87869. if (semantic === "NORMAL") {
  87870. tempVertexData.normals = new Float32Array(buffer.length);
  87871. tempVertexData.normals.set(buffer);
  87872. }
  87873. else if (semantic === "POSITION") {
  87874. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  87875. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  87876. for (var j = 0; j < buffer.length; j += 4) {
  87877. tempVertexData.positions[j] = buffer[j];
  87878. tempVertexData.positions[j + 1] = buffer[j + 1];
  87879. tempVertexData.positions[j + 2] = buffer[j + 2];
  87880. }
  87881. }
  87882. else {
  87883. tempVertexData.positions = new Float32Array(buffer.length);
  87884. tempVertexData.positions.set(buffer);
  87885. }
  87886. verticesCounts.push(tempVertexData.positions.length);
  87887. }
  87888. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  87889. var channel = Number(semantic.split("_")[1]);
  87890. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  87891. var uvs = new Float32Array(buffer.length);
  87892. uvs.set(buffer);
  87893. normalizeUVs(uvs);
  87894. tempVertexData.set(uvs, uvKind);
  87895. }
  87896. else if (semantic === "JOINT") {
  87897. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  87898. tempVertexData.matricesIndices.set(buffer);
  87899. }
  87900. else if (semantic === "WEIGHT") {
  87901. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  87902. tempVertexData.matricesWeights.set(buffer);
  87903. }
  87904. else if (semantic === "COLOR") {
  87905. tempVertexData.colors = new Float32Array(buffer.length);
  87906. tempVertexData.colors.set(buffer);
  87907. }
  87908. }
  87909. // Indices
  87910. accessor = gltfRuntime.accessors[primitive.indices];
  87911. if (accessor) {
  87912. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  87913. tempVertexData.indices = new Int32Array(buffer.length);
  87914. tempVertexData.indices.set(buffer);
  87915. indexCounts.push(tempVertexData.indices.length);
  87916. }
  87917. else {
  87918. // Set indices on the fly
  87919. var indices = [];
  87920. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  87921. indices.push(j);
  87922. }
  87923. tempVertexData.indices = new Int32Array(indices);
  87924. indexCounts.push(tempVertexData.indices.length);
  87925. }
  87926. vertexData.merge(tempVertexData);
  87927. // Sub material
  87928. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  87929. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  87930. // Update vertices start and index start
  87931. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  87932. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  87933. }
  87934. }
  87935. var material;
  87936. if (subMaterials.length > 1) {
  87937. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  87938. material.subMaterials = subMaterials;
  87939. }
  87940. else {
  87941. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  87942. }
  87943. if (subMaterials.length === 1) {
  87944. material = subMaterials[0];
  87945. }
  87946. if (!newMesh.material) {
  87947. newMesh.material = material;
  87948. }
  87949. // Apply geometry
  87950. geometry.setAllVerticesData(vertexData, false);
  87951. newMesh.computeWorldMatrix(true);
  87952. // Apply submeshes
  87953. newMesh.subMeshes = [];
  87954. var index = 0;
  87955. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  87956. var meshID = meshes[meshIndex];
  87957. var mesh = gltfRuntime.meshes[meshID];
  87958. if (!mesh) {
  87959. continue;
  87960. }
  87961. for (var i = 0; i < mesh.primitives.length; i++) {
  87962. if (mesh.primitives[i].mode !== 4) {
  87963. //continue;
  87964. }
  87965. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  87966. index++;
  87967. }
  87968. }
  87969. // Finish
  87970. return newMesh;
  87971. };
  87972. /**
  87973. * Configure node transformation from position, rotation and scaling
  87974. */
  87975. var configureNode = function (newNode, position, rotation, scaling) {
  87976. if (newNode.position) {
  87977. newNode.position = position;
  87978. }
  87979. if (newNode.rotationQuaternion || newNode.rotation) {
  87980. newNode.rotationQuaternion = rotation;
  87981. }
  87982. if (newNode.scaling) {
  87983. newNode.scaling = scaling;
  87984. }
  87985. };
  87986. /**
  87987. * Configures node from transformation matrix
  87988. */
  87989. var configureNodeFromMatrix = function (newNode, node, parent) {
  87990. if (node.matrix) {
  87991. var position = new BABYLON.Vector3(0, 0, 0);
  87992. var rotation = new BABYLON.Quaternion();
  87993. var scaling = new BABYLON.Vector3(0, 0, 0);
  87994. var mat = BABYLON.Matrix.FromArray(node.matrix);
  87995. mat.decompose(scaling, rotation, position);
  87996. configureNode(newNode, position, rotation, scaling);
  87997. }
  87998. else if (node.translation && node.rotation && node.scale) {
  87999. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  88000. }
  88001. newNode.computeWorldMatrix(true);
  88002. };
  88003. /**
  88004. * Imports a node
  88005. */
  88006. var importNode = function (gltfRuntime, node, id, parent) {
  88007. var lastNode = null;
  88008. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  88009. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  88010. return null;
  88011. }
  88012. }
  88013. // Meshes
  88014. if (node.skin) {
  88015. if (node.meshes) {
  88016. var skin = gltfRuntime.skins[node.skin];
  88017. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  88018. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  88019. if (newMesh.skeleton === null) {
  88020. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  88021. if (!skin.babylonSkeleton) {
  88022. skin.babylonSkeleton = newMesh.skeleton;
  88023. }
  88024. }
  88025. lastNode = newMesh;
  88026. }
  88027. }
  88028. else if (node.meshes) {
  88029. /**
  88030. * Improve meshes property
  88031. */
  88032. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  88033. lastNode = newMesh;
  88034. }
  88035. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  88036. var light = gltfRuntime.lights[node.light];
  88037. if (light) {
  88038. if (light.type === "ambient") {
  88039. var ambienLight = light[light.type];
  88040. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88041. hemiLight.name = node.name || "";
  88042. if (ambienLight.color) {
  88043. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  88044. }
  88045. lastNode = hemiLight;
  88046. }
  88047. else if (light.type === "directional") {
  88048. var directionalLight = light[light.type];
  88049. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88050. dirLight.name = node.name || "";
  88051. if (directionalLight.color) {
  88052. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  88053. }
  88054. lastNode = dirLight;
  88055. }
  88056. else if (light.type === "point") {
  88057. var pointLight = light[light.type];
  88058. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88059. ptLight.name = node.name || "";
  88060. if (pointLight.color) {
  88061. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  88062. }
  88063. lastNode = ptLight;
  88064. }
  88065. else if (light.type === "spot") {
  88066. var spotLight = light[light.type];
  88067. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  88068. spLight.name = node.name || "";
  88069. if (spotLight.color) {
  88070. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  88071. }
  88072. if (spotLight.fallOfAngle) {
  88073. spLight.angle = spotLight.fallOfAngle;
  88074. }
  88075. if (spotLight.fallOffExponent) {
  88076. spLight.exponent = spotLight.fallOffExponent;
  88077. }
  88078. lastNode = spLight;
  88079. }
  88080. }
  88081. }
  88082. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  88083. var camera = gltfRuntime.cameras[node.camera];
  88084. if (camera) {
  88085. if (camera.type === "orthographic") {
  88086. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88087. orthoCamera.name = node.name || "";
  88088. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  88089. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  88090. lastNode = orthoCamera;
  88091. }
  88092. else if (camera.type === "perspective") {
  88093. var perspectiveCamera = camera[camera.type];
  88094. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88095. persCamera.name = node.name || "";
  88096. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  88097. if (!perspectiveCamera.aspectRatio) {
  88098. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  88099. }
  88100. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  88101. persCamera.maxZ = perspectiveCamera.zfar;
  88102. persCamera.minZ = perspectiveCamera.znear;
  88103. }
  88104. lastNode = persCamera;
  88105. }
  88106. }
  88107. }
  88108. // Empty node
  88109. if (!node.jointName) {
  88110. if (node.babylonNode) {
  88111. return node.babylonNode;
  88112. }
  88113. else if (lastNode === null) {
  88114. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  88115. node.babylonNode = dummy;
  88116. lastNode = dummy;
  88117. }
  88118. }
  88119. if (lastNode !== null) {
  88120. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  88121. configureNodeFromMatrix(lastNode, node, parent);
  88122. }
  88123. else {
  88124. var translation = node.translation || [0, 0, 0];
  88125. var rotation = node.rotation || [0, 0, 0, 1];
  88126. var scale = node.scale || [1, 1, 1];
  88127. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  88128. }
  88129. lastNode.updateCache(true);
  88130. node.babylonNode = lastNode;
  88131. }
  88132. return lastNode;
  88133. };
  88134. /**
  88135. * Traverses nodes and creates them
  88136. */
  88137. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  88138. if (meshIncluded === void 0) { meshIncluded = false; }
  88139. var node = gltfRuntime.nodes[id];
  88140. var newNode = null;
  88141. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  88142. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  88143. meshIncluded = true;
  88144. }
  88145. else {
  88146. meshIncluded = false;
  88147. }
  88148. }
  88149. else {
  88150. meshIncluded = true;
  88151. }
  88152. if (!node.jointName && meshIncluded) {
  88153. newNode = importNode(gltfRuntime, node, id, parent);
  88154. if (newNode !== null) {
  88155. newNode.id = id;
  88156. newNode.parent = parent;
  88157. }
  88158. }
  88159. if (node.children) {
  88160. for (var i = 0; i < node.children.length; i++) {
  88161. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  88162. }
  88163. }
  88164. };
  88165. /**
  88166. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  88167. */
  88168. var postLoad = function (gltfRuntime) {
  88169. // Nodes
  88170. var currentScene = gltfRuntime.currentScene;
  88171. if (currentScene) {
  88172. for (var i = 0; i < currentScene.nodes.length; i++) {
  88173. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  88174. }
  88175. }
  88176. else {
  88177. for (var thing in gltfRuntime.scenes) {
  88178. currentScene = gltfRuntime.scenes[thing];
  88179. for (var i = 0; i < currentScene.nodes.length; i++) {
  88180. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  88181. }
  88182. }
  88183. }
  88184. // Set animations
  88185. loadAnimations(gltfRuntime);
  88186. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  88187. var skeleton = gltfRuntime.scene.skeletons[i];
  88188. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  88189. }
  88190. };
  88191. /**
  88192. * onBind shaderrs callback to set uniforms and matrices
  88193. */
  88194. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  88195. var materialValues = material.values || technique.parameters;
  88196. for (var unif in unTreatedUniforms) {
  88197. var uniform = unTreatedUniforms[unif];
  88198. var type = uniform.type;
  88199. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  88200. if (uniform.semantic && !uniform.source && !uniform.node) {
  88201. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  88202. }
  88203. else if (uniform.semantic && (uniform.source || uniform.node)) {
  88204. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  88205. if (source === null) {
  88206. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  88207. }
  88208. if (source === null) {
  88209. continue;
  88210. }
  88211. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  88212. }
  88213. }
  88214. else {
  88215. var value = materialValues[technique.uniforms[unif]];
  88216. if (!value) {
  88217. continue;
  88218. }
  88219. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  88220. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  88221. if (texture === null || texture === undefined) {
  88222. continue;
  88223. }
  88224. shaderMaterial.getEffect().setTexture(unif, texture);
  88225. }
  88226. else {
  88227. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  88228. }
  88229. }
  88230. }
  88231. onSuccess(shaderMaterial);
  88232. };
  88233. /**
  88234. * Prepare uniforms to send the only one time
  88235. * Loads the appropriate textures
  88236. */
  88237. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  88238. var materialValues = material.values || technique.parameters;
  88239. var techniqueUniforms = technique.uniforms;
  88240. /**
  88241. * Prepare values here (not matrices)
  88242. */
  88243. for (var unif in unTreatedUniforms) {
  88244. var uniform = unTreatedUniforms[unif];
  88245. var type = uniform.type;
  88246. var value = materialValues[techniqueUniforms[unif]];
  88247. if (value === undefined) {
  88248. // In case the value is the same for all materials
  88249. value = uniform.value;
  88250. }
  88251. if (!value) {
  88252. continue;
  88253. }
  88254. var onLoadTexture = function (uniformName) {
  88255. return function (texture) {
  88256. if (uniform.value && uniformName) {
  88257. // Static uniform
  88258. shaderMaterial.setTexture(uniformName, texture);
  88259. delete unTreatedUniforms[uniformName];
  88260. }
  88261. };
  88262. };
  88263. // Texture (sampler2D)
  88264. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  88265. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  88266. }
  88267. else {
  88268. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  88269. // Static uniform
  88270. delete unTreatedUniforms[unif];
  88271. }
  88272. }
  88273. }
  88274. };
  88275. /**
  88276. * Shader compilation failed
  88277. */
  88278. var onShaderCompileError = function (program, shaderMaterial, onError) {
  88279. return function (effect, error) {
  88280. shaderMaterial.dispose(true);
  88281. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  88282. };
  88283. };
  88284. /**
  88285. * Shader compilation success
  88286. */
  88287. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  88288. return function (_) {
  88289. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  88290. shaderMaterial.onBind = function (mesh) {
  88291. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  88292. };
  88293. };
  88294. };
  88295. /**
  88296. * Returns the appropriate uniform if already handled by babylon
  88297. */
  88298. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  88299. for (var unif in technique.uniforms) {
  88300. var uniform = technique.uniforms[unif];
  88301. var uniformParameter = technique.parameters[uniform];
  88302. if (tokenizer.currentIdentifier === unif) {
  88303. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  88304. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  88305. if (transformIndex !== -1) {
  88306. delete unTreatedUniforms[unif];
  88307. return babylonTransforms[transformIndex];
  88308. }
  88309. }
  88310. }
  88311. }
  88312. return tokenizer.currentIdentifier;
  88313. };
  88314. /**
  88315. * All shaders loaded. Create materials one by one
  88316. */
  88317. var importMaterials = function (gltfRuntime) {
  88318. // Create materials
  88319. for (var mat in gltfRuntime.materials) {
  88320. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  88321. }
  88322. };
  88323. /**
  88324. * Implementation of the base glTF spec
  88325. */
  88326. var GLTFLoaderBase = /** @class */ (function () {
  88327. function GLTFLoaderBase() {
  88328. }
  88329. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  88330. var gltfRuntime = {
  88331. extensions: {},
  88332. accessors: {},
  88333. buffers: {},
  88334. bufferViews: {},
  88335. meshes: {},
  88336. lights: {},
  88337. cameras: {},
  88338. nodes: {},
  88339. images: {},
  88340. textures: {},
  88341. shaders: {},
  88342. programs: {},
  88343. samplers: {},
  88344. techniques: {},
  88345. materials: {},
  88346. animations: {},
  88347. skins: {},
  88348. extensionsUsed: [],
  88349. scenes: {},
  88350. buffersCount: 0,
  88351. shaderscount: 0,
  88352. scene: scene,
  88353. rootUrl: rootUrl,
  88354. loadedBufferCount: 0,
  88355. loadedBufferViews: {},
  88356. loadedShaderCount: 0,
  88357. importOnlyMeshes: false,
  88358. dummyNodes: []
  88359. };
  88360. // Parse
  88361. if (parsedData.extensions) {
  88362. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  88363. }
  88364. if (parsedData.extensionsUsed) {
  88365. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  88366. }
  88367. if (parsedData.buffers) {
  88368. parseBuffers(parsedData.buffers, gltfRuntime);
  88369. }
  88370. if (parsedData.bufferViews) {
  88371. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  88372. }
  88373. if (parsedData.accessors) {
  88374. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  88375. }
  88376. if (parsedData.meshes) {
  88377. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  88378. }
  88379. if (parsedData.lights) {
  88380. parseObject(parsedData.lights, "lights", gltfRuntime);
  88381. }
  88382. if (parsedData.cameras) {
  88383. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  88384. }
  88385. if (parsedData.nodes) {
  88386. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  88387. }
  88388. if (parsedData.images) {
  88389. parseObject(parsedData.images, "images", gltfRuntime);
  88390. }
  88391. if (parsedData.textures) {
  88392. parseObject(parsedData.textures, "textures", gltfRuntime);
  88393. }
  88394. if (parsedData.shaders) {
  88395. parseShaders(parsedData.shaders, gltfRuntime);
  88396. }
  88397. if (parsedData.programs) {
  88398. parseObject(parsedData.programs, "programs", gltfRuntime);
  88399. }
  88400. if (parsedData.samplers) {
  88401. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  88402. }
  88403. if (parsedData.techniques) {
  88404. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  88405. }
  88406. if (parsedData.materials) {
  88407. parseObject(parsedData.materials, "materials", gltfRuntime);
  88408. }
  88409. if (parsedData.animations) {
  88410. parseObject(parsedData.animations, "animations", gltfRuntime);
  88411. }
  88412. if (parsedData.skins) {
  88413. parseObject(parsedData.skins, "skins", gltfRuntime);
  88414. }
  88415. if (parsedData.scenes) {
  88416. gltfRuntime.scenes = parsedData.scenes;
  88417. }
  88418. if (parsedData.scene && parsedData.scenes) {
  88419. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  88420. }
  88421. return gltfRuntime;
  88422. };
  88423. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  88424. var buffer = gltfRuntime.buffers[id];
  88425. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  88426. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  88427. }
  88428. else {
  88429. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  88430. if (request) {
  88431. onError(request.status + " " + request.statusText);
  88432. }
  88433. });
  88434. }
  88435. };
  88436. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  88437. var texture = gltfRuntime.textures[id];
  88438. if (!texture || !texture.source) {
  88439. onError("");
  88440. return;
  88441. }
  88442. if (texture.babylonTexture) {
  88443. onSuccess(null);
  88444. return;
  88445. }
  88446. var source = gltfRuntime.images[texture.source];
  88447. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  88448. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  88449. }
  88450. else {
  88451. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  88452. if (request) {
  88453. onError(request.status + " " + request.statusText);
  88454. }
  88455. });
  88456. }
  88457. };
  88458. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  88459. var texture = gltfRuntime.textures[id];
  88460. if (texture.babylonTexture) {
  88461. onSuccess(texture.babylonTexture);
  88462. return;
  88463. }
  88464. var sampler = gltfRuntime.samplers[texture.sampler];
  88465. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  88466. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  88467. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  88468. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  88469. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  88470. var blob = new Blob([buffer]);
  88471. var blobURL = URL.createObjectURL(blob);
  88472. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  88473. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  88474. if (sampler.wrapS !== undefined) {
  88475. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  88476. }
  88477. if (sampler.wrapT !== undefined) {
  88478. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  88479. }
  88480. newTexture.name = id;
  88481. texture.babylonTexture = newTexture;
  88482. onSuccess(newTexture);
  88483. };
  88484. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  88485. var shader = gltfRuntime.shaders[id];
  88486. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  88487. var shaderString = atob(shader.uri.split(",")[1]);
  88488. onSuccess(shaderString);
  88489. }
  88490. else {
  88491. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  88492. if (request) {
  88493. onError(request.status + " " + request.statusText);
  88494. }
  88495. });
  88496. }
  88497. };
  88498. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  88499. var material = gltfRuntime.materials[id];
  88500. if (!material.technique) {
  88501. if (onError) {
  88502. onError("No technique found.");
  88503. }
  88504. return;
  88505. }
  88506. var technique = gltfRuntime.techniques[material.technique];
  88507. if (!technique) {
  88508. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  88509. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  88510. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  88511. onSuccess(defaultMaterial);
  88512. return;
  88513. }
  88514. var program = gltfRuntime.programs[technique.program];
  88515. var states = technique.states;
  88516. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  88517. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  88518. var newVertexShader = "";
  88519. var newPixelShader = "";
  88520. var vertexTokenizer = new Tokenizer(vertexShader);
  88521. var pixelTokenizer = new Tokenizer(pixelShader);
  88522. var unTreatedUniforms = {};
  88523. var uniforms = [];
  88524. var attributes = [];
  88525. var samplers = [];
  88526. // Fill uniform, sampler2D and attributes
  88527. for (var unif in technique.uniforms) {
  88528. var uniform = technique.uniforms[unif];
  88529. var uniformParameter = technique.parameters[uniform];
  88530. unTreatedUniforms[unif] = uniformParameter;
  88531. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  88532. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  88533. if (transformIndex !== -1) {
  88534. uniforms.push(babylonTransforms[transformIndex]);
  88535. delete unTreatedUniforms[unif];
  88536. }
  88537. else {
  88538. uniforms.push(unif);
  88539. }
  88540. }
  88541. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  88542. samplers.push(unif);
  88543. }
  88544. else {
  88545. uniforms.push(unif);
  88546. }
  88547. }
  88548. for (var attr in technique.attributes) {
  88549. var attribute = technique.attributes[attr];
  88550. var attributeParameter = technique.parameters[attribute];
  88551. if (attributeParameter.semantic) {
  88552. attributes.push(getAttribute(attributeParameter));
  88553. }
  88554. }
  88555. // Configure vertex shader
  88556. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  88557. var tokenType = vertexTokenizer.currentToken;
  88558. if (tokenType !== ETokenType.IDENTIFIER) {
  88559. newVertexShader += vertexTokenizer.currentString;
  88560. continue;
  88561. }
  88562. var foundAttribute = false;
  88563. for (var attr in technique.attributes) {
  88564. var attribute = technique.attributes[attr];
  88565. var attributeParameter = technique.parameters[attribute];
  88566. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  88567. newVertexShader += getAttribute(attributeParameter);
  88568. foundAttribute = true;
  88569. break;
  88570. }
  88571. }
  88572. if (foundAttribute) {
  88573. continue;
  88574. }
  88575. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  88576. }
  88577. // Configure pixel shader
  88578. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  88579. var tokenType = pixelTokenizer.currentToken;
  88580. if (tokenType !== ETokenType.IDENTIFIER) {
  88581. newPixelShader += pixelTokenizer.currentString;
  88582. continue;
  88583. }
  88584. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  88585. }
  88586. // Create shader material
  88587. var shaderPath = {
  88588. vertex: program.vertexShader + id,
  88589. fragment: program.fragmentShader + id
  88590. };
  88591. var options = {
  88592. attributes: attributes,
  88593. uniforms: uniforms,
  88594. samplers: samplers,
  88595. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  88596. };
  88597. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  88598. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  88599. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  88600. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  88601. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  88602. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  88603. if (states && states.functions) {
  88604. var functions = states.functions;
  88605. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  88606. shaderMaterial.backFaceCulling = false;
  88607. }
  88608. var blendFunc = functions.blendFuncSeparate;
  88609. if (blendFunc) {
  88610. 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) {
  88611. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  88612. }
  88613. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  88614. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  88615. }
  88616. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  88617. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  88618. }
  88619. 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) {
  88620. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  88621. }
  88622. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  88623. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  88624. }
  88625. 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) {
  88626. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  88627. }
  88628. }
  88629. }
  88630. };
  88631. return GLTFLoaderBase;
  88632. }());
  88633. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  88634. /**
  88635. * glTF V1 Loader
  88636. */
  88637. var GLTFLoader = /** @class */ (function () {
  88638. function GLTFLoader() {
  88639. // #region Stubs for IGLTFLoader interface
  88640. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  88641. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  88642. this.compileMaterials = false;
  88643. this.useClipPlane = false;
  88644. this.compileShadowGenerators = false;
  88645. this.onDisposeObservable = new BABYLON.Observable();
  88646. this.onMeshLoadedObservable = new BABYLON.Observable();
  88647. this.onTextureLoadedObservable = new BABYLON.Observable();
  88648. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88649. this.onCompleteObservable = new BABYLON.Observable();
  88650. }
  88651. GLTFLoader.RegisterExtension = function (extension) {
  88652. if (GLTFLoader.Extensions[extension.name]) {
  88653. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  88654. return;
  88655. }
  88656. GLTFLoader.Extensions[extension.name] = extension;
  88657. };
  88658. GLTFLoader.prototype.dispose = function () { };
  88659. // #endregion
  88660. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  88661. var _this = this;
  88662. scene.useRightHandedSystem = true;
  88663. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  88664. gltfRuntime.importOnlyMeshes = true;
  88665. if (meshesNames === "") {
  88666. gltfRuntime.importMeshesNames = [];
  88667. }
  88668. else if (typeof meshesNames === "string") {
  88669. gltfRuntime.importMeshesNames = [meshesNames];
  88670. }
  88671. else if (meshesNames && !(meshesNames instanceof Array)) {
  88672. gltfRuntime.importMeshesNames = [meshesNames];
  88673. }
  88674. else {
  88675. gltfRuntime.importMeshesNames = [];
  88676. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  88677. }
  88678. // Create nodes
  88679. _this._createNodes(gltfRuntime);
  88680. var meshes = new Array();
  88681. var skeletons = new Array();
  88682. // Fill arrays of meshes and skeletons
  88683. for (var nde in gltfRuntime.nodes) {
  88684. var node = gltfRuntime.nodes[nde];
  88685. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  88686. meshes.push(node.babylonNode);
  88687. }
  88688. }
  88689. for (var skl in gltfRuntime.skins) {
  88690. var skin = gltfRuntime.skins[skl];
  88691. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  88692. skeletons.push(skin.babylonSkeleton);
  88693. }
  88694. }
  88695. // Load buffers, shaders, materials, etc.
  88696. _this._loadBuffersAsync(gltfRuntime, function () {
  88697. _this._loadShadersAsync(gltfRuntime, function () {
  88698. importMaterials(gltfRuntime);
  88699. postLoad(gltfRuntime);
  88700. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  88701. onSuccess(meshes, [], skeletons);
  88702. }
  88703. });
  88704. }, onProgress);
  88705. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  88706. onSuccess(meshes, [], skeletons);
  88707. }
  88708. }, onError);
  88709. return true;
  88710. };
  88711. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  88712. var _this = this;
  88713. scene.useRightHandedSystem = true;
  88714. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  88715. // Load runtime extensios
  88716. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  88717. // Create nodes
  88718. _this._createNodes(gltfRuntime);
  88719. // Load buffers, shaders, materials, etc.
  88720. _this._loadBuffersAsync(gltfRuntime, function () {
  88721. _this._loadShadersAsync(gltfRuntime, function () {
  88722. importMaterials(gltfRuntime);
  88723. postLoad(gltfRuntime);
  88724. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  88725. onSuccess();
  88726. }
  88727. });
  88728. });
  88729. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  88730. onSuccess();
  88731. }
  88732. }, onError);
  88733. }, onError);
  88734. };
  88735. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  88736. var hasShaders = false;
  88737. var processShader = function (sha, shader) {
  88738. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  88739. gltfRuntime.loadedShaderCount++;
  88740. if (shaderString) {
  88741. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  88742. }
  88743. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  88744. onload();
  88745. }
  88746. }, function () {
  88747. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  88748. });
  88749. };
  88750. for (var sha in gltfRuntime.shaders) {
  88751. hasShaders = true;
  88752. var shader = gltfRuntime.shaders[sha];
  88753. if (shader) {
  88754. processShader.bind(this, sha, shader)();
  88755. }
  88756. else {
  88757. BABYLON.Tools.Error("No shader named: " + sha);
  88758. }
  88759. }
  88760. if (!hasShaders) {
  88761. onload();
  88762. }
  88763. };
  88764. ;
  88765. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  88766. var hasBuffers = false;
  88767. var processBuffer = function (buf, buffer) {
  88768. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  88769. gltfRuntime.loadedBufferCount++;
  88770. if (bufferView) {
  88771. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  88772. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  88773. }
  88774. gltfRuntime.loadedBufferViews[buf] = bufferView;
  88775. }
  88776. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  88777. onLoad();
  88778. }
  88779. }, function () {
  88780. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  88781. });
  88782. };
  88783. for (var buf in gltfRuntime.buffers) {
  88784. hasBuffers = true;
  88785. var buffer = gltfRuntime.buffers[buf];
  88786. if (buffer) {
  88787. processBuffer.bind(this, buf, buffer)();
  88788. }
  88789. else {
  88790. BABYLON.Tools.Error("No buffer named: " + buf);
  88791. }
  88792. }
  88793. if (!hasBuffers) {
  88794. onLoad();
  88795. }
  88796. };
  88797. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  88798. var currentScene = gltfRuntime.currentScene;
  88799. if (currentScene) {
  88800. // Only one scene even if multiple scenes are defined
  88801. for (var i = 0; i < currentScene.nodes.length; i++) {
  88802. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  88803. }
  88804. }
  88805. else {
  88806. // Load all scenes
  88807. for (var thing in gltfRuntime.scenes) {
  88808. currentScene = gltfRuntime.scenes[thing];
  88809. for (var i = 0; i < currentScene.nodes.length; i++) {
  88810. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  88811. }
  88812. }
  88813. }
  88814. };
  88815. GLTFLoader.Extensions = {};
  88816. return GLTFLoader;
  88817. }());
  88818. GLTF1.GLTFLoader = GLTFLoader;
  88819. ;
  88820. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  88821. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88822. })(BABYLON || (BABYLON = {}));
  88823. //# sourceMappingURL=babylon.glTFLoader.js.map
  88824. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88825. var BABYLON;
  88826. (function (BABYLON) {
  88827. var GLTF1;
  88828. (function (GLTF1) {
  88829. /**
  88830. * Utils functions for GLTF
  88831. */
  88832. var GLTFUtils = /** @class */ (function () {
  88833. function GLTFUtils() {
  88834. }
  88835. /**
  88836. * Sets the given "parameter" matrix
  88837. * @param scene: the {BABYLON.Scene} object
  88838. * @param source: the source node where to pick the matrix
  88839. * @param parameter: the GLTF technique parameter
  88840. * @param uniformName: the name of the shader's uniform
  88841. * @param shaderMaterial: the shader material
  88842. */
  88843. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  88844. var mat = null;
  88845. if (parameter.semantic === "MODEL") {
  88846. mat = source.getWorldMatrix();
  88847. }
  88848. else if (parameter.semantic === "PROJECTION") {
  88849. mat = scene.getProjectionMatrix();
  88850. }
  88851. else if (parameter.semantic === "VIEW") {
  88852. mat = scene.getViewMatrix();
  88853. }
  88854. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  88855. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  88856. }
  88857. else if (parameter.semantic === "MODELVIEW") {
  88858. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  88859. }
  88860. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  88861. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  88862. }
  88863. else if (parameter.semantic === "MODELINVERSE") {
  88864. mat = source.getWorldMatrix().invert();
  88865. }
  88866. else if (parameter.semantic === "VIEWINVERSE") {
  88867. mat = scene.getViewMatrix().invert();
  88868. }
  88869. else if (parameter.semantic === "PROJECTIONINVERSE") {
  88870. mat = scene.getProjectionMatrix().invert();
  88871. }
  88872. else if (parameter.semantic === "MODELVIEWINVERSE") {
  88873. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  88874. }
  88875. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  88876. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  88877. }
  88878. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  88879. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  88880. }
  88881. else {
  88882. debugger;
  88883. }
  88884. if (mat) {
  88885. switch (parameter.type) {
  88886. case GLTF1.EParameterType.FLOAT_MAT2:
  88887. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  88888. break;
  88889. case GLTF1.EParameterType.FLOAT_MAT3:
  88890. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  88891. break;
  88892. case GLTF1.EParameterType.FLOAT_MAT4:
  88893. shaderMaterial.setMatrix(uniformName, mat);
  88894. break;
  88895. default: break;
  88896. }
  88897. }
  88898. };
  88899. /**
  88900. * Sets the given "parameter" matrix
  88901. * @param shaderMaterial: the shader material
  88902. * @param uniform: the name of the shader's uniform
  88903. * @param value: the value of the uniform
  88904. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  88905. */
  88906. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  88907. switch (type) {
  88908. case GLTF1.EParameterType.FLOAT:
  88909. shaderMaterial.setFloat(uniform, value);
  88910. return true;
  88911. case GLTF1.EParameterType.FLOAT_VEC2:
  88912. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  88913. return true;
  88914. case GLTF1.EParameterType.FLOAT_VEC3:
  88915. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  88916. return true;
  88917. case GLTF1.EParameterType.FLOAT_VEC4:
  88918. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  88919. return true;
  88920. default: return false;
  88921. }
  88922. };
  88923. /**
  88924. * If the uri is a base64 string
  88925. * @param uri: the uri to test
  88926. */
  88927. GLTFUtils.IsBase64 = function (uri) {
  88928. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  88929. };
  88930. /**
  88931. * Decode the base64 uri
  88932. * @param uri: the uri to decode
  88933. */
  88934. GLTFUtils.DecodeBase64 = function (uri) {
  88935. var decodedString = atob(uri.split(",")[1]);
  88936. var bufferLength = decodedString.length;
  88937. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  88938. for (var i = 0; i < bufferLength; i++) {
  88939. bufferView[i] = decodedString.charCodeAt(i);
  88940. }
  88941. return bufferView.buffer;
  88942. };
  88943. /**
  88944. * Returns the wrap mode of the texture
  88945. * @param mode: the mode value
  88946. */
  88947. GLTFUtils.GetWrapMode = function (mode) {
  88948. switch (mode) {
  88949. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  88950. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  88951. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  88952. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  88953. }
  88954. };
  88955. /**
  88956. * Returns the byte stride giving an accessor
  88957. * @param accessor: the GLTF accessor objet
  88958. */
  88959. GLTFUtils.GetByteStrideFromType = function (accessor) {
  88960. // Needs this function since "byteStride" isn't requiered in glTF format
  88961. var type = accessor.type;
  88962. switch (type) {
  88963. case "VEC2": return 2;
  88964. case "VEC3": return 3;
  88965. case "VEC4": return 4;
  88966. case "MAT2": return 4;
  88967. case "MAT3": return 9;
  88968. case "MAT4": return 16;
  88969. default: return 1;
  88970. }
  88971. };
  88972. /**
  88973. * Returns the texture filter mode giving a mode value
  88974. * @param mode: the filter mode value
  88975. */
  88976. GLTFUtils.GetTextureFilterMode = function (mode) {
  88977. switch (mode) {
  88978. case GLTF1.ETextureFilterType.LINEAR:
  88979. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  88980. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88981. case GLTF1.ETextureFilterType.NEAREST:
  88982. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  88983. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  88984. }
  88985. };
  88986. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  88987. var byteOffset = bufferView.byteOffset + byteOffset;
  88988. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  88989. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  88990. throw new Error("Buffer access is out of range");
  88991. }
  88992. var buffer = loadedBufferView.buffer;
  88993. byteOffset += loadedBufferView.byteOffset;
  88994. switch (componentType) {
  88995. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  88996. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  88997. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  88998. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  88999. default: return new Float32Array(buffer, byteOffset, byteLength);
  89000. }
  89001. };
  89002. /**
  89003. * Returns a buffer from its accessor
  89004. * @param gltfRuntime: the GLTF runtime
  89005. * @param accessor: the GLTF accessor
  89006. */
  89007. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  89008. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  89009. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  89010. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  89011. };
  89012. /**
  89013. * Decodes a buffer view into a string
  89014. * @param view: the buffer view
  89015. */
  89016. GLTFUtils.DecodeBufferToText = function (view) {
  89017. var result = "";
  89018. var length = view.byteLength;
  89019. for (var i = 0; i < length; ++i) {
  89020. result += String.fromCharCode(view[i]);
  89021. }
  89022. return result;
  89023. };
  89024. /**
  89025. * Returns the default material of gltf. Related to
  89026. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  89027. * @param scene: the Babylon.js scene
  89028. */
  89029. GLTFUtils.GetDefaultMaterial = function (scene) {
  89030. if (!GLTFUtils._DefaultMaterial) {
  89031. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  89032. "precision highp float;",
  89033. "",
  89034. "uniform mat4 worldView;",
  89035. "uniform mat4 projection;",
  89036. "",
  89037. "attribute vec3 position;",
  89038. "",
  89039. "void main(void)",
  89040. "{",
  89041. " gl_Position = projection * worldView * vec4(position, 1.0);",
  89042. "}"
  89043. ].join("\n");
  89044. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  89045. "precision highp float;",
  89046. "",
  89047. "uniform vec4 u_emission;",
  89048. "",
  89049. "void main(void)",
  89050. "{",
  89051. " gl_FragColor = u_emission;",
  89052. "}"
  89053. ].join("\n");
  89054. var shaderPath = {
  89055. vertex: "GLTFDefaultMaterial",
  89056. fragment: "GLTFDefaultMaterial"
  89057. };
  89058. var options = {
  89059. attributes: ["position"],
  89060. uniforms: ["worldView", "projection", "u_emission"],
  89061. samplers: new Array(),
  89062. needAlphaBlending: false
  89063. };
  89064. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  89065. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  89066. }
  89067. return GLTFUtils._DefaultMaterial;
  89068. };
  89069. // The GLTF default material
  89070. GLTFUtils._DefaultMaterial = null;
  89071. return GLTFUtils;
  89072. }());
  89073. GLTF1.GLTFUtils = GLTFUtils;
  89074. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89075. })(BABYLON || (BABYLON = {}));
  89076. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  89077. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89078. var BABYLON;
  89079. (function (BABYLON) {
  89080. var GLTF1;
  89081. (function (GLTF1) {
  89082. var GLTFLoaderExtension = /** @class */ (function () {
  89083. function GLTFLoaderExtension(name) {
  89084. this._name = name;
  89085. }
  89086. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  89087. get: function () {
  89088. return this._name;
  89089. },
  89090. enumerable: true,
  89091. configurable: true
  89092. });
  89093. /**
  89094. * Defines an override for loading the runtime
  89095. * Return true to stop further extensions from loading the runtime
  89096. */
  89097. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  89098. return false;
  89099. };
  89100. /**
  89101. * Defines an onverride for creating gltf runtime
  89102. * Return true to stop further extensions from creating the runtime
  89103. */
  89104. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  89105. return false;
  89106. };
  89107. /**
  89108. * Defines an override for loading buffers
  89109. * Return true to stop further extensions from loading this buffer
  89110. */
  89111. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89112. return false;
  89113. };
  89114. /**
  89115. * Defines an override for loading texture buffers
  89116. * Return true to stop further extensions from loading this texture data
  89117. */
  89118. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89119. return false;
  89120. };
  89121. /**
  89122. * Defines an override for creating textures
  89123. * Return true to stop further extensions from loading this texture
  89124. */
  89125. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89126. return false;
  89127. };
  89128. /**
  89129. * Defines an override for loading shader strings
  89130. * Return true to stop further extensions from loading this shader data
  89131. */
  89132. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89133. return false;
  89134. };
  89135. /**
  89136. * Defines an override for loading materials
  89137. * Return true to stop further extensions from loading this material
  89138. */
  89139. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89140. return false;
  89141. };
  89142. // ---------
  89143. // Utilities
  89144. // ---------
  89145. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  89146. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89147. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  89148. }, function () {
  89149. setTimeout(function () {
  89150. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  89151. });
  89152. });
  89153. };
  89154. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  89155. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89156. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  89157. }, function () {
  89158. setTimeout(function () {
  89159. onSuccess();
  89160. });
  89161. });
  89162. };
  89163. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89164. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89165. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  89166. }, function () {
  89167. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  89168. });
  89169. };
  89170. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  89171. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  89172. };
  89173. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89174. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89175. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  89176. }, function () {
  89177. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  89178. });
  89179. };
  89180. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89181. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89182. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  89183. }, function () {
  89184. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  89185. });
  89186. };
  89187. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89188. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89189. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  89190. }, function () {
  89191. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  89192. });
  89193. };
  89194. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89195. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89196. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  89197. }, function () {
  89198. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  89199. });
  89200. };
  89201. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  89202. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  89203. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  89204. if (func(loaderExtension)) {
  89205. return;
  89206. }
  89207. }
  89208. defaultFunc();
  89209. };
  89210. return GLTFLoaderExtension;
  89211. }());
  89212. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  89213. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89214. })(BABYLON || (BABYLON = {}));
  89215. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  89216. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89217. var BABYLON;
  89218. (function (BABYLON) {
  89219. var GLTF1;
  89220. (function (GLTF1) {
  89221. var BinaryExtensionBufferName = "binary_glTF";
  89222. ;
  89223. ;
  89224. var GLTFBinaryExtension = /** @class */ (function (_super) {
  89225. __extends(GLTFBinaryExtension, _super);
  89226. function GLTFBinaryExtension() {
  89227. return _super.call(this, "KHR_binary_glTF") || this;
  89228. }
  89229. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  89230. var extensionsUsed = data.json.extensionsUsed;
  89231. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  89232. return false;
  89233. }
  89234. this._bin = data.bin;
  89235. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  89236. return true;
  89237. };
  89238. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89239. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  89240. return false;
  89241. }
  89242. if (id !== BinaryExtensionBufferName) {
  89243. return false;
  89244. }
  89245. onSuccess(this._bin);
  89246. return true;
  89247. };
  89248. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89249. var texture = gltfRuntime.textures[id];
  89250. var source = gltfRuntime.images[texture.source];
  89251. if (!source.extensions || !(this.name in source.extensions)) {
  89252. return false;
  89253. }
  89254. var sourceExt = source.extensions[this.name];
  89255. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  89256. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  89257. onSuccess(buffer);
  89258. return true;
  89259. };
  89260. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89261. var shader = gltfRuntime.shaders[id];
  89262. if (!shader.extensions || !(this.name in shader.extensions)) {
  89263. return false;
  89264. }
  89265. var binaryExtensionShader = shader.extensions[this.name];
  89266. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  89267. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  89268. setTimeout(function () {
  89269. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  89270. onSuccess(shaderString);
  89271. });
  89272. return true;
  89273. };
  89274. return GLTFBinaryExtension;
  89275. }(GLTF1.GLTFLoaderExtension));
  89276. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  89277. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  89278. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89279. })(BABYLON || (BABYLON = {}));
  89280. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  89281. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89282. var BABYLON;
  89283. (function (BABYLON) {
  89284. var GLTF1;
  89285. (function (GLTF1) {
  89286. ;
  89287. ;
  89288. ;
  89289. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  89290. __extends(GLTFMaterialsCommonExtension, _super);
  89291. function GLTFMaterialsCommonExtension() {
  89292. return _super.call(this, "KHR_materials_common") || this;
  89293. }
  89294. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  89295. if (!gltfRuntime.extensions)
  89296. return false;
  89297. var extension = gltfRuntime.extensions[this.name];
  89298. if (!extension)
  89299. return false;
  89300. // Create lights
  89301. var lights = extension.lights;
  89302. if (lights) {
  89303. for (var thing in lights) {
  89304. var light = lights[thing];
  89305. switch (light.type) {
  89306. case "ambient":
  89307. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  89308. var ambient = light.ambient;
  89309. if (ambient) {
  89310. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  89311. }
  89312. break;
  89313. case "point":
  89314. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  89315. var point = light.point;
  89316. if (point) {
  89317. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  89318. }
  89319. break;
  89320. case "directional":
  89321. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  89322. var directional = light.directional;
  89323. if (directional) {
  89324. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  89325. }
  89326. break;
  89327. case "spot":
  89328. var spot = light.spot;
  89329. if (spot) {
  89330. 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);
  89331. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  89332. }
  89333. break;
  89334. default:
  89335. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  89336. break;
  89337. }
  89338. }
  89339. }
  89340. return false;
  89341. };
  89342. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89343. var material = gltfRuntime.materials[id];
  89344. if (!material || !material.extensions)
  89345. return false;
  89346. var extension = material.extensions[this.name];
  89347. if (!extension)
  89348. return false;
  89349. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  89350. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89351. if (extension.technique === "CONSTANT") {
  89352. standardMaterial.disableLighting = true;
  89353. }
  89354. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  89355. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  89356. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  89357. // Ambient
  89358. if (typeof extension.values.ambient === "string") {
  89359. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  89360. }
  89361. else {
  89362. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  89363. }
  89364. // Diffuse
  89365. if (typeof extension.values.diffuse === "string") {
  89366. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  89367. }
  89368. else {
  89369. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  89370. }
  89371. // Emission
  89372. if (typeof extension.values.emission === "string") {
  89373. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  89374. }
  89375. else {
  89376. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  89377. }
  89378. // Specular
  89379. if (typeof extension.values.specular === "string") {
  89380. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  89381. }
  89382. else {
  89383. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  89384. }
  89385. return true;
  89386. };
  89387. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  89388. // Create buffer from texture url
  89389. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  89390. // Create texture from buffer
  89391. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  89392. }, onError);
  89393. };
  89394. return GLTFMaterialsCommonExtension;
  89395. }(GLTF1.GLTFLoaderExtension));
  89396. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  89397. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  89398. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89399. })(BABYLON || (BABYLON = {}));
  89400. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  89401. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89402. var BABYLON;
  89403. (function (BABYLON) {
  89404. var GLTF2;
  89405. (function (GLTF2) {
  89406. /**
  89407. * Enums
  89408. */
  89409. var EComponentType;
  89410. (function (EComponentType) {
  89411. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  89412. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89413. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  89414. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89415. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  89416. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  89417. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  89418. var EMeshPrimitiveMode;
  89419. (function (EMeshPrimitiveMode) {
  89420. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  89421. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  89422. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  89423. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  89424. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  89425. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  89426. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  89427. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  89428. var ETextureMagFilter;
  89429. (function (ETextureMagFilter) {
  89430. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  89431. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  89432. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  89433. var ETextureMinFilter;
  89434. (function (ETextureMinFilter) {
  89435. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  89436. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  89437. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  89438. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  89439. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  89440. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  89441. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  89442. var ETextureWrapMode;
  89443. (function (ETextureWrapMode) {
  89444. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  89445. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  89446. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  89447. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  89448. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89449. })(BABYLON || (BABYLON = {}));
  89450. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  89451. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89452. var BABYLON;
  89453. (function (BABYLON) {
  89454. var GLTF2;
  89455. (function (GLTF2) {
  89456. var GLTFLoaderTracker = /** @class */ (function () {
  89457. function GLTFLoaderTracker(onComplete) {
  89458. this._pendingCount = 0;
  89459. this._callback = onComplete;
  89460. }
  89461. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  89462. this._pendingCount++;
  89463. };
  89464. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  89465. if (--this._pendingCount === 0) {
  89466. this._callback();
  89467. }
  89468. };
  89469. return GLTFLoaderTracker;
  89470. }());
  89471. var GLTFLoader = /** @class */ (function () {
  89472. function GLTFLoader() {
  89473. this._disposed = false;
  89474. this._defaultSampler = {};
  89475. this._renderReady = false;
  89476. this._requests = new Array();
  89477. this._renderReadyObservable = new BABYLON.Observable();
  89478. // Count of pending work that needs to complete before the asset is rendered.
  89479. this._renderPendingCount = 0;
  89480. // Count of pending work that needs to complete before the loader is disposed.
  89481. this._loaderPendingCount = 0;
  89482. this._loaderTrackers = new Array();
  89483. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  89484. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  89485. this.compileMaterials = false;
  89486. this.useClipPlane = false;
  89487. this.compileShadowGenerators = false;
  89488. this.onDisposeObservable = new BABYLON.Observable();
  89489. this.onMeshLoadedObservable = new BABYLON.Observable();
  89490. this.onTextureLoadedObservable = new BABYLON.Observable();
  89491. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89492. this.onCompleteObservable = new BABYLON.Observable();
  89493. }
  89494. GLTFLoader.RegisterExtension = function (extension) {
  89495. if (GLTFLoader.Extensions[extension.name]) {
  89496. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  89497. return;
  89498. }
  89499. GLTFLoader.Extensions[extension.name] = extension;
  89500. // Keep the order of registration so that extensions registered first are called first.
  89501. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  89502. };
  89503. GLTFLoader.prototype.dispose = function () {
  89504. if (this._disposed) {
  89505. return;
  89506. }
  89507. this._disposed = true;
  89508. this._abortRequests();
  89509. this._releaseResources();
  89510. this.onDisposeObservable.notifyObservers(this);
  89511. };
  89512. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89513. var _this = this;
  89514. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  89515. if (onSuccess) {
  89516. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  89517. }
  89518. }, onProgress, onError);
  89519. };
  89520. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  89521. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  89522. };
  89523. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89524. var _this = this;
  89525. this._babylonScene = scene;
  89526. this._rootUrl = rootUrl;
  89527. this._successCallback = onSuccess;
  89528. this._progressCallback = onProgress;
  89529. this._errorCallback = onError;
  89530. this._tryCatchOnError(function () {
  89531. _this._loadData(data);
  89532. _this._addPendingData(_this);
  89533. _this._loadDefaultScene(nodeNames);
  89534. _this._loadAnimations();
  89535. _this._removePendingData(_this);
  89536. });
  89537. };
  89538. GLTFLoader.prototype._onProgress = function () {
  89539. if (!this._progressCallback) {
  89540. return;
  89541. }
  89542. var lengthComputable = true;
  89543. var loaded = 0;
  89544. var total = 0;
  89545. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  89546. var request = _a[_i];
  89547. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  89548. return;
  89549. }
  89550. lengthComputable = lengthComputable && request._lengthComputable;
  89551. loaded += request._loaded;
  89552. total += request._total;
  89553. }
  89554. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  89555. };
  89556. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  89557. if (this._renderReady) {
  89558. func();
  89559. }
  89560. else {
  89561. this._renderReadyObservable.add(func);
  89562. }
  89563. };
  89564. GLTFLoader.prototype._onRenderReady = function () {
  89565. this._rootNode.babylonMesh.setEnabled(true);
  89566. this._startAnimations();
  89567. if (this._successCallback) {
  89568. this._successCallback();
  89569. }
  89570. this._renderReadyObservable.notifyObservers(this);
  89571. };
  89572. GLTFLoader.prototype._onComplete = function () {
  89573. this._abortRequests();
  89574. this._releaseResources();
  89575. this.onCompleteObservable.notifyObservers(this);
  89576. };
  89577. GLTFLoader.prototype._loadData = function (data) {
  89578. this._gltf = data.json;
  89579. // Assign the index of each object for convinience.
  89580. GLTFLoader._AssignIndices(this._gltf.accessors);
  89581. GLTFLoader._AssignIndices(this._gltf.animations);
  89582. GLTFLoader._AssignIndices(this._gltf.buffers);
  89583. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  89584. GLTFLoader._AssignIndices(this._gltf.images);
  89585. GLTFLoader._AssignIndices(this._gltf.materials);
  89586. GLTFLoader._AssignIndices(this._gltf.meshes);
  89587. GLTFLoader._AssignIndices(this._gltf.nodes);
  89588. GLTFLoader._AssignIndices(this._gltf.samplers);
  89589. GLTFLoader._AssignIndices(this._gltf.scenes);
  89590. GLTFLoader._AssignIndices(this._gltf.skins);
  89591. GLTFLoader._AssignIndices(this._gltf.textures);
  89592. // Handle global extensions as they may add their own data types.
  89593. GLTF2.GLTFLoaderExtension.LoadRoot(this, "#/", this._gltf);
  89594. if (data.bin) {
  89595. var buffers = this._gltf.buffers;
  89596. if (buffers && buffers[0] && !buffers[0].uri) {
  89597. var binaryBuffer = buffers[0];
  89598. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  89599. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  89600. }
  89601. binaryBuffer.loadedData = data.bin;
  89602. }
  89603. else {
  89604. BABYLON.Tools.Warn("Unexpected BIN chunk");
  89605. }
  89606. }
  89607. };
  89608. GLTFLoader.prototype._getMeshes = function () {
  89609. var meshes = new Array();
  89610. // Root mesh is always first.
  89611. meshes.push(this._rootNode.babylonMesh);
  89612. var nodes = this._gltf.nodes;
  89613. if (nodes) {
  89614. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  89615. var node = nodes_1[_i];
  89616. if (node.babylonMesh) {
  89617. meshes.push(node.babylonMesh);
  89618. }
  89619. }
  89620. }
  89621. return meshes;
  89622. };
  89623. GLTFLoader.prototype._getSkeletons = function () {
  89624. var skeletons = new Array();
  89625. var skins = this._gltf.skins;
  89626. if (skins) {
  89627. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  89628. var skin = skins_1[_i];
  89629. if (skin.babylonSkeleton) {
  89630. skeletons.push(skin.babylonSkeleton);
  89631. }
  89632. }
  89633. }
  89634. return skeletons;
  89635. };
  89636. GLTFLoader.prototype._startAnimations = function () {
  89637. var animations = this._gltf.animations;
  89638. if (!animations) {
  89639. return;
  89640. }
  89641. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  89642. var animation = animations_1[_i];
  89643. animation.babylonAnimationGroup.normalize();
  89644. }
  89645. switch (this.animationStartMode) {
  89646. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  89647. // do nothing
  89648. break;
  89649. }
  89650. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  89651. var animation = animations[0];
  89652. animation.babylonAnimationGroup.start(true);
  89653. break;
  89654. }
  89655. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  89656. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  89657. var animation = animations_2[_a];
  89658. animation.babylonAnimationGroup.start(true);
  89659. }
  89660. break;
  89661. }
  89662. default: {
  89663. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  89664. return;
  89665. }
  89666. }
  89667. };
  89668. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  89669. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  89670. if (!scene) {
  89671. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  89672. }
  89673. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  89674. };
  89675. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  89676. var _this = this;
  89677. GLTF2.GLTFLoaderExtension.LoadScene(this, context, scene);
  89678. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  89679. switch (this.coordinateSystemMode) {
  89680. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  89681. if (!this._babylonScene.useRightHandedSystem) {
  89682. this._rootNode.rotation = [0, 1, 0, 0];
  89683. this._rootNode.scale = [1, 1, -1];
  89684. this._loadTransform(this._rootNode);
  89685. }
  89686. break;
  89687. }
  89688. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  89689. this._babylonScene.useRightHandedSystem = true;
  89690. break;
  89691. }
  89692. default: {
  89693. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  89694. return;
  89695. }
  89696. }
  89697. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  89698. var nodeIndices = scene.nodes;
  89699. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  89700. node.parent = parentNode;
  89701. return true;
  89702. }, this._rootNode);
  89703. if (nodeNames) {
  89704. if (!(nodeNames instanceof Array)) {
  89705. nodeNames = [nodeNames];
  89706. }
  89707. var filteredNodeIndices_1 = new Array();
  89708. this._traverseNodes(context, nodeIndices, function (node) {
  89709. if (nodeNames.indexOf(node.name) !== -1) {
  89710. filteredNodeIndices_1.push(node.index);
  89711. node.parent = _this._rootNode;
  89712. return false;
  89713. }
  89714. return true;
  89715. }, this._rootNode);
  89716. nodeIndices = filteredNodeIndices_1;
  89717. }
  89718. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  89719. var index = nodeIndices_1[_i];
  89720. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  89721. if (!node) {
  89722. throw new Error(context + ": Failed to find node " + index);
  89723. }
  89724. this._loadNode("#/nodes/" + index, node);
  89725. }
  89726. // Disable the root mesh until the asset is ready to render.
  89727. this._rootNode.babylonMesh.setEnabled(false);
  89728. };
  89729. GLTFLoader.prototype._loadNode = function (context, node) {
  89730. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  89731. return;
  89732. }
  89733. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  89734. this._loadTransform(node);
  89735. if (node.mesh != null) {
  89736. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  89737. if (!mesh) {
  89738. throw new Error(context + ": Failed to find mesh " + node.mesh);
  89739. }
  89740. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  89741. }
  89742. node.babylonMesh.parent = node.parent.babylonMesh;
  89743. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  89744. node.babylonAnimationTargets.push(node.babylonMesh);
  89745. if (node.skin != null) {
  89746. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  89747. if (!skin_1) {
  89748. throw new Error(context + ": Failed to find skin " + node.skin);
  89749. }
  89750. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  89751. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  89752. node.babylonMesh._refreshBoundingInfo(true);
  89753. });
  89754. node.babylonMesh.parent = this._rootNode.babylonMesh;
  89755. node.babylonMesh.position = BABYLON.Vector3.Zero();
  89756. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  89757. node.babylonMesh.scaling = BABYLON.Vector3.One();
  89758. }
  89759. if (node.camera != null) {
  89760. // TODO: handle cameras
  89761. }
  89762. if (node.children) {
  89763. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  89764. var index = _a[_i];
  89765. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  89766. if (!childNode) {
  89767. throw new Error(context + ": Failed to find child node " + index);
  89768. }
  89769. this._loadNode("#/nodes/" + index, childNode);
  89770. }
  89771. }
  89772. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  89773. };
  89774. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  89775. var _this = this;
  89776. var primitives = mesh.primitives;
  89777. if (!primitives || primitives.length === 0) {
  89778. throw new Error(context + ": Primitives are missing");
  89779. }
  89780. this._createMorphTargets(context, node, mesh);
  89781. this._loadAllVertexDataAsync(context, mesh, function () {
  89782. _this._loadMorphTargets(context, node, mesh);
  89783. var vertexData = new BABYLON.VertexData();
  89784. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  89785. var primitive = primitives_1[_i];
  89786. vertexData.merge(primitive.vertexData);
  89787. }
  89788. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  89789. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  89790. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  89791. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  89792. node.babylonMesh.subMeshes = [];
  89793. var verticesStart = 0;
  89794. var indicesStart = 0;
  89795. for (var index = 0; index < primitives.length; index++) {
  89796. var vertexData_1 = primitives[index].vertexData;
  89797. var verticesCount = vertexData_1.positions.length;
  89798. var indicesCount = vertexData_1.indices.length;
  89799. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  89800. verticesStart += verticesCount;
  89801. indicesStart += indicesCount;
  89802. }
  89803. ;
  89804. });
  89805. if (primitives.length === 1) {
  89806. var primitive = primitives[0];
  89807. if (primitive.material == null) {
  89808. node.babylonMesh.material = this._getDefaultMaterial();
  89809. }
  89810. else {
  89811. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  89812. if (!material) {
  89813. throw new Error(context + ": Failed to find material " + primitive.material);
  89814. }
  89815. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  89816. if (isNew) {
  89817. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  89818. }
  89819. node.babylonMesh.material = babylonMaterial;
  89820. });
  89821. }
  89822. }
  89823. else {
  89824. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  89825. node.babylonMesh.material = multiMaterial;
  89826. var subMaterials_1 = multiMaterial.subMaterials;
  89827. var _loop_1 = function (index) {
  89828. var primitive = primitives[index];
  89829. if (primitive.material == null) {
  89830. subMaterials_1[index] = this_1._getDefaultMaterial();
  89831. }
  89832. else {
  89833. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  89834. if (!material) {
  89835. throw new Error(context + ": Failed to find material " + primitive.material);
  89836. }
  89837. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  89838. if (isNew) {
  89839. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  89840. }
  89841. subMaterials_1[index] = babylonMaterial;
  89842. });
  89843. }
  89844. };
  89845. var this_1 = this;
  89846. for (var index = 0; index < primitives.length; index++) {
  89847. _loop_1(index);
  89848. }
  89849. ;
  89850. }
  89851. };
  89852. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  89853. var primitives = mesh.primitives;
  89854. var numRemainingPrimitives = primitives.length;
  89855. var _loop_2 = function (index) {
  89856. var primitive = primitives[index];
  89857. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  89858. primitive.vertexData = vertexData;
  89859. if (--numRemainingPrimitives === 0) {
  89860. onSuccess();
  89861. }
  89862. });
  89863. };
  89864. var this_2 = this;
  89865. for (var index = 0; index < primitives.length; index++) {
  89866. _loop_2(index);
  89867. }
  89868. };
  89869. /**
  89870. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  89871. * @param {ArrayBufferView} data
  89872. * @param {IGLTFAccessor} accessor
  89873. */
  89874. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  89875. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  89876. return data;
  89877. }
  89878. var buffer = data;
  89879. var factor = 1;
  89880. switch (accessor.componentType) {
  89881. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  89882. factor = 1 / 255;
  89883. break;
  89884. }
  89885. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  89886. factor = 1 / 65535;
  89887. break;
  89888. }
  89889. default: {
  89890. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  89891. }
  89892. }
  89893. var result = new Float32Array(accessor.count * 2);
  89894. for (var i = 0; i < result.length; ++i) {
  89895. result[i] = buffer[i] * factor;
  89896. }
  89897. return result;
  89898. };
  89899. /**
  89900. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  89901. * @param {ArrayBufferView} data
  89902. * @param {IGLTFAccessor} accessor
  89903. */
  89904. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  89905. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  89906. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  89907. return data;
  89908. }
  89909. var buffer = data;
  89910. var factor = 1;
  89911. switch (accessor.componentType) {
  89912. case GLTF2.EComponentType.FLOAT: {
  89913. factor = 1;
  89914. break;
  89915. }
  89916. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  89917. factor = 1 / 255;
  89918. break;
  89919. }
  89920. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  89921. factor = 1 / 65535;
  89922. break;
  89923. }
  89924. default: {
  89925. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  89926. }
  89927. }
  89928. var result = new Float32Array(accessor.count * 4);
  89929. if (colorComponentCount === 4) {
  89930. for (var i = 0; i < result.length; ++i) {
  89931. result[i] = buffer[i] * factor;
  89932. }
  89933. }
  89934. else {
  89935. var offset = 0;
  89936. for (var i = 0; i < result.length; ++i) {
  89937. if ((i + 1) % 4 === 0) {
  89938. result[i] = 1;
  89939. }
  89940. else {
  89941. result[i] = buffer[offset++] * factor;
  89942. }
  89943. }
  89944. }
  89945. return result;
  89946. };
  89947. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  89948. var _this = this;
  89949. var attributes = primitive.attributes;
  89950. if (!attributes) {
  89951. throw new Error(context + ": Attributes are missing");
  89952. }
  89953. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  89954. // TODO: handle other primitive modes
  89955. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  89956. }
  89957. var vertexData = new BABYLON.VertexData();
  89958. var numRemainingAttributes = Object.keys(attributes).length;
  89959. var _loop_3 = function (attribute) {
  89960. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  89961. if (!accessor) {
  89962. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  89963. }
  89964. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  89965. switch (attribute) {
  89966. case "POSITION": {
  89967. vertexData.positions = data;
  89968. break;
  89969. }
  89970. case "NORMAL": {
  89971. vertexData.normals = data;
  89972. break;
  89973. }
  89974. case "TANGENT": {
  89975. vertexData.tangents = data;
  89976. break;
  89977. }
  89978. case "TEXCOORD_0": {
  89979. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  89980. break;
  89981. }
  89982. case "TEXCOORD_1": {
  89983. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  89984. break;
  89985. }
  89986. case "JOINTS_0": {
  89987. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  89988. break;
  89989. }
  89990. case "WEIGHTS_0": {
  89991. //TODO: need to add support for normalized weights.
  89992. vertexData.matricesWeights = data;
  89993. break;
  89994. }
  89995. case "COLOR_0": {
  89996. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  89997. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  89998. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  89999. mesh.hasVertexAlpha = hasVertexAlpha;
  90000. }
  90001. break;
  90002. }
  90003. default: {
  90004. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  90005. break;
  90006. }
  90007. }
  90008. if (--numRemainingAttributes === 0) {
  90009. if (primitive.indices == null) {
  90010. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  90011. for (var i = 0; i < vertexData.indices.length; i++) {
  90012. vertexData.indices[i] = i;
  90013. }
  90014. onSuccess(vertexData);
  90015. }
  90016. else {
  90017. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  90018. if (!indicesAccessor) {
  90019. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  90020. }
  90021. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  90022. vertexData.indices = data;
  90023. onSuccess(vertexData);
  90024. });
  90025. }
  90026. }
  90027. });
  90028. };
  90029. var this_3 = this;
  90030. for (var attribute in attributes) {
  90031. _loop_3(attribute);
  90032. }
  90033. };
  90034. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  90035. var primitives = mesh.primitives;
  90036. var targets = primitives[0].targets;
  90037. if (!targets) {
  90038. return;
  90039. }
  90040. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  90041. var primitive = primitives_2[_i];
  90042. if (!primitive.targets || primitive.targets.length != targets.length) {
  90043. throw new Error(context + ": All primitives are required to list the same number of targets");
  90044. }
  90045. }
  90046. var morphTargetManager = new BABYLON.MorphTargetManager();
  90047. node.babylonMesh.morphTargetManager = morphTargetManager;
  90048. for (var index = 0; index < targets.length; index++) {
  90049. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  90050. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  90051. }
  90052. };
  90053. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  90054. var morphTargetManager = node.babylonMesh.morphTargetManager;
  90055. if (!morphTargetManager) {
  90056. return;
  90057. }
  90058. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  90059. var numTargets = morphTargetManager.numTargets;
  90060. for (var index = 0; index < numTargets; index++) {
  90061. var vertexData = new BABYLON.VertexData();
  90062. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  90063. var primitive = _a[_i];
  90064. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  90065. }
  90066. if (!vertexData.positions) {
  90067. throw new Error(context + ": Positions are missing");
  90068. }
  90069. var target = morphTargetManager.getTarget(index);
  90070. target.setPositions(vertexData.positions);
  90071. target.setNormals(vertexData.normals);
  90072. target.setTangents(vertexData.tangents);
  90073. }
  90074. });
  90075. };
  90076. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  90077. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  90078. var _loop_4 = function (primitive) {
  90079. var targets = primitive.targets;
  90080. primitive.targetsVertexData = new Array(targets.length);
  90081. var _loop_5 = function (index) {
  90082. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  90083. primitive.targetsVertexData[index] = vertexData;
  90084. if (--numRemainingTargets === 0) {
  90085. onSuccess();
  90086. }
  90087. });
  90088. };
  90089. for (var index = 0; index < targets.length; index++) {
  90090. _loop_5(index);
  90091. }
  90092. };
  90093. var this_4 = this;
  90094. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  90095. var primitive = _a[_i];
  90096. _loop_4(primitive);
  90097. }
  90098. };
  90099. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  90100. var targetVertexData = new BABYLON.VertexData();
  90101. var numRemainingAttributes = Object.keys(attributes).length;
  90102. var _loop_6 = function (attribute) {
  90103. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  90104. if (!accessor) {
  90105. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  90106. }
  90107. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  90108. // glTF stores morph target information as deltas while babylon.js expects the final data.
  90109. // As a result we have to add the original data to the delta to calculate the final data.
  90110. var values = data;
  90111. switch (attribute) {
  90112. case "POSITION": {
  90113. for (var i = 0; i < values.length; i++) {
  90114. values[i] += vertexData.positions[i];
  90115. }
  90116. targetVertexData.positions = values;
  90117. break;
  90118. }
  90119. case "NORMAL": {
  90120. for (var i = 0; i < values.length; i++) {
  90121. values[i] += vertexData.normals[i];
  90122. }
  90123. targetVertexData.normals = values;
  90124. break;
  90125. }
  90126. case "TANGENT": {
  90127. // Tangent data for morph targets is stored as xyz delta.
  90128. // The vertexData.tangent is stored as xyzw.
  90129. // So we need to skip every fourth vertexData.tangent.
  90130. for (var i = 0, j = 0; i < values.length; i++, j++) {
  90131. values[i] += vertexData.tangents[j];
  90132. if ((i + 1) % 3 == 0) {
  90133. j++;
  90134. }
  90135. }
  90136. targetVertexData.tangents = values;
  90137. break;
  90138. }
  90139. default: {
  90140. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  90141. break;
  90142. }
  90143. }
  90144. if (--numRemainingAttributes === 0) {
  90145. onSuccess(targetVertexData);
  90146. }
  90147. });
  90148. };
  90149. var this_5 = this;
  90150. for (var attribute in attributes) {
  90151. _loop_6(attribute);
  90152. }
  90153. };
  90154. GLTFLoader.prototype._loadTransform = function (node) {
  90155. var position = BABYLON.Vector3.Zero();
  90156. var rotation = BABYLON.Quaternion.Identity();
  90157. var scaling = BABYLON.Vector3.One();
  90158. if (node.matrix) {
  90159. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  90160. matrix.decompose(scaling, rotation, position);
  90161. }
  90162. else {
  90163. if (node.translation)
  90164. position = BABYLON.Vector3.FromArray(node.translation);
  90165. if (node.rotation)
  90166. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  90167. if (node.scale)
  90168. scaling = BABYLON.Vector3.FromArray(node.scale);
  90169. }
  90170. node.babylonMesh.position = position;
  90171. node.babylonMesh.rotationQuaternion = rotation;
  90172. node.babylonMesh.scaling = scaling;
  90173. };
  90174. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  90175. var _this = this;
  90176. if (skin.babylonSkeleton) {
  90177. onSuccess();
  90178. return;
  90179. }
  90180. var skeletonId = "skeleton" + skin.index;
  90181. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  90182. if (skin.inverseBindMatrices == null) {
  90183. this._loadBones(context, skin, null);
  90184. onSuccess();
  90185. }
  90186. else {
  90187. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  90188. if (!accessor) {
  90189. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  90190. }
  90191. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  90192. _this._loadBones(context, skin, data);
  90193. onSuccess();
  90194. });
  90195. }
  90196. };
  90197. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  90198. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  90199. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  90200. node.babylonAnimationTargets.push(babylonBone);
  90201. return babylonBone;
  90202. };
  90203. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  90204. var babylonBones = {};
  90205. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  90206. var index = _a[_i];
  90207. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  90208. if (!node) {
  90209. throw new Error(context + ": Failed to find joint " + index);
  90210. }
  90211. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  90212. }
  90213. };
  90214. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  90215. var babylonBone = babylonBones[node.index];
  90216. if (babylonBone) {
  90217. return babylonBone;
  90218. }
  90219. var boneIndex = skin.joints.indexOf(node.index);
  90220. var baseMatrix = BABYLON.Matrix.Identity();
  90221. if (inverseBindMatrixData && boneIndex !== -1) {
  90222. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  90223. baseMatrix.invertToRef(baseMatrix);
  90224. }
  90225. var babylonParentBone = null;
  90226. if (node.parent !== this._rootNode) {
  90227. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  90228. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  90229. }
  90230. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  90231. babylonBones[node.index] = babylonBone;
  90232. return babylonBone;
  90233. };
  90234. GLTFLoader.prototype._getNodeMatrix = function (node) {
  90235. return node.matrix ?
  90236. BABYLON.Matrix.FromArray(node.matrix) :
  90237. 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());
  90238. };
  90239. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  90240. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  90241. var index = indices_1[_i];
  90242. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  90243. if (!node) {
  90244. throw new Error(context + ": Failed to find node " + index);
  90245. }
  90246. this._traverseNode(context, node, action, parentNode);
  90247. }
  90248. };
  90249. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  90250. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  90251. return;
  90252. }
  90253. if (!action(node, parentNode)) {
  90254. return;
  90255. }
  90256. if (node.children) {
  90257. this._traverseNodes(context, node.children, action, node);
  90258. }
  90259. };
  90260. GLTFLoader.prototype._loadAnimations = function () {
  90261. var animations = this._gltf.animations;
  90262. if (!animations) {
  90263. return;
  90264. }
  90265. for (var index = 0; index < animations.length; index++) {
  90266. var animation = animations[index];
  90267. this._loadAnimation("#/animations/" + index, animation);
  90268. }
  90269. };
  90270. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  90271. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  90272. for (var index = 0; index < animation.channels.length; index++) {
  90273. var channel = GLTFLoader._GetProperty(animation.channels, index);
  90274. if (!channel) {
  90275. throw new Error(context + ": Failed to find channel " + index);
  90276. }
  90277. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  90278. if (!sampler) {
  90279. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  90280. }
  90281. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  90282. }
  90283. };
  90284. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  90285. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  90286. if (!targetNode) {
  90287. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  90288. }
  90289. var targetPath;
  90290. var animationType;
  90291. switch (channel.target.path) {
  90292. case "translation": {
  90293. targetPath = "position";
  90294. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90295. break;
  90296. }
  90297. case "rotation": {
  90298. targetPath = "rotationQuaternion";
  90299. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90300. break;
  90301. }
  90302. case "scale": {
  90303. targetPath = "scaling";
  90304. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90305. break;
  90306. }
  90307. case "weights": {
  90308. targetPath = "influence";
  90309. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  90310. break;
  90311. }
  90312. default: {
  90313. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  90314. }
  90315. }
  90316. var inputData;
  90317. var outputData;
  90318. var checkSuccess = function () {
  90319. if (!inputData || !outputData) {
  90320. return;
  90321. }
  90322. var outputBufferOffset = 0;
  90323. var getNextOutputValue;
  90324. switch (targetPath) {
  90325. case "position": {
  90326. getNextOutputValue = function () {
  90327. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  90328. outputBufferOffset += 3;
  90329. return value;
  90330. };
  90331. break;
  90332. }
  90333. case "rotationQuaternion": {
  90334. getNextOutputValue = function () {
  90335. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  90336. outputBufferOffset += 4;
  90337. return value;
  90338. };
  90339. break;
  90340. }
  90341. case "scaling": {
  90342. getNextOutputValue = function () {
  90343. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  90344. outputBufferOffset += 3;
  90345. return value;
  90346. };
  90347. break;
  90348. }
  90349. case "influence": {
  90350. getNextOutputValue = function () {
  90351. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  90352. var value = new Array(numTargets);
  90353. for (var i = 0; i < numTargets; i++) {
  90354. value[i] = outputData[outputBufferOffset++];
  90355. }
  90356. return value;
  90357. };
  90358. break;
  90359. }
  90360. }
  90361. sampler.interpolation = sampler.interpolation || "LINEAR";
  90362. var getNextKey;
  90363. switch (sampler.interpolation) {
  90364. case "STEP": {
  90365. getNextKey = function (frameIndex) { return ({
  90366. frame: inputData[frameIndex],
  90367. value: getNextOutputValue(),
  90368. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  90369. }); };
  90370. break;
  90371. }
  90372. case "LINEAR": {
  90373. getNextKey = function (frameIndex) { return ({
  90374. frame: inputData[frameIndex],
  90375. value: getNextOutputValue()
  90376. }); };
  90377. break;
  90378. }
  90379. case "CUBICSPLINE": {
  90380. getNextKey = function (frameIndex) { return ({
  90381. frame: inputData[frameIndex],
  90382. inTangent: getNextOutputValue(),
  90383. value: getNextOutputValue(),
  90384. outTangent: getNextOutputValue()
  90385. }); };
  90386. break;
  90387. }
  90388. default: {
  90389. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  90390. }
  90391. }
  90392. ;
  90393. var keys;
  90394. if (inputData.length === 1) {
  90395. var key = getNextKey(0);
  90396. keys = [
  90397. { frame: key.frame, value: key.value },
  90398. { frame: key.frame + 1, value: key.value }
  90399. ];
  90400. }
  90401. else {
  90402. keys = new Array(inputData.length);
  90403. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  90404. keys[frameIndex] = getNextKey(frameIndex);
  90405. }
  90406. }
  90407. if (targetPath === "influence") {
  90408. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  90409. var _loop_7 = function (targetIndex) {
  90410. var morphTarget = morphTargetManager.getTarget(targetIndex);
  90411. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  90412. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  90413. babylonAnimation.setKeys(keys.map(function (key) { return ({
  90414. frame: key.frame,
  90415. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  90416. value: key.value[targetIndex],
  90417. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  90418. }); }));
  90419. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  90420. };
  90421. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  90422. _loop_7(targetIndex);
  90423. }
  90424. }
  90425. else {
  90426. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  90427. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  90428. babylonAnimation.setKeys(keys);
  90429. if (targetNode.babylonAnimationTargets) {
  90430. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  90431. var target = _a[_i];
  90432. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  90433. }
  90434. }
  90435. }
  90436. };
  90437. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  90438. if (!inputAccessor) {
  90439. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  90440. }
  90441. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  90442. inputData = data;
  90443. checkSuccess();
  90444. });
  90445. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  90446. if (!outputAccessor) {
  90447. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  90448. }
  90449. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  90450. outputData = data;
  90451. checkSuccess();
  90452. });
  90453. };
  90454. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  90455. var _this = this;
  90456. this._addPendingData(buffer);
  90457. if (buffer.loadedData) {
  90458. onSuccess(buffer.loadedData);
  90459. this._removePendingData(buffer);
  90460. }
  90461. else if (buffer.loadedObservable) {
  90462. buffer.loadedObservable.add(function (buffer) {
  90463. onSuccess(buffer.loadedData);
  90464. _this._removePendingData(buffer);
  90465. });
  90466. }
  90467. else {
  90468. if (!buffer.uri) {
  90469. throw new Error(context + ": Uri is missing");
  90470. }
  90471. buffer.loadedObservable = new BABYLON.Observable();
  90472. buffer.loadedObservable.add(function (buffer) {
  90473. onSuccess(buffer.loadedData);
  90474. _this._removePendingData(buffer);
  90475. });
  90476. this._loadUriAsync(context, buffer.uri, function (data) {
  90477. buffer.loadedData = data;
  90478. buffer.loadedObservable.notifyObservers(buffer);
  90479. buffer.loadedObservable = undefined;
  90480. });
  90481. }
  90482. };
  90483. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  90484. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  90485. if (!buffer) {
  90486. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  90487. }
  90488. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  90489. var data;
  90490. try {
  90491. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  90492. }
  90493. catch (e) {
  90494. throw new Error(context + ": " + e.message);
  90495. }
  90496. onSuccess(data);
  90497. });
  90498. };
  90499. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  90500. var _this = this;
  90501. if (accessor.sparse) {
  90502. throw new Error(context + ": Sparse accessors are not currently supported");
  90503. }
  90504. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  90505. if (!bufferView) {
  90506. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  90507. }
  90508. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  90509. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  90510. var data;
  90511. var byteOffset = accessor.byteOffset || 0;
  90512. var byteStride = bufferView.byteStride;
  90513. if (byteStride === 0) {
  90514. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  90515. }
  90516. try {
  90517. switch (accessor.componentType) {
  90518. case GLTF2.EComponentType.BYTE: {
  90519. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90520. break;
  90521. }
  90522. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  90523. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90524. break;
  90525. }
  90526. case GLTF2.EComponentType.SHORT: {
  90527. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90528. break;
  90529. }
  90530. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  90531. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90532. break;
  90533. }
  90534. case GLTF2.EComponentType.UNSIGNED_INT: {
  90535. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90536. break;
  90537. }
  90538. case GLTF2.EComponentType.FLOAT: {
  90539. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90540. break;
  90541. }
  90542. default: {
  90543. throw new Error(context + ": Invalid component type " + accessor.componentType);
  90544. }
  90545. }
  90546. }
  90547. catch (e) {
  90548. throw new Error(context + ": " + e);
  90549. }
  90550. onSuccess(data);
  90551. });
  90552. };
  90553. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  90554. byteOffset += data.byteOffset;
  90555. var targetLength = count * numComponents;
  90556. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  90557. return new typedArray(data.buffer, byteOffset, targetLength);
  90558. }
  90559. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  90560. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  90561. var targetBuffer = new typedArray(targetLength);
  90562. var sourceIndex = 0;
  90563. var targetIndex = 0;
  90564. while (targetIndex < targetLength) {
  90565. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  90566. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  90567. targetIndex++;
  90568. }
  90569. sourceIndex += elementStride;
  90570. }
  90571. return targetBuffer;
  90572. };
  90573. GLTFLoader.prototype._addPendingData = function (data) {
  90574. if (!this._renderReady) {
  90575. this._renderPendingCount++;
  90576. }
  90577. this._addLoaderPendingData(data);
  90578. };
  90579. GLTFLoader.prototype._removePendingData = function (data) {
  90580. var _this = this;
  90581. if (!this._renderReady) {
  90582. if (--this._renderPendingCount === 0) {
  90583. this._addLoaderPendingData(this);
  90584. this._compileMaterialsAsync(function () {
  90585. _this._compileShadowGeneratorsAsync(function () {
  90586. _this._removeLoaderPendingData(_this);
  90587. _this._renderReady = true;
  90588. _this._onRenderReady();
  90589. });
  90590. });
  90591. }
  90592. }
  90593. this._removeLoaderPendingData(data);
  90594. };
  90595. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  90596. this._loaderPendingCount++;
  90597. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  90598. var tracker = _a[_i];
  90599. tracker._addPendingData(data);
  90600. }
  90601. };
  90602. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  90603. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  90604. var tracker = _a[_i];
  90605. tracker._removePendingData(data);
  90606. }
  90607. if (--this._loaderPendingCount === 0) {
  90608. this._onComplete();
  90609. }
  90610. };
  90611. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  90612. var _this = this;
  90613. var tracker = new GLTFLoaderTracker(function () {
  90614. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  90615. onComplete();
  90616. });
  90617. this._loaderTrackers.push(tracker);
  90618. this._addLoaderPendingData(tracker);
  90619. action();
  90620. this._removeLoaderPendingData(tracker);
  90621. };
  90622. GLTFLoader.prototype._getDefaultMaterial = function () {
  90623. if (!this._defaultMaterial) {
  90624. var id = "__gltf_default";
  90625. var material = this._babylonScene.getMaterialByName(id);
  90626. if (!material) {
  90627. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  90628. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  90629. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  90630. material.metallic = 1;
  90631. material.roughness = 1;
  90632. }
  90633. this._defaultMaterial = material;
  90634. }
  90635. return this._defaultMaterial;
  90636. };
  90637. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  90638. var babylonMaterial = material.babylonMaterial;
  90639. // Ensure metallic workflow
  90640. babylonMaterial.metallic = 1;
  90641. babylonMaterial.roughness = 1;
  90642. var properties = material.pbrMetallicRoughness;
  90643. if (!properties) {
  90644. return;
  90645. }
  90646. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  90647. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  90648. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  90649. if (properties.baseColorTexture) {
  90650. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  90651. if (!texture) {
  90652. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  90653. }
  90654. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  90655. }
  90656. if (properties.metallicRoughnessTexture) {
  90657. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  90658. if (!texture) {
  90659. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  90660. }
  90661. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  90662. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  90663. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  90664. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  90665. }
  90666. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  90667. };
  90668. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  90669. if (material.babylonMaterial) {
  90670. assign(material.babylonMaterial, false);
  90671. return;
  90672. }
  90673. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  90674. return;
  90675. }
  90676. this._createPbrMaterial(material);
  90677. this._loadMaterialBaseProperties(context, material);
  90678. this._loadMaterialMetallicRoughnessProperties(context, material);
  90679. assign(material.babylonMaterial, true);
  90680. };
  90681. GLTFLoader.prototype._createPbrMaterial = function (material) {
  90682. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  90683. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  90684. material.babylonMaterial = babylonMaterial;
  90685. };
  90686. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  90687. var babylonMaterial = material.babylonMaterial;
  90688. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  90689. if (material.doubleSided) {
  90690. babylonMaterial.backFaceCulling = false;
  90691. babylonMaterial.twoSidedLighting = true;
  90692. }
  90693. if (material.normalTexture) {
  90694. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  90695. if (!texture) {
  90696. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  90697. }
  90698. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  90699. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  90700. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  90701. if (material.normalTexture.scale != null) {
  90702. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  90703. }
  90704. }
  90705. if (material.occlusionTexture) {
  90706. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  90707. if (!texture) {
  90708. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  90709. }
  90710. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  90711. babylonMaterial.useAmbientInGrayScale = true;
  90712. if (material.occlusionTexture.strength != null) {
  90713. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  90714. }
  90715. }
  90716. if (material.emissiveTexture) {
  90717. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  90718. if (!texture) {
  90719. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  90720. }
  90721. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  90722. }
  90723. };
  90724. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  90725. var babylonMaterial = material.babylonMaterial;
  90726. var alphaMode = material.alphaMode || "OPAQUE";
  90727. switch (alphaMode) {
  90728. case "OPAQUE": {
  90729. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  90730. break;
  90731. }
  90732. case "MASK": {
  90733. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  90734. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  90735. if (colorFactor) {
  90736. if (colorFactor[3] == 0) {
  90737. babylonMaterial.alphaCutOff = 1;
  90738. }
  90739. else {
  90740. babylonMaterial.alphaCutOff /= colorFactor[3];
  90741. }
  90742. }
  90743. if (babylonMaterial.albedoTexture) {
  90744. babylonMaterial.albedoTexture.hasAlpha = true;
  90745. }
  90746. break;
  90747. }
  90748. case "BLEND": {
  90749. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  90750. if (colorFactor) {
  90751. babylonMaterial.alpha = colorFactor[3];
  90752. }
  90753. if (babylonMaterial.albedoTexture) {
  90754. babylonMaterial.albedoTexture.hasAlpha = true;
  90755. babylonMaterial.useAlphaFromAlbedoTexture = true;
  90756. }
  90757. break;
  90758. }
  90759. default: {
  90760. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  90761. }
  90762. }
  90763. };
  90764. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  90765. var _this = this;
  90766. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  90767. if (!sampler) {
  90768. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  90769. }
  90770. this._loadSampler("#/samplers/" + sampler.index, sampler);
  90771. this._addPendingData(texture);
  90772. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  90773. _this._tryCatchOnError(function () {
  90774. _this._removePendingData(texture);
  90775. });
  90776. }, function (message) {
  90777. _this._tryCatchOnError(function () {
  90778. throw new Error(context + ": " + message);
  90779. });
  90780. });
  90781. if (texture.url) {
  90782. babylonTexture.updateURL(texture.url);
  90783. }
  90784. else if (texture.dataReadyObservable) {
  90785. texture.dataReadyObservable.add(function (texture) {
  90786. babylonTexture.updateURL(texture.url);
  90787. });
  90788. }
  90789. else {
  90790. texture.dataReadyObservable = new BABYLON.Observable();
  90791. texture.dataReadyObservable.add(function (texture) {
  90792. babylonTexture.updateURL(texture.url);
  90793. });
  90794. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  90795. if (!image_1) {
  90796. throw new Error(context + ": Failed to find source " + texture.source);
  90797. }
  90798. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  90799. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  90800. texture.dataReadyObservable.notifyObservers(texture);
  90801. texture.dataReadyObservable = undefined;
  90802. });
  90803. }
  90804. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  90805. babylonTexture.wrapU = sampler.wrapU;
  90806. babylonTexture.wrapV = sampler.wrapV;
  90807. babylonTexture.name = texture.name || "texture" + texture.index;
  90808. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  90809. return babylonTexture;
  90810. };
  90811. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  90812. if (sampler.noMipMaps != undefined) {
  90813. return;
  90814. }
  90815. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  90816. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  90817. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  90818. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  90819. };
  90820. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  90821. if (image.uri) {
  90822. this._loadUriAsync(context, image.uri, onSuccess);
  90823. }
  90824. else {
  90825. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  90826. if (!bufferView) {
  90827. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  90828. }
  90829. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  90830. }
  90831. };
  90832. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  90833. var _this = this;
  90834. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  90835. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  90836. return;
  90837. }
  90838. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  90839. throw new Error(context + ": Uri '" + uri + "' is invalid");
  90840. }
  90841. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  90842. _this._tryCatchOnError(function () {
  90843. onSuccess(new Uint8Array(data));
  90844. });
  90845. }, function (event) {
  90846. _this._tryCatchOnError(function () {
  90847. if (request && !_this._renderReady) {
  90848. request._lengthComputable = event.lengthComputable;
  90849. request._loaded = event.loaded;
  90850. request._total = event.total;
  90851. _this._onProgress();
  90852. }
  90853. });
  90854. }, this._babylonScene.database, true, function (request, exception) {
  90855. _this._tryCatchOnError(function () {
  90856. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  90857. });
  90858. });
  90859. this._requests.push(request);
  90860. };
  90861. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  90862. if (this._disposed) {
  90863. return;
  90864. }
  90865. try {
  90866. handler();
  90867. }
  90868. catch (e) {
  90869. BABYLON.Tools.Error("glTF Loader: " + e.message);
  90870. if (this._errorCallback) {
  90871. this._errorCallback(e.message, e);
  90872. }
  90873. this.dispose();
  90874. }
  90875. };
  90876. GLTFLoader._AssignIndices = function (array) {
  90877. if (array) {
  90878. for (var index = 0; index < array.length; index++) {
  90879. array[index].index = index;
  90880. }
  90881. }
  90882. };
  90883. GLTFLoader._GetProperty = function (array, index) {
  90884. if (!array || index == undefined || !array[index]) {
  90885. return null;
  90886. }
  90887. return array[index];
  90888. };
  90889. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  90890. // Set defaults if undefined
  90891. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  90892. switch (mode) {
  90893. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90894. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90895. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90896. default:
  90897. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  90898. return BABYLON.Texture.WRAP_ADDRESSMODE;
  90899. }
  90900. };
  90901. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  90902. // Set defaults if undefined
  90903. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  90904. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  90905. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  90906. switch (minFilter) {
  90907. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  90908. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  90909. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  90910. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  90911. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  90912. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  90913. default:
  90914. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  90915. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  90916. }
  90917. }
  90918. else {
  90919. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  90920. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  90921. }
  90922. switch (minFilter) {
  90923. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  90924. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  90925. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  90926. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  90927. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  90928. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  90929. default:
  90930. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  90931. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  90932. }
  90933. }
  90934. };
  90935. GLTFLoader._GetNumComponents = function (context, type) {
  90936. switch (type) {
  90937. case "SCALAR": return 1;
  90938. case "VEC2": return 2;
  90939. case "VEC3": return 3;
  90940. case "VEC4": return 4;
  90941. case "MAT2": return 4;
  90942. case "MAT3": return 9;
  90943. case "MAT4": return 16;
  90944. }
  90945. throw new Error(context + ": Invalid type " + type);
  90946. };
  90947. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  90948. var _this = this;
  90949. if (this.useClipPlane) {
  90950. babylonMaterial.forceCompilation(babylonMesh, function () {
  90951. babylonMaterial.forceCompilation(babylonMesh, function () {
  90952. _this._tryCatchOnError(onSuccess);
  90953. }, { clipPlane: true });
  90954. });
  90955. }
  90956. else {
  90957. babylonMaterial.forceCompilation(babylonMesh, function () {
  90958. _this._tryCatchOnError(onSuccess);
  90959. });
  90960. }
  90961. };
  90962. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  90963. if (!this.compileMaterials || !this._gltf.materials) {
  90964. onSuccess();
  90965. return;
  90966. }
  90967. var meshes = this._getMeshes();
  90968. var remaining = 0;
  90969. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  90970. var mesh = meshes_1[_i];
  90971. if (mesh.material instanceof BABYLON.MultiMaterial) {
  90972. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  90973. var subMaterial = _b[_a];
  90974. if (subMaterial) {
  90975. remaining++;
  90976. }
  90977. }
  90978. }
  90979. else if (mesh.material) {
  90980. remaining++;
  90981. }
  90982. }
  90983. if (remaining === 0) {
  90984. onSuccess();
  90985. return;
  90986. }
  90987. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  90988. var mesh = meshes_2[_c];
  90989. if (mesh.material instanceof BABYLON.MultiMaterial) {
  90990. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  90991. var subMaterial = _e[_d];
  90992. if (subMaterial) {
  90993. this._compileMaterialAsync(subMaterial, mesh, function () {
  90994. if (--remaining === 0) {
  90995. onSuccess();
  90996. }
  90997. });
  90998. }
  90999. }
  91000. }
  91001. else if (mesh.material) {
  91002. this._compileMaterialAsync(mesh.material, mesh, function () {
  91003. if (--remaining === 0) {
  91004. onSuccess();
  91005. }
  91006. });
  91007. }
  91008. }
  91009. };
  91010. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  91011. var _this = this;
  91012. if (!this.compileShadowGenerators) {
  91013. onSuccess();
  91014. return;
  91015. }
  91016. var lights = this._babylonScene.lights;
  91017. var remaining = 0;
  91018. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  91019. var light = lights_1[_i];
  91020. var generator = light.getShadowGenerator();
  91021. if (generator) {
  91022. remaining++;
  91023. }
  91024. }
  91025. if (remaining === 0) {
  91026. onSuccess();
  91027. return;
  91028. }
  91029. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  91030. var light = lights_2[_a];
  91031. var generator = light.getShadowGenerator();
  91032. if (generator) {
  91033. generator.forceCompilation(function () {
  91034. if (--remaining === 0) {
  91035. _this._tryCatchOnError(onSuccess);
  91036. }
  91037. });
  91038. }
  91039. }
  91040. };
  91041. GLTFLoader.prototype._abortRequests = function () {
  91042. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91043. var request = _a[_i];
  91044. request.abort();
  91045. }
  91046. this._requests.length = 0;
  91047. };
  91048. GLTFLoader.prototype._releaseResources = function () {
  91049. if (this._gltf.textures) {
  91050. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  91051. var texture = _a[_i];
  91052. if (texture.url) {
  91053. URL.revokeObjectURL(texture.url);
  91054. texture.url = undefined;
  91055. }
  91056. }
  91057. }
  91058. };
  91059. GLTFLoader.Extensions = {};
  91060. return GLTFLoader;
  91061. }());
  91062. GLTF2.GLTFLoader = GLTFLoader;
  91063. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  91064. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91065. })(BABYLON || (BABYLON = {}));
  91066. //# sourceMappingURL=babylon.glTFLoader.js.map
  91067. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91068. var BABYLON;
  91069. (function (BABYLON) {
  91070. var GLTF2;
  91071. (function (GLTF2) {
  91072. /**
  91073. * Utils functions for GLTF
  91074. */
  91075. var GLTFUtils = /** @class */ (function () {
  91076. function GLTFUtils() {
  91077. }
  91078. /**
  91079. * If the uri is a base64 string
  91080. * @param uri: the uri to test
  91081. */
  91082. GLTFUtils.IsBase64 = function (uri) {
  91083. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  91084. };
  91085. /**
  91086. * Decode the base64 uri
  91087. * @param uri: the uri to decode
  91088. */
  91089. GLTFUtils.DecodeBase64 = function (uri) {
  91090. var decodedString = atob(uri.split(",")[1]);
  91091. var bufferLength = decodedString.length;
  91092. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  91093. for (var i = 0; i < bufferLength; i++) {
  91094. bufferView[i] = decodedString.charCodeAt(i);
  91095. }
  91096. return bufferView.buffer;
  91097. };
  91098. GLTFUtils.ValidateUri = function (uri) {
  91099. return (uri.indexOf("..") === -1);
  91100. };
  91101. return GLTFUtils;
  91102. }());
  91103. GLTF2.GLTFUtils = GLTFUtils;
  91104. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91105. })(BABYLON || (BABYLON = {}));
  91106. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  91107. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91108. var BABYLON;
  91109. (function (BABYLON) {
  91110. var GLTF2;
  91111. (function (GLTF2) {
  91112. var GLTFLoaderExtension = /** @class */ (function () {
  91113. function GLTFLoaderExtension() {
  91114. this.enabled = true;
  91115. }
  91116. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  91117. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  91118. GLTFLoaderExtension.prototype._loadRoot = function (loader, context, root) { return false; };
  91119. GLTFLoaderExtension.prototype._loadScene = function (loader, context, scene) { return false; };
  91120. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  91121. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  91122. var _this = this;
  91123. if (!property.extensions) {
  91124. return false;
  91125. }
  91126. var extension = property.extensions[this.name];
  91127. if (!extension) {
  91128. return false;
  91129. }
  91130. // Clear out the extension before executing the action to avoid recursing into the same property.
  91131. property.extensions[this.name] = undefined;
  91132. action(context + "extensions/" + this.name, extension, function () {
  91133. // Restore the extension after completing the action.
  91134. property.extensions[_this.name] = extension;
  91135. });
  91136. return true;
  91137. };
  91138. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  91139. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  91140. };
  91141. GLTFLoaderExtension.LoadRoot = function (loader, context, root) {
  91142. return this._ApplyExtensions(function (extension) { return extension._loadRoot(loader, context, root); });
  91143. };
  91144. GLTFLoaderExtension.LoadScene = function (loader, context, scene) {
  91145. return this._ApplyExtensions(function (extension) { return extension._loadScene(loader, context, scene); });
  91146. };
  91147. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  91148. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  91149. };
  91150. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  91151. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  91152. };
  91153. GLTFLoaderExtension._ApplyExtensions = function (action) {
  91154. var extensions = GLTFLoaderExtension._Extensions;
  91155. if (!extensions) {
  91156. return false;
  91157. }
  91158. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  91159. var extension = extensions_1[_i];
  91160. if (extension.enabled && action(extension)) {
  91161. return true;
  91162. }
  91163. }
  91164. return false;
  91165. };
  91166. //
  91167. // Utilities
  91168. //
  91169. GLTFLoaderExtension._Extensions = [];
  91170. return GLTFLoaderExtension;
  91171. }());
  91172. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  91173. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91174. })(BABYLON || (BABYLON = {}));
  91175. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  91176. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  91177. var BABYLON;
  91178. (function (BABYLON) {
  91179. var GLTF2;
  91180. (function (GLTF2) {
  91181. var Extensions;
  91182. (function (Extensions) {
  91183. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  91184. var MSFTLOD = /** @class */ (function (_super) {
  91185. __extends(MSFTLOD, _super);
  91186. function MSFTLOD() {
  91187. var _this = _super !== null && _super.apply(this, arguments) || this;
  91188. /**
  91189. * Specify the minimal delay between LODs in ms (default = 250)
  91190. */
  91191. _this.Delay = 250;
  91192. return _this;
  91193. }
  91194. Object.defineProperty(MSFTLOD.prototype, "name", {
  91195. get: function () {
  91196. return "MSFT_lod";
  91197. },
  91198. enumerable: true,
  91199. configurable: true
  91200. });
  91201. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  91202. return this._loadExtension(context, node, function (context, extension, onComplete) {
  91203. for (var i = extension.ids.length - 1; i >= 0; i--) {
  91204. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  91205. if (!lodNode) {
  91206. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  91207. }
  91208. loader._traverseNode(context, lodNode, action, parentNode);
  91209. }
  91210. loader._traverseNode(context, node, action, parentNode);
  91211. onComplete();
  91212. });
  91213. };
  91214. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  91215. var _this = this;
  91216. return this._loadExtension(context, node, function (context, extension, onComplete) {
  91217. var nodes = [node];
  91218. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  91219. var index = _a[_i];
  91220. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  91221. if (!lodNode) {
  91222. throw new Error(context + ": Failed to find node " + index);
  91223. }
  91224. nodes.push(lodNode);
  91225. }
  91226. loader._addLoaderPendingData(node);
  91227. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  91228. loader._removeLoaderPendingData(node);
  91229. onComplete();
  91230. });
  91231. });
  91232. };
  91233. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  91234. var _this = this;
  91235. loader._whenAction(function () {
  91236. loader._loadNode(context, nodes[index]);
  91237. }, function () {
  91238. if (index !== nodes.length - 1) {
  91239. var previousNode = nodes[index + 1];
  91240. previousNode.babylonMesh.setEnabled(false);
  91241. }
  91242. if (index === 0) {
  91243. onComplete();
  91244. return;
  91245. }
  91246. setTimeout(function () {
  91247. loader._tryCatchOnError(function () {
  91248. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  91249. });
  91250. }, _this.Delay);
  91251. });
  91252. };
  91253. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  91254. var _this = this;
  91255. return this._loadExtension(context, material, function (context, extension, onComplete) {
  91256. var materials = [material];
  91257. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  91258. var index = _a[_i];
  91259. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  91260. if (!lodMaterial) {
  91261. throw new Error(context + ": Failed to find material " + index);
  91262. }
  91263. materials.push(lodMaterial);
  91264. }
  91265. loader._addLoaderPendingData(material);
  91266. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  91267. loader._removeLoaderPendingData(material);
  91268. onComplete();
  91269. });
  91270. });
  91271. };
  91272. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  91273. var _this = this;
  91274. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  91275. if (index === materials.length - 1) {
  91276. assign(babylonMaterial, isNew);
  91277. // Load the next LOD when the loader is ready to render.
  91278. loader._executeWhenRenderReady(function () {
  91279. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  91280. });
  91281. }
  91282. else {
  91283. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  91284. assign(babylonMaterial, isNew);
  91285. if (index === 0) {
  91286. onComplete();
  91287. }
  91288. else {
  91289. setTimeout(function () {
  91290. loader._tryCatchOnError(function () {
  91291. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  91292. });
  91293. }, _this.Delay);
  91294. }
  91295. });
  91296. }
  91297. });
  91298. };
  91299. return MSFTLOD;
  91300. }(GLTF2.GLTFLoaderExtension));
  91301. Extensions.MSFTLOD = MSFTLOD;
  91302. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  91303. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  91304. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91305. })(BABYLON || (BABYLON = {}));
  91306. //# sourceMappingURL=MSFT_lod.js.map
  91307. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  91308. var BABYLON;
  91309. (function (BABYLON) {
  91310. var GLTF2;
  91311. (function (GLTF2) {
  91312. var Extensions;
  91313. (function (Extensions) {
  91314. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  91315. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  91316. function KHRMaterialsPbrSpecularGlossiness() {
  91317. return _super !== null && _super.apply(this, arguments) || this;
  91318. }
  91319. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  91320. get: function () {
  91321. return "KHR_materials_pbrSpecularGlossiness";
  91322. },
  91323. enumerable: true,
  91324. configurable: true
  91325. });
  91326. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  91327. var _this = this;
  91328. return this._loadExtension(context, material, function (context, extension, onComplete) {
  91329. loader._createPbrMaterial(material);
  91330. loader._loadMaterialBaseProperties(context, material);
  91331. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  91332. assign(material.babylonMaterial, true);
  91333. onComplete();
  91334. });
  91335. };
  91336. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  91337. var babylonMaterial = material.babylonMaterial;
  91338. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  91339. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  91340. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  91341. if (properties.diffuseTexture) {
  91342. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  91343. if (!texture) {
  91344. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  91345. }
  91346. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  91347. }
  91348. if (properties.specularGlossinessTexture) {
  91349. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  91350. if (!texture) {
  91351. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  91352. }
  91353. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  91354. babylonMaterial.reflectivityTexture.hasAlpha = true;
  91355. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  91356. }
  91357. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  91358. };
  91359. return KHRMaterialsPbrSpecularGlossiness;
  91360. }(GLTF2.GLTFLoaderExtension));
  91361. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  91362. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  91363. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  91364. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91365. })(BABYLON || (BABYLON = {}));
  91366. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  91367. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  91368. var BABYLON;
  91369. (function (BABYLON) {
  91370. var GLTF2;
  91371. (function (GLTF2) {
  91372. var Extensions;
  91373. (function (Extensions) {
  91374. var KHRLights = /** @class */ (function (_super) {
  91375. __extends(KHRLights, _super);
  91376. function KHRLights() {
  91377. return _super !== null && _super.apply(this, arguments) || this;
  91378. }
  91379. Object.defineProperty(KHRLights.prototype, "name", {
  91380. get: function () {
  91381. return "KHR_lights";
  91382. },
  91383. enumerable: true,
  91384. configurable: true
  91385. });
  91386. KHRLights.prototype.applyCommonProperties = function (light, lightInfo) {
  91387. if (lightInfo.color) {
  91388. light.diffuse.copyFromFloats(lightInfo.color[0], lightInfo.color[1], lightInfo.color[2]);
  91389. }
  91390. else {
  91391. light.diffuse.copyFromFloats(1, 1, 1);
  91392. }
  91393. if (lightInfo.intensity !== undefined) {
  91394. light.intensity = lightInfo.intensity;
  91395. }
  91396. else {
  91397. light.intensity = 1;
  91398. }
  91399. };
  91400. KHRLights.prototype._loadScene = function (loader, context, scene) {
  91401. return this._loadExtension(context, scene, function (context, extension, onComplete) {
  91402. if (extension.light >= 0 && loader._gltf.extensions) {
  91403. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  91404. if (lightInfo.type !== 'ambient') {
  91405. return;
  91406. }
  91407. var lightColor = lightInfo.color ? lightInfo.color : [1, 1, 1];
  91408. loader._babylonScene.ambientColor.copyFromFloats(lightColor[0], lightColor[1], lightColor[2]);
  91409. }
  91410. onComplete();
  91411. });
  91412. };
  91413. KHRLights.prototype._loadNode = function (loader, context, node) {
  91414. var _this = this;
  91415. return this._loadExtension(context, node, function (context, extension, onComplete) {
  91416. if (extension.light >= 0 && loader._gltf.extensions) {
  91417. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  91418. var name_1 = node.name || 'Light';
  91419. var matrix = void 0;
  91420. if (node.matrix) {
  91421. matrix = BABYLON.Matrix.FromArray(node.matrix);
  91422. }
  91423. else {
  91424. matrix = BABYLON.Matrix.Identity();
  91425. }
  91426. var direction = new BABYLON.Vector3(0, 0, 1);
  91427. if (lightInfo.type == 'directional' || lightInfo.type == 'spot') {
  91428. var rotationMatrix = matrix.getRotationMatrix();
  91429. BABYLON.Vector3.TransformCoordinatesToRef(direction, rotationMatrix, direction);
  91430. }
  91431. var light = void 0;
  91432. if (lightInfo.type == 'directional') {
  91433. light = new BABYLON.DirectionalLight(name_1, direction, loader._babylonScene);
  91434. }
  91435. else {
  91436. var position = matrix.getTranslation();
  91437. if (lightInfo.type == 'spot') {
  91438. var angle = lightInfo.spot && lightInfo.spot.outerConeAngle ? lightInfo.spot.outerConeAngle : Math.PI / 2;
  91439. light = new BABYLON.SpotLight(name_1, position, direction, angle, 2, loader._babylonScene);
  91440. }
  91441. else {
  91442. light = new BABYLON.PointLight(name_1, position, loader._babylonScene);
  91443. }
  91444. }
  91445. _this.applyCommonProperties(light, lightInfo);
  91446. extension.babylonLight = light;
  91447. extension.babylonLight.parent = node.parent ? node.parent.babylonMesh : null;
  91448. if (node.children) {
  91449. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  91450. var index = _a[_i];
  91451. var childNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  91452. if (!childNode) {
  91453. throw new Error(context + ": Failed to find child node " + index);
  91454. }
  91455. loader._loadNode("#/nodes/" + index, childNode);
  91456. }
  91457. }
  91458. }
  91459. onComplete();
  91460. });
  91461. };
  91462. KHRLights.prototype._loadRoot = function (loader, context, root) {
  91463. return this._loadExtension(context, root, function (context, extension, onComplete) {
  91464. extension.lights.forEach(function (light, idx) {
  91465. light.index = idx;
  91466. });
  91467. onComplete();
  91468. });
  91469. };
  91470. return KHRLights;
  91471. }(GLTF2.GLTFLoaderExtension));
  91472. Extensions.KHRLights = KHRLights;
  91473. GLTF2.GLTFLoader.RegisterExtension(new KHRLights());
  91474. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  91475. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91476. })(BABYLON || (BABYLON = {}));
  91477. //# sourceMappingURL=KHR_lights.js.map
  91478. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91479. globalObject["BABYLON"] = BABYLON;
  91480. 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 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 HighlightLayer = BABYLON.HighlightLayer;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;
  91481. 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,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,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };